blob: 4b5c68a7bde8cc65b5da7ef2c0e703e456972bfc [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
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000238static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
Fangrui Song99337e22018-07-20 08:19:20 +0000239 CallExpr *TheCall, unsigned SizeIdx,
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000240 unsigned DstSizeIdx,
241 StringRef LikelyMacroName) {
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000242 if (TheCall->getNumArgs() <= SizeIdx ||
243 TheCall->getNumArgs() <= DstSizeIdx)
244 return;
245
246 const Expr *SizeArg = TheCall->getArg(SizeIdx);
247 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
248
Fangrui Song407659a2018-11-30 23:41:18 +0000249 Expr::EvalResult SizeResult, DstSizeResult;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000250
251 // find out if both sizes are known at compile time
Fangrui Song407659a2018-11-30 23:41:18 +0000252 if (!SizeArg->EvaluateAsInt(SizeResult, S.Context) ||
253 !DstSizeArg->EvaluateAsInt(DstSizeResult, S.Context))
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000254 return;
255
Fangrui Song407659a2018-11-30 23:41:18 +0000256 llvm::APSInt Size = SizeResult.Val.getInt();
257 llvm::APSInt DstSize = DstSizeResult.Val.getInt();
258
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000259 if (Size.ule(DstSize))
260 return;
261
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000262 // Confirmed overflow, so generate the diagnostic.
263 StringRef FunctionName = FDecl->getName();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000264 SourceLocation SL = TheCall->getBeginLoc();
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000265 SourceManager &SM = S.getSourceManager();
266 // If we're in an expansion of a macro whose name corresponds to this builtin,
267 // use the simple macro name and location.
268 if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) ==
269 LikelyMacroName) {
270 FunctionName = LikelyMacroName;
271 SL = SM.getImmediateMacroCallerLoc(SL);
272 }
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000273
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000274 S.Diag(SL, diag::warn_memcpy_chk_overflow)
275 << FunctionName << DstSize.toString(/*Radix=*/10)
276 << Size.toString(/*Radix=*/10);
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000277}
278
Peter Collingbournef7706832014-12-12 23:41:25 +0000279static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
280 if (checkArgCount(S, BuiltinCall, 2))
281 return true;
282
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000283 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
Peter Collingbournef7706832014-12-12 23:41:25 +0000284 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
285 Expr *Call = BuiltinCall->getArg(0);
286 Expr *Chain = BuiltinCall->getArg(1);
287
288 if (Call->getStmtClass() != Stmt::CallExprClass) {
289 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
290 << Call->getSourceRange();
291 return true;
292 }
293
294 auto CE = cast<CallExpr>(Call);
295 if (CE->getCallee()->getType()->isBlockPointerType()) {
296 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
297 << Call->getSourceRange();
298 return true;
299 }
300
301 const Decl *TargetDecl = CE->getCalleeDecl();
302 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
303 if (FD->getBuiltinID()) {
304 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
305 << Call->getSourceRange();
306 return true;
307 }
308
309 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
310 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
311 << Call->getSourceRange();
312 return true;
313 }
314
315 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
316 if (ChainResult.isInvalid())
317 return true;
318 if (!ChainResult.get()->getType()->isPointerType()) {
319 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
320 << Chain->getSourceRange();
321 return true;
322 }
323
David Majnemerced8bdf2015-02-25 17:36:15 +0000324 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000325 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
326 QualType BuiltinTy = S.Context.getFunctionType(
327 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
328 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
329
330 Builtin =
331 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
332
333 BuiltinCall->setType(CE->getType());
334 BuiltinCall->setValueKind(CE->getValueKind());
335 BuiltinCall->setObjectKind(CE->getObjectKind());
336 BuiltinCall->setCallee(Builtin);
337 BuiltinCall->setArg(1, ChainResult.get());
338
339 return false;
340}
341
Reid Kleckner1d59f992015-01-22 01:36:17 +0000342static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
343 Scope::ScopeFlags NeededScopeFlags,
344 unsigned DiagID) {
345 // Scopes aren't available during instantiation. Fortunately, builtin
346 // functions cannot be template args so they cannot be formed through template
347 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000348 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000349 return false;
350
351 Scope *S = SemaRef.getCurScope();
352 while (S && !S->isSEHExceptScope())
353 S = S->getParent();
354 if (!S || !(S->getFlags() & NeededScopeFlags)) {
355 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
356 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
357 << DRE->getDecl()->getIdentifier();
358 return true;
359 }
360
361 return false;
362}
363
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000364static inline bool isBlockPointer(Expr *Arg) {
365 return Arg->getType()->isBlockPointerType();
366}
367
368/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
369/// void*, which is a requirement of device side enqueue.
370static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
371 const BlockPointerType *BPT =
372 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
373 ArrayRef<QualType> Params =
374 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
375 unsigned ArgCounter = 0;
376 bool IllegalParams = false;
377 // Iterate through the block parameters until either one is found that is not
378 // a local void*, or the block is valid.
379 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
380 I != E; ++I, ++ArgCounter) {
381 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
382 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
383 LangAS::opencl_local) {
384 // Get the location of the error. If a block literal has been passed
385 // (BlockExpr) then we can point straight to the offending argument,
386 // else we just point to the variable reference.
387 SourceLocation ErrorLoc;
388 if (isa<BlockExpr>(BlockArg)) {
389 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000390 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000391 } else if (isa<DeclRefExpr>(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000392 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000393 }
394 S.Diag(ErrorLoc,
395 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
396 IllegalParams = true;
397 }
398 }
399
400 return IllegalParams;
401}
402
Joey Gouly84ae3362017-07-31 15:15:59 +0000403static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
404 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000405 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
406 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
Joey Gouly84ae3362017-07-31 15:15:59 +0000407 return true;
408 }
409 return false;
410}
411
Joey Goulyfa76b492017-08-01 13:27:09 +0000412static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
413 if (checkArgCount(S, TheCall, 2))
414 return true;
415
416 if (checkOpenCLSubgroupExt(S, TheCall))
417 return true;
418
419 // First argument is an ndrange_t type.
420 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000421 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000422 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000423 << TheCall->getDirectCallee() << "'ndrange_t'";
424 return true;
425 }
426
427 Expr *BlockArg = TheCall->getArg(1);
428 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000429 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000430 << TheCall->getDirectCallee() << "block";
431 return true;
432 }
433 return checkOpenCLBlockArgs(S, BlockArg);
434}
435
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000436/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
437/// get_kernel_work_group_size
438/// and get_kernel_preferred_work_group_size_multiple builtin functions.
439static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
440 if (checkArgCount(S, TheCall, 1))
441 return true;
442
443 Expr *BlockArg = TheCall->getArg(0);
444 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000445 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000446 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000447 return true;
448 }
449 return checkOpenCLBlockArgs(S, BlockArg);
450}
451
Simon Pilgrim2c518802017-03-30 14:13:19 +0000452/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000453static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
454 const QualType &IntType);
455
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000456static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000457 unsigned Start, unsigned End) {
458 bool IllegalParams = false;
459 for (unsigned I = Start; I <= End; ++I)
460 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
461 S.Context.getSizeType());
462 return IllegalParams;
463}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000464
465/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
466/// 'local void*' parameter of passed block.
467static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
468 Expr *BlockArg,
469 unsigned NumNonVarArgs) {
470 const BlockPointerType *BPT =
471 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
472 unsigned NumBlockParams =
473 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
474 unsigned TotalNumArgs = TheCall->getNumArgs();
475
476 // For each argument passed to the block, a corresponding uint needs to
477 // be passed to describe the size of the local memory.
478 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000479 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000480 diag::err_opencl_enqueue_kernel_local_size_args);
481 return true;
482 }
483
484 // Check that the sizes of the local memory are specified by integers.
485 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
486 TotalNumArgs - 1);
487}
488
489/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
490/// overload formats specified in Table 6.13.17.1.
491/// int enqueue_kernel(queue_t queue,
492/// kernel_enqueue_flags_t flags,
493/// const ndrange_t ndrange,
494/// void (^block)(void))
495/// int enqueue_kernel(queue_t queue,
496/// kernel_enqueue_flags_t flags,
497/// const ndrange_t ndrange,
498/// uint num_events_in_wait_list,
499/// clk_event_t *event_wait_list,
500/// clk_event_t *event_ret,
501/// void (^block)(void))
502/// int enqueue_kernel(queue_t queue,
503/// kernel_enqueue_flags_t flags,
504/// const ndrange_t ndrange,
505/// void (^block)(local void*, ...),
506/// uint size0, ...)
507/// int enqueue_kernel(queue_t queue,
508/// kernel_enqueue_flags_t flags,
509/// const ndrange_t ndrange,
510/// uint num_events_in_wait_list,
511/// clk_event_t *event_wait_list,
512/// clk_event_t *event_ret,
513/// void (^block)(local void*, ...),
514/// uint size0, ...)
515static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
516 unsigned NumArgs = TheCall->getNumArgs();
517
518 if (NumArgs < 4) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000519 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000520 return true;
521 }
522
523 Expr *Arg0 = TheCall->getArg(0);
524 Expr *Arg1 = TheCall->getArg(1);
525 Expr *Arg2 = TheCall->getArg(2);
526 Expr *Arg3 = TheCall->getArg(3);
527
528 // First argument always needs to be a queue_t type.
529 if (!Arg0->getType()->isQueueT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000530 S.Diag(TheCall->getArg(0)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000531 diag::err_opencl_builtin_expected_type)
532 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000533 return true;
534 }
535
536 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
537 if (!Arg1->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000538 S.Diag(TheCall->getArg(1)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000539 diag::err_opencl_builtin_expected_type)
540 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000541 return true;
542 }
543
544 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000545 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000546 S.Diag(TheCall->getArg(2)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000547 diag::err_opencl_builtin_expected_type)
548 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000549 return true;
550 }
551
552 // With four arguments, there is only one form that the function could be
553 // called in: no events and no variable arguments.
554 if (NumArgs == 4) {
555 // check that the last argument is the right block type.
556 if (!isBlockPointer(Arg3)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000557 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000558 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000559 return true;
560 }
561 // we have a block type, check the prototype
562 const BlockPointerType *BPT =
563 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
564 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000565 S.Diag(Arg3->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000566 diag::err_opencl_enqueue_kernel_blocks_no_args);
567 return true;
568 }
569 return false;
570 }
571 // we can have block + varargs.
572 if (isBlockPointer(Arg3))
573 return (checkOpenCLBlockArgs(S, Arg3) ||
574 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
575 // last two cases with either exactly 7 args or 7 args and varargs.
576 if (NumArgs >= 7) {
577 // check common block argument.
578 Expr *Arg6 = TheCall->getArg(6);
579 if (!isBlockPointer(Arg6)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000580 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000581 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000582 return true;
583 }
584 if (checkOpenCLBlockArgs(S, Arg6))
585 return true;
586
587 // Forth argument has to be any integer type.
588 if (!Arg3->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000589 S.Diag(TheCall->getArg(3)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000590 diag::err_opencl_builtin_expected_type)
591 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000592 return true;
593 }
594 // check remaining common arguments.
595 Expr *Arg4 = TheCall->getArg(4);
596 Expr *Arg5 = TheCall->getArg(5);
597
Anastasia Stulova2b461202016-11-14 15:34:01 +0000598 // Fifth argument is always passed as a pointer to clk_event_t.
599 if (!Arg4->isNullPointerConstant(S.Context,
600 Expr::NPC_ValueDependentIsNotNull) &&
601 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000602 S.Diag(TheCall->getArg(4)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000603 diag::err_opencl_builtin_expected_type)
604 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000605 << S.Context.getPointerType(S.Context.OCLClkEventTy);
606 return true;
607 }
608
Anastasia Stulova2b461202016-11-14 15:34:01 +0000609 // Sixth argument is always passed as a pointer to clk_event_t.
610 if (!Arg5->isNullPointerConstant(S.Context,
611 Expr::NPC_ValueDependentIsNotNull) &&
612 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000613 Arg5->getType()->getPointeeType()->isClkEventT())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000614 S.Diag(TheCall->getArg(5)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000615 diag::err_opencl_builtin_expected_type)
616 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000617 << S.Context.getPointerType(S.Context.OCLClkEventTy);
618 return true;
619 }
620
621 if (NumArgs == 7)
622 return false;
623
624 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
625 }
626
627 // None of the specific case has been detected, give generic error
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000628 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000629 diag::err_opencl_enqueue_kernel_incorrect_args);
630 return true;
631}
632
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000633/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000634static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000635 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000636}
637
638/// Returns true if pipe element type is different from the pointer.
639static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
640 const Expr *Arg0 = Call->getArg(0);
641 // First argument type should always be pipe.
642 if (!Arg0->getType()->isPipeType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000643 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000644 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000645 return true;
646 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000647 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000648 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
649 // Validates the access qualifier is compatible with the call.
650 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
651 // read_only and write_only, and assumed to be read_only if no qualifier is
652 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000653 switch (Call->getDirectCallee()->getBuiltinID()) {
654 case Builtin::BIread_pipe:
655 case Builtin::BIreserve_read_pipe:
656 case Builtin::BIcommit_read_pipe:
657 case Builtin::BIwork_group_reserve_read_pipe:
658 case Builtin::BIsub_group_reserve_read_pipe:
659 case Builtin::BIwork_group_commit_read_pipe:
660 case Builtin::BIsub_group_commit_read_pipe:
661 if (!(!AccessQual || AccessQual->isReadOnly())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000662 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000663 diag::err_opencl_builtin_pipe_invalid_access_modifier)
664 << "read_only" << Arg0->getSourceRange();
665 return true;
666 }
667 break;
668 case Builtin::BIwrite_pipe:
669 case Builtin::BIreserve_write_pipe:
670 case Builtin::BIcommit_write_pipe:
671 case Builtin::BIwork_group_reserve_write_pipe:
672 case Builtin::BIsub_group_reserve_write_pipe:
673 case Builtin::BIwork_group_commit_write_pipe:
674 case Builtin::BIsub_group_commit_write_pipe:
675 if (!(AccessQual && AccessQual->isWriteOnly())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000676 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000677 diag::err_opencl_builtin_pipe_invalid_access_modifier)
678 << "write_only" << Arg0->getSourceRange();
679 return true;
680 }
681 break;
682 default:
683 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000684 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000685 return false;
686}
687
688/// Returns true if pipe element type is different from the pointer.
689static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
690 const Expr *Arg0 = Call->getArg(0);
691 const Expr *ArgIdx = Call->getArg(Idx);
692 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000693 const QualType EltTy = PipeTy->getElementType();
694 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000695 // The Idx argument should be a pointer and the type of the pointer and
696 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000697 if (!ArgTy ||
698 !S.Context.hasSameType(
699 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000700 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000701 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000702 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000703 return true;
704 }
705 return false;
706}
707
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000708// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000709// \param S Reference to the semantic analyzer.
710// \param Call A pointer to the builtin call.
711// \return True if a semantic error has been found, false otherwise.
712static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000713 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
714 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000715 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000716 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000717 if (checkOpenCLPipeArg(S, Call))
718 return true;
719 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000720 // read/write_pipe(pipe T, T*).
721 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000722 if (checkOpenCLPipePacketType(S, Call, 1))
723 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000724 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000725
726 case 4: {
727 if (checkOpenCLPipeArg(S, Call))
728 return true;
729 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000730 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
731 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000732 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000733 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000734 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000735 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000736 return true;
737 }
738
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000739 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000740 const Expr *Arg2 = Call->getArg(2);
741 if (!Arg2->getType()->isIntegerType() &&
742 !Arg2->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000743 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000744 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000745 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000746 return true;
747 }
748
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000749 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000750 if (checkOpenCLPipePacketType(S, Call, 3))
751 return true;
752 } break;
753 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000754 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000755 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000756 return true;
757 }
758
759 return false;
760}
761
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000762// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000763// /_}reserve_{read/write}_pipe
764// \param S Reference to the semantic analyzer.
765// \param Call The call to the builtin function to be analyzed.
766// \return True if a semantic error was found, false otherwise.
767static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
768 if (checkArgCount(S, Call, 2))
769 return true;
770
771 if (checkOpenCLPipeArg(S, Call))
772 return true;
773
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000774 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000775 if (!Call->getArg(1)->getType()->isIntegerType() &&
776 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000777 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000778 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000779 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000780 return true;
781 }
782
Joey Gouly922ca232017-08-09 14:52:47 +0000783 // Since return type of reserve_read/write_pipe built-in function is
Aaron Ballman68d50642018-06-19 14:53:20 +0000784 // reserve_id_t, which is not defined in the builtin def file , we used int
785 // as return type and need to override the return type of these functions.
786 Call->setType(S.Context.OCLReserveIDTy);
787
788 return false;
789}
790
791// Performs a semantic analysis on {work_group_/sub_group_
792// /_}commit_{read/write}_pipe
793// \param S Reference to the semantic analyzer.
794// \param Call The call to the builtin function to be analyzed.
795// \return True if a semantic error was found, false otherwise.
796static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
797 if (checkArgCount(S, Call, 2))
798 return true;
799
800 if (checkOpenCLPipeArg(S, Call))
801 return true;
802
803 // Check reserve_id_t.
804 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000805 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000806 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
807 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
808 return true;
809 }
810
811 return false;
812}
813
814// Performs a semantic analysis on the call to built-in Pipe
815// Query Functions.
816// \param S Reference to the semantic analyzer.
817// \param Call The call to the builtin function to be analyzed.
818// \return True if a semantic error was found, false otherwise.
819static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
820 if (checkArgCount(S, Call, 1))
821 return true;
822
823 if (!Call->getArg(0)->getType()->isPipeType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000824 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000825 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
826 return true;
827 }
828
829 return false;
830}
831
832// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
833// Performs semantic analysis for the to_global/local/private call.
834// \param S Reference to the semantic analyzer.
835// \param BuiltinID ID of the builtin function.
836// \param Call A pointer to the builtin call.
837// \return True if a semantic error has been found, false otherwise.
838static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
839 CallExpr *Call) {
840 if (Call->getNumArgs() != 1) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000841 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
Aaron Ballman68d50642018-06-19 14:53:20 +0000842 << Call->getDirectCallee() << Call->getSourceRange();
843 return true;
844 }
845
846 auto RT = Call->getArg(0)->getType();
847 if (!RT->isPointerType() || RT->getPointeeType()
848 .getAddressSpace() == LangAS::opencl_constant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000849 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000850 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
851 return true;
852 }
853
Sven van Haastregt1076cc22018-09-20 10:07:27 +0000854 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
855 S.Diag(Call->getArg(0)->getBeginLoc(),
856 diag::warn_opencl_generic_address_space_arg)
857 << Call->getDirectCallee()->getNameInfo().getAsString()
858 << Call->getArg(0)->getSourceRange();
859 }
860
Aaron Ballman68d50642018-06-19 14:53:20 +0000861 RT = RT->getPointeeType();
862 auto Qual = RT.getQualifiers();
863 switch (BuiltinID) {
864 case Builtin::BIto_global:
865 Qual.setAddressSpace(LangAS::opencl_global);
866 break;
867 case Builtin::BIto_local:
868 Qual.setAddressSpace(LangAS::opencl_local);
869 break;
870 case Builtin::BIto_private:
871 Qual.setAddressSpace(LangAS::opencl_private);
872 break;
873 default:
874 llvm_unreachable("Invalid builtin function");
875 }
876 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
877 RT.getUnqualifiedType(), Qual)));
878
879 return false;
880}
881
Eric Fiselier26187502018-12-14 21:11:28 +0000882static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
883 if (checkArgCount(S, TheCall, 1))
884 return ExprError();
885
886 // Compute __builtin_launder's parameter type from the argument.
887 // The parameter type is:
888 // * The type of the argument if it's not an array or function type,
889 // Otherwise,
890 // * The decayed argument type.
891 QualType ParamTy = [&]() {
892 QualType ArgTy = TheCall->getArg(0)->getType();
893 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
894 return S.Context.getPointerType(Ty->getElementType());
895 if (ArgTy->isFunctionType()) {
896 return S.Context.getPointerType(ArgTy);
897 }
898 return ArgTy;
899 }();
900
901 TheCall->setType(ParamTy);
902
903 auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
904 if (!ParamTy->isPointerType())
905 return 0;
906 if (ParamTy->isFunctionPointerType())
907 return 1;
908 if (ParamTy->isVoidPointerType())
909 return 2;
910 return llvm::Optional<unsigned>{};
911 }();
912 if (DiagSelect.hasValue()) {
913 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
914 << DiagSelect.getValue() << TheCall->getSourceRange();
915 return ExprError();
916 }
917
918 // We either have an incomplete class type, or we have a class template
919 // whose instantiation has not been forced. Example:
920 //
921 // template <class T> struct Foo { T value; };
922 // Foo<int> *p = nullptr;
923 // auto *d = __builtin_launder(p);
924 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
925 diag::err_incomplete_type))
926 return ExprError();
927
928 assert(ParamTy->getPointeeType()->isObjectType() &&
929 "Unhandled non-object pointer case");
930
931 InitializedEntity Entity =
932 InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
933 ExprResult Arg =
934 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
935 if (Arg.isInvalid())
936 return ExprError();
937 TheCall->setArg(0, Arg.get());
938
939 return TheCall;
940}
941
Aaron Ballman68d50642018-06-19 14:53:20 +0000942// Emit an error and return true if the current architecture is not in the list
943// of supported architectures.
944static bool
945CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
946 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
947 llvm::Triple::ArchType CurArch =
948 S.getASTContext().getTargetInfo().getTriple().getArch();
949 if (llvm::is_contained(SupportedArchs, CurArch))
950 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000951 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
Aaron Ballman68d50642018-06-19 14:53:20 +0000952 << TheCall->getSourceRange();
953 return true;
954}
955
956ExprResult
957Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
958 CallExpr *TheCall) {
959 ExprResult TheCallResult(TheCall);
960
961 // Find out if any arguments are required to be integer constant expressions.
962 unsigned ICEArguments = 0;
963 ASTContext::GetBuiltinTypeError Error;
964 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
965 if (Error != ASTContext::GE_None)
966 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
Fangrui Song6907ce22018-07-30 19:24:48 +0000967
Aaron Ballman68d50642018-06-19 14:53:20 +0000968 // If any arguments are required to be ICE's, check and diagnose.
969 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
970 // Skip arguments not required to be ICE's.
971 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000972
Aaron Ballman68d50642018-06-19 14:53:20 +0000973 llvm::APSInt Result;
974 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
975 return true;
976 ICEArguments &= ~(1 << ArgNo);
977 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000978
Aaron Ballman68d50642018-06-19 14:53:20 +0000979 switch (BuiltinID) {
980 case Builtin::BI__builtin___CFStringMakeConstantString:
981 assert(TheCall->getNumArgs() == 1 &&
982 "Wrong # arguments to builtin CFStringMakeConstantString");
983 if (CheckObjCString(TheCall->getArg(0)))
984 return ExprError();
985 break;
986 case Builtin::BI__builtin_ms_va_start:
987 case Builtin::BI__builtin_stdarg_start:
988 case Builtin::BI__builtin_va_start:
989 if (SemaBuiltinVAStart(BuiltinID, TheCall))
990 return ExprError();
991 break;
992 case Builtin::BI__va_start: {
993 switch (Context.getTargetInfo().getTriple().getArch()) {
Martin Storsjo0b339e42018-09-27 08:24:15 +0000994 case llvm::Triple::aarch64:
Aaron Ballman68d50642018-06-19 14:53:20 +0000995 case llvm::Triple::arm:
996 case llvm::Triple::thumb:
997 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
998 return ExprError();
999 break;
1000 default:
1001 if (SemaBuiltinVAStart(BuiltinID, TheCall))
1002 return ExprError();
1003 break;
1004 }
1005 break;
1006 }
1007
1008 // The acquire, release, and no fence variants are ARM and AArch64 only.
1009 case Builtin::BI_interlockedbittestandset_acq:
1010 case Builtin::BI_interlockedbittestandset_rel:
1011 case Builtin::BI_interlockedbittestandset_nf:
1012 case Builtin::BI_interlockedbittestandreset_acq:
1013 case Builtin::BI_interlockedbittestandreset_rel:
1014 case Builtin::BI_interlockedbittestandreset_nf:
1015 if (CheckBuiltinTargetSupport(
1016 *this, BuiltinID, TheCall,
1017 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1018 return ExprError();
1019 break;
1020
1021 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1022 case Builtin::BI_bittest64:
1023 case Builtin::BI_bittestandcomplement64:
1024 case Builtin::BI_bittestandreset64:
1025 case Builtin::BI_bittestandset64:
1026 case Builtin::BI_interlockedbittestandreset64:
1027 case Builtin::BI_interlockedbittestandset64:
1028 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1029 {llvm::Triple::x86_64, llvm::Triple::arm,
1030 llvm::Triple::thumb, llvm::Triple::aarch64}))
1031 return ExprError();
1032 break;
1033
1034 case Builtin::BI__builtin_isgreater:
1035 case Builtin::BI__builtin_isgreaterequal:
1036 case Builtin::BI__builtin_isless:
1037 case Builtin::BI__builtin_islessequal:
1038 case Builtin::BI__builtin_islessgreater:
1039 case Builtin::BI__builtin_isunordered:
1040 if (SemaBuiltinUnorderedCompare(TheCall))
1041 return ExprError();
1042 break;
1043 case Builtin::BI__builtin_fpclassify:
1044 if (SemaBuiltinFPClassification(TheCall, 6))
1045 return ExprError();
1046 break;
1047 case Builtin::BI__builtin_isfinite:
1048 case Builtin::BI__builtin_isinf:
1049 case Builtin::BI__builtin_isinf_sign:
1050 case Builtin::BI__builtin_isnan:
1051 case Builtin::BI__builtin_isnormal:
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00001052 case Builtin::BI__builtin_signbit:
1053 case Builtin::BI__builtin_signbitf:
1054 case Builtin::BI__builtin_signbitl:
Aaron Ballman68d50642018-06-19 14:53:20 +00001055 if (SemaBuiltinFPClassification(TheCall, 1))
1056 return ExprError();
1057 break;
1058 case Builtin::BI__builtin_shufflevector:
1059 return SemaBuiltinShuffleVector(TheCall);
1060 // TheCall will be freed by the smart pointer here, but that's fine, since
1061 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1062 case Builtin::BI__builtin_prefetch:
1063 if (SemaBuiltinPrefetch(TheCall))
1064 return ExprError();
1065 break;
1066 case Builtin::BI__builtin_alloca_with_align:
1067 if (SemaBuiltinAllocaWithAlign(TheCall))
1068 return ExprError();
1069 break;
1070 case Builtin::BI__assume:
1071 case Builtin::BI__builtin_assume:
1072 if (SemaBuiltinAssume(TheCall))
1073 return ExprError();
1074 break;
1075 case Builtin::BI__builtin_assume_aligned:
1076 if (SemaBuiltinAssumeAligned(TheCall))
1077 return ExprError();
1078 break;
Erik Pilkington9c3b5882019-01-30 20:34:53 +00001079 case Builtin::BI__builtin_dynamic_object_size:
Aaron Ballman68d50642018-06-19 14:53:20 +00001080 case Builtin::BI__builtin_object_size:
1081 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1082 return ExprError();
1083 break;
1084 case Builtin::BI__builtin_longjmp:
1085 if (SemaBuiltinLongjmp(TheCall))
1086 return ExprError();
1087 break;
1088 case Builtin::BI__builtin_setjmp:
1089 if (SemaBuiltinSetjmp(TheCall))
1090 return ExprError();
1091 break;
1092 case Builtin::BI_setjmp:
1093 case Builtin::BI_setjmpex:
1094 if (checkArgCount(*this, TheCall, 1))
1095 return true;
1096 break;
1097 case Builtin::BI__builtin_classify_type:
1098 if (checkArgCount(*this, TheCall, 1)) return true;
1099 TheCall->setType(Context.IntTy);
1100 break;
1101 case Builtin::BI__builtin_constant_p:
1102 if (checkArgCount(*this, TheCall, 1)) return true;
1103 TheCall->setType(Context.IntTy);
1104 break;
Eric Fiselier26187502018-12-14 21:11:28 +00001105 case Builtin::BI__builtin_launder:
1106 return SemaBuiltinLaunder(*this, TheCall);
Aaron Ballman68d50642018-06-19 14:53:20 +00001107 case Builtin::BI__sync_fetch_and_add:
1108 case Builtin::BI__sync_fetch_and_add_1:
1109 case Builtin::BI__sync_fetch_and_add_2:
1110 case Builtin::BI__sync_fetch_and_add_4:
1111 case Builtin::BI__sync_fetch_and_add_8:
1112 case Builtin::BI__sync_fetch_and_add_16:
1113 case Builtin::BI__sync_fetch_and_sub:
1114 case Builtin::BI__sync_fetch_and_sub_1:
1115 case Builtin::BI__sync_fetch_and_sub_2:
1116 case Builtin::BI__sync_fetch_and_sub_4:
1117 case Builtin::BI__sync_fetch_and_sub_8:
1118 case Builtin::BI__sync_fetch_and_sub_16:
1119 case Builtin::BI__sync_fetch_and_or:
1120 case Builtin::BI__sync_fetch_and_or_1:
1121 case Builtin::BI__sync_fetch_and_or_2:
1122 case Builtin::BI__sync_fetch_and_or_4:
1123 case Builtin::BI__sync_fetch_and_or_8:
1124 case Builtin::BI__sync_fetch_and_or_16:
1125 case Builtin::BI__sync_fetch_and_and:
1126 case Builtin::BI__sync_fetch_and_and_1:
1127 case Builtin::BI__sync_fetch_and_and_2:
1128 case Builtin::BI__sync_fetch_and_and_4:
1129 case Builtin::BI__sync_fetch_and_and_8:
1130 case Builtin::BI__sync_fetch_and_and_16:
1131 case Builtin::BI__sync_fetch_and_xor:
1132 case Builtin::BI__sync_fetch_and_xor_1:
1133 case Builtin::BI__sync_fetch_and_xor_2:
1134 case Builtin::BI__sync_fetch_and_xor_4:
1135 case Builtin::BI__sync_fetch_and_xor_8:
1136 case Builtin::BI__sync_fetch_and_xor_16:
1137 case Builtin::BI__sync_fetch_and_nand:
1138 case Builtin::BI__sync_fetch_and_nand_1:
1139 case Builtin::BI__sync_fetch_and_nand_2:
1140 case Builtin::BI__sync_fetch_and_nand_4:
1141 case Builtin::BI__sync_fetch_and_nand_8:
1142 case Builtin::BI__sync_fetch_and_nand_16:
1143 case Builtin::BI__sync_add_and_fetch:
1144 case Builtin::BI__sync_add_and_fetch_1:
1145 case Builtin::BI__sync_add_and_fetch_2:
1146 case Builtin::BI__sync_add_and_fetch_4:
1147 case Builtin::BI__sync_add_and_fetch_8:
1148 case Builtin::BI__sync_add_and_fetch_16:
1149 case Builtin::BI__sync_sub_and_fetch:
1150 case Builtin::BI__sync_sub_and_fetch_1:
1151 case Builtin::BI__sync_sub_and_fetch_2:
1152 case Builtin::BI__sync_sub_and_fetch_4:
1153 case Builtin::BI__sync_sub_and_fetch_8:
1154 case Builtin::BI__sync_sub_and_fetch_16:
1155 case Builtin::BI__sync_and_and_fetch:
1156 case Builtin::BI__sync_and_and_fetch_1:
1157 case Builtin::BI__sync_and_and_fetch_2:
1158 case Builtin::BI__sync_and_and_fetch_4:
1159 case Builtin::BI__sync_and_and_fetch_8:
1160 case Builtin::BI__sync_and_and_fetch_16:
1161 case Builtin::BI__sync_or_and_fetch:
1162 case Builtin::BI__sync_or_and_fetch_1:
1163 case Builtin::BI__sync_or_and_fetch_2:
1164 case Builtin::BI__sync_or_and_fetch_4:
1165 case Builtin::BI__sync_or_and_fetch_8:
1166 case Builtin::BI__sync_or_and_fetch_16:
1167 case Builtin::BI__sync_xor_and_fetch:
1168 case Builtin::BI__sync_xor_and_fetch_1:
1169 case Builtin::BI__sync_xor_and_fetch_2:
1170 case Builtin::BI__sync_xor_and_fetch_4:
1171 case Builtin::BI__sync_xor_and_fetch_8:
1172 case Builtin::BI__sync_xor_and_fetch_16:
1173 case Builtin::BI__sync_nand_and_fetch:
1174 case Builtin::BI__sync_nand_and_fetch_1:
1175 case Builtin::BI__sync_nand_and_fetch_2:
1176 case Builtin::BI__sync_nand_and_fetch_4:
1177 case Builtin::BI__sync_nand_and_fetch_8:
1178 case Builtin::BI__sync_nand_and_fetch_16:
1179 case Builtin::BI__sync_val_compare_and_swap:
1180 case Builtin::BI__sync_val_compare_and_swap_1:
1181 case Builtin::BI__sync_val_compare_and_swap_2:
1182 case Builtin::BI__sync_val_compare_and_swap_4:
1183 case Builtin::BI__sync_val_compare_and_swap_8:
1184 case Builtin::BI__sync_val_compare_and_swap_16:
1185 case Builtin::BI__sync_bool_compare_and_swap:
1186 case Builtin::BI__sync_bool_compare_and_swap_1:
1187 case Builtin::BI__sync_bool_compare_and_swap_2:
1188 case Builtin::BI__sync_bool_compare_and_swap_4:
1189 case Builtin::BI__sync_bool_compare_and_swap_8:
1190 case Builtin::BI__sync_bool_compare_and_swap_16:
1191 case Builtin::BI__sync_lock_test_and_set:
1192 case Builtin::BI__sync_lock_test_and_set_1:
1193 case Builtin::BI__sync_lock_test_and_set_2:
1194 case Builtin::BI__sync_lock_test_and_set_4:
1195 case Builtin::BI__sync_lock_test_and_set_8:
1196 case Builtin::BI__sync_lock_test_and_set_16:
1197 case Builtin::BI__sync_lock_release:
1198 case Builtin::BI__sync_lock_release_1:
1199 case Builtin::BI__sync_lock_release_2:
1200 case Builtin::BI__sync_lock_release_4:
1201 case Builtin::BI__sync_lock_release_8:
1202 case Builtin::BI__sync_lock_release_16:
1203 case Builtin::BI__sync_swap:
1204 case Builtin::BI__sync_swap_1:
1205 case Builtin::BI__sync_swap_2:
1206 case Builtin::BI__sync_swap_4:
1207 case Builtin::BI__sync_swap_8:
1208 case Builtin::BI__sync_swap_16:
1209 return SemaBuiltinAtomicOverloaded(TheCallResult);
JF Bastiene77b48b2018-09-10 20:42:56 +00001210 case Builtin::BI__sync_synchronize:
1211 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1212 << TheCall->getCallee()->getSourceRange();
1213 break;
Aaron Ballman68d50642018-06-19 14:53:20 +00001214 case Builtin::BI__builtin_nontemporal_load:
1215 case Builtin::BI__builtin_nontemporal_store:
1216 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1217#define BUILTIN(ID, TYPE, ATTRS)
1218#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1219 case Builtin::BI##ID: \
1220 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1221#include "clang/Basic/Builtins.def"
1222 case Builtin::BI__annotation:
1223 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1224 return ExprError();
1225 break;
1226 case Builtin::BI__builtin_annotation:
1227 if (SemaBuiltinAnnotation(*this, TheCall))
1228 return ExprError();
1229 break;
1230 case Builtin::BI__builtin_addressof:
1231 if (SemaBuiltinAddressof(*this, TheCall))
1232 return ExprError();
1233 break;
1234 case Builtin::BI__builtin_add_overflow:
1235 case Builtin::BI__builtin_sub_overflow:
1236 case Builtin::BI__builtin_mul_overflow:
1237 if (SemaBuiltinOverflow(*this, TheCall))
1238 return ExprError();
1239 break;
1240 case Builtin::BI__builtin_operator_new:
1241 case Builtin::BI__builtin_operator_delete: {
1242 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1243 ExprResult Res =
1244 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1245 if (Res.isInvalid())
1246 CorrectDelayedTyposInExpr(TheCallResult.get());
1247 return Res;
1248 }
1249 case Builtin::BI__builtin_dump_struct: {
1250 // We first want to ensure we are called with 2 arguments
1251 if (checkArgCount(*this, TheCall, 2))
1252 return ExprError();
1253 // Ensure that the first argument is of type 'struct XX *'
1254 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1255 const QualType PtrArgType = PtrArg->getType();
1256 if (!PtrArgType->isPointerType() ||
1257 !PtrArgType->getPointeeType()->isRecordType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001258 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman68d50642018-06-19 14:53:20 +00001259 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1260 << "structure pointer";
1261 return ExprError();
Aaron Ballman06525342018-04-10 21:58:13 +00001262 }
1263
1264 // Ensure that the second argument is of type 'FunctionType'
1265 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1266 const QualType FnPtrArgType = FnPtrArg->getType();
1267 if (!FnPtrArgType->isPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001268 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1269 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1270 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001271 return ExprError();
1272 }
1273
1274 const auto *FuncType =
1275 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1276
1277 if (!FuncType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001278 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1279 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1280 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001281 return ExprError();
1282 }
1283
1284 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1285 if (!FT->getNumParams()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001286 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001287 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1288 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1289 return ExprError();
1290 }
1291 QualType PT = FT->getParamType(0);
1292 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1293 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1294 !PT->getPointeeType().isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001295 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001296 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1297 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1298 return ExprError();
1299 }
1300 }
1301
1302 TheCall->setType(Context.IntTy);
1303 break;
1304 }
1305
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001306 // check secure string manipulation functions where overflows
1307 // are detectable at compile time
1308 case Builtin::BI__builtin___memcpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001309 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy");
1310 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001311 case Builtin::BI__builtin___memmove_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001312 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove");
1313 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001314 case Builtin::BI__builtin___memset_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001315 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset");
1316 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001317 case Builtin::BI__builtin___strlcat_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001318 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat");
1319 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001320 case Builtin::BI__builtin___strlcpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001321 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy");
1322 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001323 case Builtin::BI__builtin___strncat_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001324 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat");
1325 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001326 case Builtin::BI__builtin___strncpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001327 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy");
1328 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001329 case Builtin::BI__builtin___stpncpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001330 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy");
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001331 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001332 case Builtin::BI__builtin___memccpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001333 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy");
Steven Wu566c14e2014-09-24 04:37:33 +00001334 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001335 case Builtin::BI__builtin___snprintf_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001336 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf");
1337 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001338 case Builtin::BI__builtin___vsnprintf_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001339 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf");
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001340 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001341 case Builtin::BI__builtin_call_with_static_chain:
1342 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1343 return ExprError();
1344 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001345 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001346 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001347 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1348 diag::err_seh___except_block))
1349 return ExprError();
1350 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001351 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001352 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001353 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1354 diag::err_seh___except_filter))
1355 return ExprError();
1356 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001357 case Builtin::BI__GetExceptionInfo:
1358 if (checkArgCount(*this, TheCall, 1))
1359 return ExprError();
1360
1361 if (CheckCXXThrowOperand(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001362 TheCall->getBeginLoc(),
David Majnemerba3e5ec2015-03-13 18:26:17 +00001363 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1364 TheCall))
1365 return ExprError();
1366
1367 TheCall->setType(Context.VoidPtrTy);
1368 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001369 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001370 case Builtin::BIread_pipe:
1371 case Builtin::BIwrite_pipe:
1372 // Since those two functions are declared with var args, we need a semantic
1373 // check for the argument.
1374 if (SemaBuiltinRWPipe(*this, TheCall))
1375 return ExprError();
1376 break;
1377 case Builtin::BIreserve_read_pipe:
1378 case Builtin::BIreserve_write_pipe:
1379 case Builtin::BIwork_group_reserve_read_pipe:
1380 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001381 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1382 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001383 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001384 case Builtin::BIsub_group_reserve_read_pipe:
1385 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001386 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1387 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001388 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001389 break;
1390 case Builtin::BIcommit_read_pipe:
1391 case Builtin::BIcommit_write_pipe:
1392 case Builtin::BIwork_group_commit_read_pipe:
1393 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001394 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1395 return ExprError();
1396 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001397 case Builtin::BIsub_group_commit_read_pipe:
1398 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001399 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1400 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001401 return ExprError();
1402 break;
1403 case Builtin::BIget_pipe_num_packets:
1404 case Builtin::BIget_pipe_max_packets:
1405 if (SemaBuiltinPipePackets(*this, TheCall))
1406 return ExprError();
1407 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001408 case Builtin::BIto_global:
1409 case Builtin::BIto_local:
1410 case Builtin::BIto_private:
1411 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1412 return ExprError();
1413 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001414 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1415 case Builtin::BIenqueue_kernel:
1416 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1417 return ExprError();
1418 break;
1419 case Builtin::BIget_kernel_work_group_size:
1420 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1421 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1422 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001423 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001424 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1425 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1426 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1427 return ExprError();
1428 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001429 case Builtin::BI__builtin_os_log_format:
1430 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001431 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001432 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001433 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001434 }
Richard Smith760520b2014-06-03 23:27:44 +00001435
Nate Begeman4904e322010-06-08 02:47:44 +00001436 // Since the target specific builtins for each arch overlap, only check those
1437 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001438 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001439 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001440 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001441 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001442 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001443 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001444 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1445 return ExprError();
1446 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001447 case llvm::Triple::aarch64:
1448 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001449 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001450 return ExprError();
1451 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001452 case llvm::Triple::hexagon:
1453 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1454 return ExprError();
1455 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001456 case llvm::Triple::mips:
1457 case llvm::Triple::mipsel:
1458 case llvm::Triple::mips64:
1459 case llvm::Triple::mips64el:
1460 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1461 return ExprError();
1462 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001463 case llvm::Triple::systemz:
1464 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1465 return ExprError();
1466 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001467 case llvm::Triple::x86:
1468 case llvm::Triple::x86_64:
1469 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1470 return ExprError();
1471 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001472 case llvm::Triple::ppc:
1473 case llvm::Triple::ppc64:
1474 case llvm::Triple::ppc64le:
1475 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1476 return ExprError();
1477 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001478 default:
1479 break;
1480 }
1481 }
1482
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001483 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001484}
1485
Nate Begeman91e1fea2010-06-14 05:21:25 +00001486// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001487static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001488 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001489 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001490 switch (Type.getEltType()) {
1491 case NeonTypeFlags::Int8:
1492 case NeonTypeFlags::Poly8:
1493 return shift ? 7 : (8 << IsQuad) - 1;
1494 case NeonTypeFlags::Int16:
1495 case NeonTypeFlags::Poly16:
1496 return shift ? 15 : (4 << IsQuad) - 1;
1497 case NeonTypeFlags::Int32:
1498 return shift ? 31 : (2 << IsQuad) - 1;
1499 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001500 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001501 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001502 case NeonTypeFlags::Poly128:
1503 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001504 case NeonTypeFlags::Float16:
1505 assert(!shift && "cannot shift float types!");
1506 return (4 << IsQuad) - 1;
1507 case NeonTypeFlags::Float32:
1508 assert(!shift && "cannot shift float types!");
1509 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001510 case NeonTypeFlags::Float64:
1511 assert(!shift && "cannot shift float types!");
1512 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001513 }
David Blaikie8a40f702012-01-17 06:56:22 +00001514 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001515}
1516
Bob Wilsone4d77232011-11-08 05:04:11 +00001517/// getNeonEltType - Return the QualType corresponding to the elements of
1518/// the vector type specified by the NeonTypeFlags. This is used to check
1519/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001520static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001521 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001522 switch (Flags.getEltType()) {
1523 case NeonTypeFlags::Int8:
1524 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1525 case NeonTypeFlags::Int16:
1526 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1527 case NeonTypeFlags::Int32:
1528 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1529 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001530 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001531 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1532 else
1533 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1534 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001535 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001536 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001537 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001538 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001539 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001540 if (IsInt64Long)
1541 return Context.UnsignedLongTy;
1542 else
1543 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001544 case NeonTypeFlags::Poly128:
1545 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001546 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001547 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001548 case NeonTypeFlags::Float32:
1549 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001550 case NeonTypeFlags::Float64:
1551 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001552 }
David Blaikie8a40f702012-01-17 06:56:22 +00001553 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001554}
1555
Tim Northover12670412014-02-19 10:37:05 +00001556bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001557 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001558 uint64_t mask = 0;
1559 unsigned TV = 0;
1560 int PtrArgNum = -1;
1561 bool HasConstPtr = false;
1562 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001563#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001564#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001565#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001566#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001567 }
1568
1569 // For NEON intrinsics which are overloaded on vector element type, validate
1570 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001571 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001572 if (mask) {
1573 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1574 return true;
1575
1576 TV = Result.getLimitedValue(64);
1577 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001578 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1579 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001580 }
1581
1582 if (PtrArgNum >= 0) {
1583 // Check that pointer arguments have the specified type.
1584 Expr *Arg = TheCall->getArg(PtrArgNum);
1585 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1586 Arg = ICE->getSubExpr();
1587 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1588 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001589
Tim Northovera2ee4332014-03-29 15:09:45 +00001590 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001591 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1592 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001593 bool IsInt64Long =
1594 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1595 QualType EltTy =
1596 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001597 if (HasConstPtr)
1598 EltTy = EltTy.withConst();
1599 QualType LHSTy = Context.getPointerType(EltTy);
1600 AssignConvertType ConvTy;
1601 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1602 if (RHS.isInvalid())
1603 return true;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001604 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
Tim Northover2fe823a2013-08-01 09:23:19 +00001605 RHS.get(), AA_Assigning))
1606 return true;
1607 }
1608
1609 // For NEON intrinsics which take an immediate value as part of the
1610 // instruction, range check them here.
1611 unsigned i = 0, l = 0, u = 0;
1612 switch (BuiltinID) {
1613 default:
1614 return false;
Luke Geesondc54b372018-06-12 09:54:27 +00001615 #define GET_NEON_IMMEDIATE_CHECK
1616 #include "clang/Basic/arm_neon.inc"
1617 #include "clang/Basic/arm_fp16.inc"
1618 #undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001619 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001620
Richard Sandiford28940af2014-04-16 08:47:51 +00001621 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001622}
1623
Tim Northovera2ee4332014-03-29 15:09:45 +00001624bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1625 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001626 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001627 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001628 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001629 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001630 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001631 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1632 BuiltinID == AArch64::BI__builtin_arm_strex ||
1633 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001634 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001635 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001636 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1637 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1638 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001639
1640 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1641
1642 // Ensure that we have the proper number of arguments.
1643 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1644 return true;
1645
1646 // Inspect the pointer argument of the atomic builtin. This should always be
1647 // a pointer type, whose element is an integral scalar or pointer type.
1648 // Because it is a pointer type, we don't have to worry about any implicit
1649 // casts here.
1650 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1651 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1652 if (PointerArgRes.isInvalid())
1653 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001654 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001655
1656 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1657 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001658 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1659 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001660 return true;
1661 }
1662
1663 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1664 // task is to insert the appropriate casts into the AST. First work out just
1665 // what the appropriate type is.
1666 QualType ValType = pointerType->getPointeeType();
1667 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1668 if (IsLdrex)
1669 AddrType.addConst();
1670
1671 // Issue a warning if the cast is dodgy.
1672 CastKind CastNeeded = CK_NoOp;
1673 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1674 CastNeeded = CK_BitCast;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001675 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1676 << PointerArg->getType() << Context.getPointerType(AddrType)
1677 << AA_Passing << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001678 }
1679
1680 // Finally, do the cast and replace the argument with the corrected version.
1681 AddrType = Context.getPointerType(AddrType);
1682 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1683 if (PointerArgRes.isInvalid())
1684 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001685 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001686
1687 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1688
1689 // In general, we allow ints, floats and pointers to be loaded and stored.
1690 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1691 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001692 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1693 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001694 return true;
1695 }
1696
1697 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001698 if (Context.getTypeSize(ValType) > MaxWidth) {
1699 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001700 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1701 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001702 return true;
1703 }
1704
1705 switch (ValType.getObjCLifetime()) {
1706 case Qualifiers::OCL_None:
1707 case Qualifiers::OCL_ExplicitNone:
1708 // okay
1709 break;
1710
1711 case Qualifiers::OCL_Weak:
1712 case Qualifiers::OCL_Strong:
1713 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001714 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1715 << ValType << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001716 return true;
1717 }
1718
Tim Northover6aacd492013-07-16 09:47:53 +00001719 if (IsLdrex) {
1720 TheCall->setType(ValType);
1721 return false;
1722 }
1723
1724 // Initialize the argument to be stored.
1725 ExprResult ValArg = TheCall->getArg(0);
1726 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1727 Context, ValType, /*consume*/ false);
1728 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1729 if (ValArg.isInvalid())
1730 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001731 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001732
1733 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1734 // but the custom checker bypasses all default analysis.
1735 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001736 return false;
1737}
1738
Nate Begeman4904e322010-06-08 02:47:44 +00001739bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001740 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001741 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1742 BuiltinID == ARM::BI__builtin_arm_strex ||
1743 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001744 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001745 }
1746
Yi Kong26d104a2014-08-13 19:18:14 +00001747 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1748 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1749 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1750 }
1751
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001752 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1753 BuiltinID == ARM::BI__builtin_arm_wsr64)
1754 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1755
1756 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1757 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1758 BuiltinID == ARM::BI__builtin_arm_wsr ||
1759 BuiltinID == ARM::BI__builtin_arm_wsrp)
1760 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1761
Tim Northover12670412014-02-19 10:37:05 +00001762 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1763 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001764
Yi Kong4efadfb2014-07-03 16:01:25 +00001765 // For intrinsics which take an immediate value as part of the instruction,
1766 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001767 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001768 switch (BuiltinID) {
1769 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001770 case ARM::BI__builtin_arm_ssat:
1771 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1772 case ARM::BI__builtin_arm_usat:
1773 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1774 case ARM::BI__builtin_arm_ssat16:
1775 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1776 case ARM::BI__builtin_arm_usat16:
1777 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001778 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001779 case ARM::BI__builtin_arm_vcvtr_d:
1780 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001781 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001782 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001783 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001784 case ARM::BI__builtin_arm_dbg:
1785 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001786 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001787}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001788
Tim Northover573cbee2014-05-24 12:52:07 +00001789bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001790 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001791 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001792 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1793 BuiltinID == AArch64::BI__builtin_arm_strex ||
1794 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001795 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1796 }
1797
Yi Konga5548432014-08-13 19:18:20 +00001798 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1799 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1800 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1801 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1802 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1803 }
1804
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001805 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1806 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001807 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001808
1809 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1810 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1811 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1812 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1813 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1814
Mandeep Singh Grang2147b1a2018-10-18 23:35:35 +00001815 // Only check the valid encoding range. Any constant in this range would be
1816 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1817 // an exception for incorrect registers. This matches MSVC behavior.
1818 if (BuiltinID == AArch64::BI_ReadStatusReg ||
1819 BuiltinID == AArch64::BI_WriteStatusReg)
1820 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1821
Mandeep Singh Grangecc82ef2018-10-04 22:32:42 +00001822 if (BuiltinID == AArch64::BI__getReg)
1823 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1824
Tim Northovera2ee4332014-03-29 15:09:45 +00001825 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1826 return true;
1827
Yi Kong19a29ac2014-07-17 10:52:06 +00001828 // For intrinsics which take an immediate value as part of the instruction,
1829 // range check them here.
1830 unsigned i = 0, l = 0, u = 0;
1831 switch (BuiltinID) {
1832 default: return false;
1833 case AArch64::BI__builtin_arm_dmb:
1834 case AArch64::BI__builtin_arm_dsb:
1835 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1836 }
1837
Yi Kong19a29ac2014-07-17 10:52:06 +00001838 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001839}
1840
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001841bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001842 struct BuiltinAndString {
1843 unsigned BuiltinID;
1844 const char *Str;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001845 };
1846
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001847 static BuiltinAndString ValidCPU[] = {
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00001848 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1849 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1850 { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1851 { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1852 { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1853 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1854 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1855 { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1856 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1857 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1858 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1859 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1860 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1861 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1862 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1863 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1864 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1865 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1866 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1867 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1868 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1869 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1870 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001871 };
1872
1873 static BuiltinAndString ValidHVX[] = {
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00001874 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1875 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1876 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1877 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1878 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1879 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1880 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1881 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1882 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1883 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1884 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1885 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1886 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1887 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1888 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1889 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1890 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1891 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1892 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1893 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1894 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1895 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1896 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1897 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
1898 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
1899 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
1900 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
1901 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
1902 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
1903 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
1904 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
1905 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
1906 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
1907 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
1908 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
1909 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
1910 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
1911 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
1912 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
1913 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
1914 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
1915 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
1916 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
1917 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
1918 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
1919 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
1920 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
1921 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
1922 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
1923 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
1924 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
1925 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
1926 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
1927 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
1928 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
1929 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
1930 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
1931 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
1932 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
1933 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
1934 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
1935 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
1936 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
1937 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
1938 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
1939 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
1940 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
1941 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
1942 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
1943 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
1944 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
1945 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
1946 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
1947 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
1948 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
1949 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
1950 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
1951 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
1952 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
1953 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
1954 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
1955 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
1956 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
1957 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
1958 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
1959 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
1960 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
1961 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
1962 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
1963 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
1964 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
1965 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
1966 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
1967 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
1968 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
1969 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
1970 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
1971 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
1972 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
1973 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
1974 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
1975 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
1976 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
1977 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
1978 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
1979 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
1980 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
1981 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
1982 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
1983 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
1984 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
1985 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
1986 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
1987 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
1988 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
1989 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
1990 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
1991 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
1992 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
1993 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
1994 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
1995 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
1996 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
1997 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
1998 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
1999 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2000 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2001 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2002 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2003 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2004 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2005 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2006 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2007 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2008 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2009 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2010 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2011 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2012 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2013 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2014 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2015 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2016 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2017 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2018 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2019 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2020 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2021 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2022 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2023 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2024 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2025 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2026 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2027 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2028 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2029 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2030 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2031 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2032 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2033 { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2034 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2035 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2036 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2037 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2038 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2039 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2040 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2041 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2042 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2043 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2044 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2045 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2046 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2047 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2048 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2049 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2050 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2051 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2052 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2053 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2054 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2055 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2056 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2057 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2058 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2059 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2060 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2061 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2062 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2063 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2064 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2065 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2066 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2067 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2068 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2069 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2070 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2071 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2072 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2073 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2074 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2075 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2076 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2077 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2078 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2079 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2080 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2081 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2082 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2083 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2084 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2085 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2086 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2087 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2088 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2089 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2090 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2091 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2092 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2093 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2094 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2095 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2096 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2097 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2098 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2099 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2100 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2101 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2102 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2103 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2104 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2105 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2106 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2107 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2108 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2109 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2110 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2111 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2112 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2113 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2114 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2115 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2116 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2117 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2118 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2119 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2120 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2121 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2122 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2123 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2124 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2125 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2126 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2127 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2128 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2129 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2130 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2131 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2132 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2133 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2134 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2135 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2136 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2137 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2138 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2139 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2140 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2141 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2142 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2143 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2144 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2145 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2146 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2147 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2148 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2149 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2150 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2151 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2152 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2153 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2154 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2155 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2156 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2157 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2158 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2159 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2160 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2161 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2162 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2163 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2164 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2165 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2166 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2167 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2168 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2169 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2170 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2171 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2172 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2173 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2174 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2175 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2176 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2177 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2178 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2179 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2180 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2181 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2182 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2183 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2184 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2185 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2186 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2187 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2188 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2189 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2190 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2191 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2192 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2193 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2194 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2195 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2196 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2197 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2198 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2199 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2200 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2201 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2202 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2203 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2204 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2205 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2206 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2207 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2208 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2209 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2210 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2211 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2212 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2213 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2214 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2215 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2216 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2217 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2218 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2219 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2220 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2221 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2222 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2223 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2224 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2225 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2226 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2227 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2228 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2229 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2230 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2231 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2232 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2233 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2234 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2235 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2236 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2237 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2238 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2239 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2240 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2241 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2242 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2243 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2244 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2245 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2246 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2247 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2248 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2249 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2250 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2251 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2252 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2253 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2254 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2255 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2256 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2257 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2258 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2259 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2260 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2261 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2262 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2263 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2264 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2265 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2266 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2267 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2268 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2269 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2270 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2271 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2272 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2273 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2274 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2275 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2276 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2277 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2278 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2279 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2280 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2281 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2282 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2283 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2284 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2285 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2286 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2287 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2288 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2289 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2290 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2291 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2292 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2293 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2294 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2295 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2296 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2297 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2298 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2299 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2300 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2301 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2302 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2303 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2304 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2305 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2306 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2307 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2308 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2309 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2310 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2311 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2312 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2313 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2314 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2315 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2316 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2317 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2318 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2319 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2320 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2321 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2322 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2323 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2324 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2325 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2326 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2327 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2328 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2329 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2330 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2331 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2332 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2333 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2334 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2335 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2336 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2337 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2338 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2339 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2340 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2341 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2342 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2343 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2344 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2345 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2346 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2347 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2348 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2349 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2350 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2351 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2352 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2353 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2354 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2355 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2356 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2357 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2358 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2359 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2360 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2361 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2362 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2363 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2364 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2365 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2366 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2367 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2368 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2369 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2370 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2371 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2372 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2373 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2374 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2375 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2376 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2377 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2378 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2379 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2380 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2381 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2382 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2383 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2384 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2385 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2386 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2387 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2388 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2389 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2390 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2391 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2392 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2393 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2394 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2395 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2396 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2397 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2398 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2399 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2400 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2401 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2402 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2403 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2404 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2405 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2406 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2407 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2408 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2409 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2410 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2411 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2412 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2413 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2414 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2415 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2416 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2417 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2418 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2419 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2420 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2421 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2422 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2423 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2424 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2425 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2426 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2427 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2428 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2429 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2430 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2431 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2432 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2433 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2434 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2435 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2436 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2437 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2438 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2439 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2440 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2441 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002442 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2443 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2444 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2445 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002446 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2447 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2448 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2449 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2450 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2451 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2452 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2453 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2454 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2455 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2456 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2457 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2458 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2459 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2460 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2461 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2462 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2463 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2464 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2465 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2466 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2467 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2468 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2469 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002470 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2471 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2472 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2473 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
Krzysztof Parzyszek2a0c7c92018-12-05 22:03:04 +00002474 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2475 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2476 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2477 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2478 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2479 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2480 { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2481 { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2482 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2483 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2484 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2485 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2486 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2487 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2488 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2489 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2490 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2491 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2492 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2493 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2494 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2495 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2496 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2497 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2498 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2499 { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2500 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2501 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2502 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2503 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2504 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2505 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2506 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2507 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2508 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2509 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2510 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2511 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2512 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2513 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2514 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2515 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2516 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2517 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2518 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2519 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2520 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2521 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2522 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2523 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2524 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2525 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2526 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2527 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2528 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2529 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2530 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2531 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2532 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2533 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2534 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2535 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2536 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2537 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2538 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2539 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2540 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2541 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2542 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2543 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2544 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2545 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2546 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2547 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2548 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2549 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2550 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2551 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2552 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2553 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2554 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2555 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2556 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2557 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2558 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2559 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2560 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2561 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2562 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2563 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2564 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2565 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2566 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2567 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2568 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2569 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2570 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2571 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2572 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2573 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2574 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2575 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2576 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2577 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2578 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2579 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2580 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2581 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2582 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2583 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2584 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2585 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2586 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2587 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2588 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2589 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2590 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2591 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2592 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2593 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2594 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2595 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2596 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2597 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2598 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2599 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2600 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2601 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2602 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2603 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2604 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2605 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002606 };
2607
2608 // Sort the tables on first execution so we can binary search them.
2609 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2610 return LHS.BuiltinID < RHS.BuiltinID;
2611 };
2612 static const bool SortOnce =
Mandeep Singh Grang50dadaa42019-01-14 23:45:58 +00002613 (llvm::sort(ValidCPU, SortCmp),
2614 llvm::sort(ValidHVX, SortCmp), true);
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002615 (void)SortOnce;
2616 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2617 return BI.BuiltinID < BuiltinID;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002618 };
2619
2620 const TargetInfo &TI = Context.getTargetInfo();
2621
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002622 const BuiltinAndString *FC =
2623 std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2624 LowerBoundCmp);
2625 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002626 const TargetOptions &Opts = TI.getTargetOpts();
2627 StringRef CPU = Opts.CPU;
2628 if (!CPU.empty()) {
2629 assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2630 CPU.consume_front("hexagon");
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002631 SmallVector<StringRef, 3> CPUs;
2632 StringRef(FC->Str).split(CPUs, ',');
2633 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002634 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002635 diag::err_hexagon_builtin_unsupported_cpu);
2636 }
2637 }
2638
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002639 const BuiltinAndString *FH =
2640 std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2641 LowerBoundCmp);
2642 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002643 if (!TI.hasFeature("hvx"))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002644 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002645 diag::err_hexagon_builtin_requires_hvx);
2646
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002647 SmallVector<StringRef, 3> HVXs;
2648 StringRef(FH->Str).split(HVXs, ',');
2649 bool IsValid = llvm::any_of(HVXs,
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002650 [&TI] (StringRef V) {
2651 std::string F = "hvx" + V.str();
2652 return TI.hasFeature(F);
2653 });
2654 if (!IsValid)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002655 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002656 diag::err_hexagon_builtin_unsupported_hvx);
2657 }
2658
2659 return false;
2660}
2661
2662bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002663 struct ArgInfo {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002664 uint8_t OpNum;
2665 bool IsSigned;
2666 uint8_t BitWidth;
2667 uint8_t Align;
2668 };
2669 struct BuiltinInfo {
2670 unsigned BuiltinID;
2671 ArgInfo Infos[2];
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002672 };
2673
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002674 static BuiltinInfo Infos[] = {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002675 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
2676 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
2677 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
2678 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
2679 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
2680 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
2681 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
2682 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
2683 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
2684 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
2685 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
2686
2687 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
2688 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
2689 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
2690 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
2691 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
2692 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
2693 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
2694 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
2695 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
2696 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
2697 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
2698
2699 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
2700 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
2701 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
2702 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
2703 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
2704 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
2705 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
2706 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
2707 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
2708 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
2709 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
2710 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
2711 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
2712 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
2713 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
2714 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
2715 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
2716 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
2717 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
2718 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
2719 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
2720 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
2721 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
2722 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
2723 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
2724 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
2725 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
2726 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
2727 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
2728 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
2729 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
2730 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
2731 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
2732 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
2733 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
2734 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
2735 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
2736 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
2737 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
2738 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
2739 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
2740 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
2741 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
2742 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
2743 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
2744 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
2745 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
2746 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
2747 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
2748 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
2749 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
2750 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2751 {{ 1, false, 6, 0 }} },
2752 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
2753 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
2754 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
2755 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
2756 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
2757 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
2758 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2759 {{ 1, false, 5, 0 }} },
2760 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
2761 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
2762 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
2763 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
2764 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
2765 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
2766 { 2, false, 5, 0 }} },
2767 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
2768 { 2, false, 6, 0 }} },
2769 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
2770 { 3, false, 5, 0 }} },
2771 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
2772 { 3, false, 6, 0 }} },
2773 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
2774 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
2775 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
2776 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
2777 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
2778 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
2779 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
2780 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
2781 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
2782 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
2783 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
2784 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
2785 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
2786 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
2787 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
2788 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2789 {{ 2, false, 4, 0 },
2790 { 3, false, 5, 0 }} },
2791 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2792 {{ 2, false, 4, 0 },
2793 { 3, false, 5, 0 }} },
2794 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2795 {{ 2, false, 4, 0 },
2796 { 3, false, 5, 0 }} },
2797 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2798 {{ 2, false, 4, 0 },
2799 { 3, false, 5, 0 }} },
2800 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
2801 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
2802 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
2803 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
2804 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
2805 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
2806 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
2807 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
2808 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
2809 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
2810 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
2811 { 2, false, 5, 0 }} },
2812 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
2813 { 2, false, 6, 0 }} },
2814 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
2815 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
2816 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
2817 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
2818 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
2819 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
2820 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
2821 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
2822 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2823 {{ 1, false, 4, 0 }} },
2824 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
2825 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2826 {{ 1, false, 4, 0 }} },
2827 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
2828 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
2829 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
2830 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
2831 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
2832 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
2833 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
2834 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
2835 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
2836 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
2837 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
2838 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
2839 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
2840 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
2841 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
2842 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
2843 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
2844 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
2845 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
2846 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2847 {{ 3, false, 1, 0 }} },
2848 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
2849 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
2850 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
2851 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2852 {{ 3, false, 1, 0 }} },
2853 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
2854 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
2855 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
2856 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2857 {{ 3, false, 1, 0 }} },
2858 };
2859
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002860 // Use a dynamically initialized static to sort the table exactly once on
2861 // first run.
2862 static const bool SortOnce =
Mandeep Singh Grang50dadaa42019-01-14 23:45:58 +00002863 (llvm::sort(Infos,
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002864 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2865 return LHS.BuiltinID < RHS.BuiltinID;
2866 }),
2867 true);
2868 (void)SortOnce;
2869
2870 const BuiltinInfo *F =
2871 std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2872 [](const BuiltinInfo &BI, unsigned BuiltinID) {
2873 return BI.BuiltinID < BuiltinID;
2874 });
2875 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002876 return false;
2877
2878 bool Error = false;
2879
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002880 for (const ArgInfo &A : F->Infos) {
2881 // Ignore empty ArgInfo elements.
2882 if (A.BitWidth == 0)
2883 continue;
2884
2885 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2886 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002887 if (!A.Align) {
2888 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2889 } else {
2890 unsigned M = 1 << A.Align;
2891 Min *= M;
2892 Max *= M;
2893 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2894 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2895 }
2896 }
2897 return Error;
2898}
2899
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002900bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2901 CallExpr *TheCall) {
2902 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2903 CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2904}
2905
2906
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002907// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2908// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2909// ordering for DSP is unspecified. MSA is ordered by the data format used
2910// by the underlying instruction i.e., df/m, df/n and then by size.
2911//
2912// FIXME: The size tests here should instead be tablegen'd along with the
2913// definitions from include/clang/Basic/BuiltinsMips.def.
2914// FIXME: GCC is strict on signedness for some of these intrinsics, we should
2915// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002916bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002917 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002918 switch (BuiltinID) {
2919 default: return false;
2920 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2921 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00002922 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2923 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2924 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2925 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2926 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Raphael Isemannb23ccec2018-12-10 12:37:46 +00002927 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002928 // df/m field.
2929 // These intrinsics take an unsigned 3 bit immediate.
2930 case Mips::BI__builtin_msa_bclri_b:
2931 case Mips::BI__builtin_msa_bnegi_b:
2932 case Mips::BI__builtin_msa_bseti_b:
2933 case Mips::BI__builtin_msa_sat_s_b:
2934 case Mips::BI__builtin_msa_sat_u_b:
2935 case Mips::BI__builtin_msa_slli_b:
2936 case Mips::BI__builtin_msa_srai_b:
2937 case Mips::BI__builtin_msa_srari_b:
2938 case Mips::BI__builtin_msa_srli_b:
2939 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2940 case Mips::BI__builtin_msa_binsli_b:
2941 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2942 // These intrinsics take an unsigned 4 bit immediate.
2943 case Mips::BI__builtin_msa_bclri_h:
2944 case Mips::BI__builtin_msa_bnegi_h:
2945 case Mips::BI__builtin_msa_bseti_h:
2946 case Mips::BI__builtin_msa_sat_s_h:
2947 case Mips::BI__builtin_msa_sat_u_h:
2948 case Mips::BI__builtin_msa_slli_h:
2949 case Mips::BI__builtin_msa_srai_h:
2950 case Mips::BI__builtin_msa_srari_h:
2951 case Mips::BI__builtin_msa_srli_h:
2952 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2953 case Mips::BI__builtin_msa_binsli_h:
2954 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002955 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002956 // The first block of intrinsics actually have an unsigned 5 bit field,
2957 // not a df/n field.
2958 case Mips::BI__builtin_msa_clei_u_b:
2959 case Mips::BI__builtin_msa_clei_u_h:
2960 case Mips::BI__builtin_msa_clei_u_w:
2961 case Mips::BI__builtin_msa_clei_u_d:
2962 case Mips::BI__builtin_msa_clti_u_b:
2963 case Mips::BI__builtin_msa_clti_u_h:
2964 case Mips::BI__builtin_msa_clti_u_w:
2965 case Mips::BI__builtin_msa_clti_u_d:
2966 case Mips::BI__builtin_msa_maxi_u_b:
2967 case Mips::BI__builtin_msa_maxi_u_h:
2968 case Mips::BI__builtin_msa_maxi_u_w:
2969 case Mips::BI__builtin_msa_maxi_u_d:
2970 case Mips::BI__builtin_msa_mini_u_b:
2971 case Mips::BI__builtin_msa_mini_u_h:
2972 case Mips::BI__builtin_msa_mini_u_w:
2973 case Mips::BI__builtin_msa_mini_u_d:
2974 case Mips::BI__builtin_msa_addvi_b:
2975 case Mips::BI__builtin_msa_addvi_h:
2976 case Mips::BI__builtin_msa_addvi_w:
2977 case Mips::BI__builtin_msa_addvi_d:
2978 case Mips::BI__builtin_msa_bclri_w:
2979 case Mips::BI__builtin_msa_bnegi_w:
2980 case Mips::BI__builtin_msa_bseti_w:
2981 case Mips::BI__builtin_msa_sat_s_w:
2982 case Mips::BI__builtin_msa_sat_u_w:
2983 case Mips::BI__builtin_msa_slli_w:
2984 case Mips::BI__builtin_msa_srai_w:
2985 case Mips::BI__builtin_msa_srari_w:
2986 case Mips::BI__builtin_msa_srli_w:
2987 case Mips::BI__builtin_msa_srlri_w:
2988 case Mips::BI__builtin_msa_subvi_b:
2989 case Mips::BI__builtin_msa_subvi_h:
2990 case Mips::BI__builtin_msa_subvi_w:
2991 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2992 case Mips::BI__builtin_msa_binsli_w:
2993 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2994 // These intrinsics take an unsigned 6 bit immediate.
2995 case Mips::BI__builtin_msa_bclri_d:
2996 case Mips::BI__builtin_msa_bnegi_d:
2997 case Mips::BI__builtin_msa_bseti_d:
2998 case Mips::BI__builtin_msa_sat_s_d:
2999 case Mips::BI__builtin_msa_sat_u_d:
3000 case Mips::BI__builtin_msa_slli_d:
3001 case Mips::BI__builtin_msa_srai_d:
3002 case Mips::BI__builtin_msa_srari_d:
3003 case Mips::BI__builtin_msa_srli_d:
3004 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3005 case Mips::BI__builtin_msa_binsli_d:
3006 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3007 // These intrinsics take a signed 5 bit immediate.
3008 case Mips::BI__builtin_msa_ceqi_b:
3009 case Mips::BI__builtin_msa_ceqi_h:
3010 case Mips::BI__builtin_msa_ceqi_w:
3011 case Mips::BI__builtin_msa_ceqi_d:
3012 case Mips::BI__builtin_msa_clti_s_b:
3013 case Mips::BI__builtin_msa_clti_s_h:
3014 case Mips::BI__builtin_msa_clti_s_w:
3015 case Mips::BI__builtin_msa_clti_s_d:
3016 case Mips::BI__builtin_msa_clei_s_b:
3017 case Mips::BI__builtin_msa_clei_s_h:
3018 case Mips::BI__builtin_msa_clei_s_w:
3019 case Mips::BI__builtin_msa_clei_s_d:
3020 case Mips::BI__builtin_msa_maxi_s_b:
3021 case Mips::BI__builtin_msa_maxi_s_h:
3022 case Mips::BI__builtin_msa_maxi_s_w:
3023 case Mips::BI__builtin_msa_maxi_s_d:
3024 case Mips::BI__builtin_msa_mini_s_b:
3025 case Mips::BI__builtin_msa_mini_s_h:
3026 case Mips::BI__builtin_msa_mini_s_w:
3027 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3028 // These intrinsics take an unsigned 8 bit immediate.
3029 case Mips::BI__builtin_msa_andi_b:
3030 case Mips::BI__builtin_msa_nori_b:
3031 case Mips::BI__builtin_msa_ori_b:
3032 case Mips::BI__builtin_msa_shf_b:
3033 case Mips::BI__builtin_msa_shf_h:
3034 case Mips::BI__builtin_msa_shf_w:
3035 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3036 case Mips::BI__builtin_msa_bseli_b:
3037 case Mips::BI__builtin_msa_bmnzi_b:
3038 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3039 // df/n format
3040 // These intrinsics take an unsigned 4 bit immediate.
3041 case Mips::BI__builtin_msa_copy_s_b:
3042 case Mips::BI__builtin_msa_copy_u_b:
3043 case Mips::BI__builtin_msa_insve_b:
3044 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003045 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3046 // These intrinsics take an unsigned 3 bit immediate.
3047 case Mips::BI__builtin_msa_copy_s_h:
3048 case Mips::BI__builtin_msa_copy_u_h:
3049 case Mips::BI__builtin_msa_insve_h:
3050 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003051 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3052 // These intrinsics take an unsigned 2 bit immediate.
3053 case Mips::BI__builtin_msa_copy_s_w:
3054 case Mips::BI__builtin_msa_copy_u_w:
3055 case Mips::BI__builtin_msa_insve_w:
3056 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003057 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3058 // These intrinsics take an unsigned 1 bit immediate.
3059 case Mips::BI__builtin_msa_copy_s_d:
3060 case Mips::BI__builtin_msa_copy_u_d:
3061 case Mips::BI__builtin_msa_insve_d:
3062 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003063 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3064 // Memory offsets and immediate loads.
3065 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00003066 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003067 case Mips::BI__builtin_msa_ldi_h:
3068 case Mips::BI__builtin_msa_ldi_w:
3069 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
Aleksandar Beserminjie5921162018-11-07 11:37:05 +00003070 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3071 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3072 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3073 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3074 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3075 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3076 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3077 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00003078 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003079
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003080 if (!m)
3081 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3082
3083 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3084 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003085}
3086
Kit Bartone50adcb2015-03-30 19:40:59 +00003087bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3088 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003089 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3090 BuiltinID == PPC::BI__builtin_divdeu ||
3091 BuiltinID == PPC::BI__builtin_bpermd;
3092 bool IsTarget64Bit = Context.getTargetInfo()
3093 .getTypeWidth(Context
3094 .getTargetInfo()
3095 .getIntPtrType()) == 64;
3096 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3097 BuiltinID == PPC::BI__builtin_divweu ||
3098 BuiltinID == PPC::BI__builtin_divde ||
3099 BuiltinID == PPC::BI__builtin_divdeu;
3100
3101 if (Is64BitBltin && !IsTarget64Bit)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003102 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3103 << TheCall->getSourceRange();
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003104
3105 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3106 (BuiltinID == PPC::BI__builtin_bpermd &&
3107 !Context.getTargetInfo().hasFeature("bpermd")))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003108 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003109 << TheCall->getSourceRange();
3110
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003111 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3112 if (!Context.getTargetInfo().hasFeature("vsx"))
3113 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3114 << TheCall->getSourceRange();
3115 return false;
3116 };
3117
Kit Bartone50adcb2015-03-30 19:40:59 +00003118 switch (BuiltinID) {
3119 default: return false;
3120 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3121 case PPC::BI__builtin_altivec_crypto_vshasigmad:
3122 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3123 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3124 case PPC::BI__builtin_tbegin:
3125 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3126 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3127 case PPC::BI__builtin_tabortwc:
3128 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3129 case PPC::BI__builtin_tabortwci:
3130 case PPC::BI__builtin_tabortdci:
3131 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3132 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00003133 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00003134 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00003135 return SemaBuiltinVSX(TheCall);
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003136 case PPC::BI__builtin_unpack_vector_int128:
3137 return SemaVSXCheck(TheCall) ||
3138 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3139 case PPC::BI__builtin_pack_vector_int128:
3140 return SemaVSXCheck(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00003141 }
3142 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3143}
3144
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003145bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3146 CallExpr *TheCall) {
3147 if (BuiltinID == SystemZ::BI__builtin_tabort) {
3148 Expr *Arg = TheCall->getArg(0);
3149 llvm::APSInt AbortCode(32);
3150 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3151 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003152 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003153 << Arg->getSourceRange();
3154 }
3155
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003156 // For intrinsics which take an immediate value as part of the instruction,
3157 // range check them here.
3158 unsigned i = 0, l = 0, u = 0;
3159 switch (BuiltinID) {
3160 default: return false;
3161 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3162 case SystemZ::BI__builtin_s390_verimb:
3163 case SystemZ::BI__builtin_s390_verimh:
3164 case SystemZ::BI__builtin_s390_verimf:
3165 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3166 case SystemZ::BI__builtin_s390_vfaeb:
3167 case SystemZ::BI__builtin_s390_vfaeh:
3168 case SystemZ::BI__builtin_s390_vfaef:
3169 case SystemZ::BI__builtin_s390_vfaebs:
3170 case SystemZ::BI__builtin_s390_vfaehs:
3171 case SystemZ::BI__builtin_s390_vfaefs:
3172 case SystemZ::BI__builtin_s390_vfaezb:
3173 case SystemZ::BI__builtin_s390_vfaezh:
3174 case SystemZ::BI__builtin_s390_vfaezf:
3175 case SystemZ::BI__builtin_s390_vfaezbs:
3176 case SystemZ::BI__builtin_s390_vfaezhs:
3177 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003178 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003179 case SystemZ::BI__builtin_s390_vfidb:
3180 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3181 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003182 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003183 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3184 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3185 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3186 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3187 case SystemZ::BI__builtin_s390_vstrcb:
3188 case SystemZ::BI__builtin_s390_vstrch:
3189 case SystemZ::BI__builtin_s390_vstrcf:
3190 case SystemZ::BI__builtin_s390_vstrczb:
3191 case SystemZ::BI__builtin_s390_vstrczh:
3192 case SystemZ::BI__builtin_s390_vstrczf:
3193 case SystemZ::BI__builtin_s390_vstrcbs:
3194 case SystemZ::BI__builtin_s390_vstrchs:
3195 case SystemZ::BI__builtin_s390_vstrcfs:
3196 case SystemZ::BI__builtin_s390_vstrczbs:
3197 case SystemZ::BI__builtin_s390_vstrczhs:
3198 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003199 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3200 case SystemZ::BI__builtin_s390_vfminsb:
3201 case SystemZ::BI__builtin_s390_vfmaxsb:
3202 case SystemZ::BI__builtin_s390_vfmindb:
3203 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003204 }
3205 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003206}
3207
Craig Topper5ba2c502015-11-07 08:08:31 +00003208/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3209/// This checks that the target supports __builtin_cpu_supports and
3210/// that the string argument is constant and valid.
3211static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3212 Expr *Arg = TheCall->getArg(0);
3213
3214 // Check if the argument is a string literal.
3215 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003216 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper5ba2c502015-11-07 08:08:31 +00003217 << Arg->getSourceRange();
3218
3219 // Check the contents of the string.
3220 StringRef Feature =
3221 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3222 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003223 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
Craig Topper5ba2c502015-11-07 08:08:31 +00003224 << Arg->getSourceRange();
3225 return false;
3226}
3227
Craig Topper699ae0c2017-08-10 20:28:30 +00003228/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3229/// This checks that the target supports __builtin_cpu_is and
3230/// that the string argument is constant and valid.
3231static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3232 Expr *Arg = TheCall->getArg(0);
3233
3234 // Check if the argument is a string literal.
3235 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003236 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper699ae0c2017-08-10 20:28:30 +00003237 << Arg->getSourceRange();
3238
3239 // Check the contents of the string.
3240 StringRef Feature =
3241 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3242 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003243 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
Craig Topper699ae0c2017-08-10 20:28:30 +00003244 << Arg->getSourceRange();
3245 return false;
3246}
3247
Craig Toppera7e253e2016-09-23 04:48:31 +00003248// Check if the rounding mode is legal.
3249bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3250 // Indicates if this instruction has rounding control or just SAE.
3251 bool HasRC = false;
3252
3253 unsigned ArgNum = 0;
3254 switch (BuiltinID) {
3255 default:
3256 return false;
3257 case X86::BI__builtin_ia32_vcvttsd2si32:
3258 case X86::BI__builtin_ia32_vcvttsd2si64:
3259 case X86::BI__builtin_ia32_vcvttsd2usi32:
3260 case X86::BI__builtin_ia32_vcvttsd2usi64:
3261 case X86::BI__builtin_ia32_vcvttss2si32:
3262 case X86::BI__builtin_ia32_vcvttss2si64:
3263 case X86::BI__builtin_ia32_vcvttss2usi32:
3264 case X86::BI__builtin_ia32_vcvttss2usi64:
3265 ArgNum = 1;
3266 break;
Craig Topper2da60bc2018-06-21 05:01:01 +00003267 case X86::BI__builtin_ia32_maxpd512:
3268 case X86::BI__builtin_ia32_maxps512:
3269 case X86::BI__builtin_ia32_minpd512:
3270 case X86::BI__builtin_ia32_minps512:
3271 ArgNum = 2;
3272 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003273 case X86::BI__builtin_ia32_cvtps2pd512_mask:
3274 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3275 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3276 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3277 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3278 case X86::BI__builtin_ia32_cvttps2dq512_mask:
3279 case X86::BI__builtin_ia32_cvttps2qq512_mask:
3280 case X86::BI__builtin_ia32_cvttps2udq512_mask:
3281 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3282 case X86::BI__builtin_ia32_exp2pd_mask:
3283 case X86::BI__builtin_ia32_exp2ps_mask:
3284 case X86::BI__builtin_ia32_getexppd512_mask:
3285 case X86::BI__builtin_ia32_getexpps512_mask:
3286 case X86::BI__builtin_ia32_rcp28pd_mask:
3287 case X86::BI__builtin_ia32_rcp28ps_mask:
3288 case X86::BI__builtin_ia32_rsqrt28pd_mask:
3289 case X86::BI__builtin_ia32_rsqrt28ps_mask:
3290 case X86::BI__builtin_ia32_vcomisd:
3291 case X86::BI__builtin_ia32_vcomiss:
3292 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3293 ArgNum = 3;
3294 break;
3295 case X86::BI__builtin_ia32_cmppd512_mask:
3296 case X86::BI__builtin_ia32_cmpps512_mask:
3297 case X86::BI__builtin_ia32_cmpsd_mask:
3298 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003299 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003300 case X86::BI__builtin_ia32_getexpsd128_round_mask:
3301 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003302 case X86::BI__builtin_ia32_maxsd_round_mask:
3303 case X86::BI__builtin_ia32_maxss_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003304 case X86::BI__builtin_ia32_minsd_round_mask:
3305 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003306 case X86::BI__builtin_ia32_rcp28sd_round_mask:
3307 case X86::BI__builtin_ia32_rcp28ss_round_mask:
3308 case X86::BI__builtin_ia32_reducepd512_mask:
3309 case X86::BI__builtin_ia32_reduceps512_mask:
3310 case X86::BI__builtin_ia32_rndscalepd_mask:
3311 case X86::BI__builtin_ia32_rndscaleps_mask:
3312 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3313 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3314 ArgNum = 4;
3315 break;
3316 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003317 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003318 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003319 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003320 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003321 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003322 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003323 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003324 case X86::BI__builtin_ia32_rangepd512_mask:
3325 case X86::BI__builtin_ia32_rangeps512_mask:
3326 case X86::BI__builtin_ia32_rangesd128_round_mask:
3327 case X86::BI__builtin_ia32_rangess128_round_mask:
3328 case X86::BI__builtin_ia32_reducesd_mask:
3329 case X86::BI__builtin_ia32_reducess_mask:
3330 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3331 case X86::BI__builtin_ia32_rndscaless_round_mask:
3332 ArgNum = 5;
3333 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003334 case X86::BI__builtin_ia32_vcvtsd2si64:
3335 case X86::BI__builtin_ia32_vcvtsd2si32:
3336 case X86::BI__builtin_ia32_vcvtsd2usi32:
3337 case X86::BI__builtin_ia32_vcvtsd2usi64:
3338 case X86::BI__builtin_ia32_vcvtss2si32:
3339 case X86::BI__builtin_ia32_vcvtss2si64:
3340 case X86::BI__builtin_ia32_vcvtss2usi32:
3341 case X86::BI__builtin_ia32_vcvtss2usi64:
Craig Topper8bf793f2018-06-29 05:43:33 +00003342 case X86::BI__builtin_ia32_sqrtpd512:
3343 case X86::BI__builtin_ia32_sqrtps512:
Craig Topper7609f1c2016-10-01 21:03:50 +00003344 ArgNum = 1;
3345 HasRC = true;
3346 break;
Craig Topper3614b412018-06-10 06:01:42 +00003347 case X86::BI__builtin_ia32_addpd512:
3348 case X86::BI__builtin_ia32_addps512:
3349 case X86::BI__builtin_ia32_divpd512:
3350 case X86::BI__builtin_ia32_divps512:
3351 case X86::BI__builtin_ia32_mulpd512:
3352 case X86::BI__builtin_ia32_mulps512:
3353 case X86::BI__builtin_ia32_subpd512:
3354 case X86::BI__builtin_ia32_subps512:
Craig Topper8e066312016-11-07 07:01:09 +00003355 case X86::BI__builtin_ia32_cvtsi2sd64:
3356 case X86::BI__builtin_ia32_cvtsi2ss32:
3357 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00003358 case X86::BI__builtin_ia32_cvtusi2sd64:
3359 case X86::BI__builtin_ia32_cvtusi2ss32:
3360 case X86::BI__builtin_ia32_cvtusi2ss64:
3361 ArgNum = 2;
3362 HasRC = true;
3363 break;
3364 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3365 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3366 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3367 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3368 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3369 case X86::BI__builtin_ia32_cvtps2qq512_mask:
3370 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3371 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3372 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3373 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3374 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3375 ArgNum = 3;
3376 HasRC = true;
3377 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003378 case X86::BI__builtin_ia32_addss_round_mask:
3379 case X86::BI__builtin_ia32_addsd_round_mask:
3380 case X86::BI__builtin_ia32_divss_round_mask:
3381 case X86::BI__builtin_ia32_divsd_round_mask:
3382 case X86::BI__builtin_ia32_mulss_round_mask:
3383 case X86::BI__builtin_ia32_mulsd_round_mask:
3384 case X86::BI__builtin_ia32_subss_round_mask:
3385 case X86::BI__builtin_ia32_subsd_round_mask:
3386 case X86::BI__builtin_ia32_scalefpd512_mask:
3387 case X86::BI__builtin_ia32_scalefps512_mask:
3388 case X86::BI__builtin_ia32_scalefsd_round_mask:
3389 case X86::BI__builtin_ia32_scalefss_round_mask:
3390 case X86::BI__builtin_ia32_getmantpd512_mask:
3391 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003392 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3393 case X86::BI__builtin_ia32_sqrtsd_round_mask:
3394 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003395 case X86::BI__builtin_ia32_vfmaddsd3_mask:
3396 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3397 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3398 case X86::BI__builtin_ia32_vfmaddss3_mask:
3399 case X86::BI__builtin_ia32_vfmaddss3_maskz:
3400 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00003401 case X86::BI__builtin_ia32_vfmaddpd512_mask:
3402 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3403 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3404 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3405 case X86::BI__builtin_ia32_vfmaddps512_mask:
3406 case X86::BI__builtin_ia32_vfmaddps512_maskz:
3407 case X86::BI__builtin_ia32_vfmaddps512_mask3:
3408 case X86::BI__builtin_ia32_vfmsubps512_mask3:
3409 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3410 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3411 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3412 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3413 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3414 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3415 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3416 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00003417 ArgNum = 4;
3418 HasRC = true;
3419 break;
3420 case X86::BI__builtin_ia32_getmantsd_round_mask:
3421 case X86::BI__builtin_ia32_getmantss_round_mask:
3422 ArgNum = 5;
3423 HasRC = true;
3424 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003425 }
3426
3427 llvm::APSInt Result;
3428
3429 // We can't check the value of a dependent argument.
3430 Expr *Arg = TheCall->getArg(ArgNum);
3431 if (Arg->isTypeDependent() || Arg->isValueDependent())
3432 return false;
3433
3434 // Check constant-ness first.
3435 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3436 return true;
3437
3438 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3439 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3440 // combined with ROUND_NO_EXC.
3441 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3442 Result == 8/*ROUND_NO_EXC*/ ||
3443 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3444 return false;
3445
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003446 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3447 << Arg->getSourceRange();
Craig Toppera7e253e2016-09-23 04:48:31 +00003448}
3449
Craig Topperdf5beb22017-03-13 17:16:50 +00003450// Check if the gather/scatter scale is legal.
3451bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3452 CallExpr *TheCall) {
3453 unsigned ArgNum = 0;
3454 switch (BuiltinID) {
3455 default:
3456 return false;
3457 case X86::BI__builtin_ia32_gatherpfdpd:
3458 case X86::BI__builtin_ia32_gatherpfdps:
3459 case X86::BI__builtin_ia32_gatherpfqpd:
3460 case X86::BI__builtin_ia32_gatherpfqps:
3461 case X86::BI__builtin_ia32_scatterpfdpd:
3462 case X86::BI__builtin_ia32_scatterpfdps:
3463 case X86::BI__builtin_ia32_scatterpfqpd:
3464 case X86::BI__builtin_ia32_scatterpfqps:
3465 ArgNum = 3;
3466 break;
3467 case X86::BI__builtin_ia32_gatherd_pd:
3468 case X86::BI__builtin_ia32_gatherd_pd256:
3469 case X86::BI__builtin_ia32_gatherq_pd:
3470 case X86::BI__builtin_ia32_gatherq_pd256:
3471 case X86::BI__builtin_ia32_gatherd_ps:
3472 case X86::BI__builtin_ia32_gatherd_ps256:
3473 case X86::BI__builtin_ia32_gatherq_ps:
3474 case X86::BI__builtin_ia32_gatherq_ps256:
3475 case X86::BI__builtin_ia32_gatherd_q:
3476 case X86::BI__builtin_ia32_gatherd_q256:
3477 case X86::BI__builtin_ia32_gatherq_q:
3478 case X86::BI__builtin_ia32_gatherq_q256:
3479 case X86::BI__builtin_ia32_gatherd_d:
3480 case X86::BI__builtin_ia32_gatherd_d256:
3481 case X86::BI__builtin_ia32_gatherq_d:
3482 case X86::BI__builtin_ia32_gatherq_d256:
3483 case X86::BI__builtin_ia32_gather3div2df:
3484 case X86::BI__builtin_ia32_gather3div2di:
3485 case X86::BI__builtin_ia32_gather3div4df:
3486 case X86::BI__builtin_ia32_gather3div4di:
3487 case X86::BI__builtin_ia32_gather3div4sf:
3488 case X86::BI__builtin_ia32_gather3div4si:
3489 case X86::BI__builtin_ia32_gather3div8sf:
3490 case X86::BI__builtin_ia32_gather3div8si:
3491 case X86::BI__builtin_ia32_gather3siv2df:
3492 case X86::BI__builtin_ia32_gather3siv2di:
3493 case X86::BI__builtin_ia32_gather3siv4df:
3494 case X86::BI__builtin_ia32_gather3siv4di:
3495 case X86::BI__builtin_ia32_gather3siv4sf:
3496 case X86::BI__builtin_ia32_gather3siv4si:
3497 case X86::BI__builtin_ia32_gather3siv8sf:
3498 case X86::BI__builtin_ia32_gather3siv8si:
3499 case X86::BI__builtin_ia32_gathersiv8df:
3500 case X86::BI__builtin_ia32_gathersiv16sf:
3501 case X86::BI__builtin_ia32_gatherdiv8df:
3502 case X86::BI__builtin_ia32_gatherdiv16sf:
3503 case X86::BI__builtin_ia32_gathersiv8di:
3504 case X86::BI__builtin_ia32_gathersiv16si:
3505 case X86::BI__builtin_ia32_gatherdiv8di:
3506 case X86::BI__builtin_ia32_gatherdiv16si:
3507 case X86::BI__builtin_ia32_scatterdiv2df:
3508 case X86::BI__builtin_ia32_scatterdiv2di:
3509 case X86::BI__builtin_ia32_scatterdiv4df:
3510 case X86::BI__builtin_ia32_scatterdiv4di:
3511 case X86::BI__builtin_ia32_scatterdiv4sf:
3512 case X86::BI__builtin_ia32_scatterdiv4si:
3513 case X86::BI__builtin_ia32_scatterdiv8sf:
3514 case X86::BI__builtin_ia32_scatterdiv8si:
3515 case X86::BI__builtin_ia32_scattersiv2df:
3516 case X86::BI__builtin_ia32_scattersiv2di:
3517 case X86::BI__builtin_ia32_scattersiv4df:
3518 case X86::BI__builtin_ia32_scattersiv4di:
3519 case X86::BI__builtin_ia32_scattersiv4sf:
3520 case X86::BI__builtin_ia32_scattersiv4si:
3521 case X86::BI__builtin_ia32_scattersiv8sf:
3522 case X86::BI__builtin_ia32_scattersiv8si:
3523 case X86::BI__builtin_ia32_scattersiv8df:
3524 case X86::BI__builtin_ia32_scattersiv16sf:
3525 case X86::BI__builtin_ia32_scatterdiv8df:
3526 case X86::BI__builtin_ia32_scatterdiv16sf:
3527 case X86::BI__builtin_ia32_scattersiv8di:
3528 case X86::BI__builtin_ia32_scattersiv16si:
3529 case X86::BI__builtin_ia32_scatterdiv8di:
3530 case X86::BI__builtin_ia32_scatterdiv16si:
3531 ArgNum = 4;
3532 break;
3533 }
3534
3535 llvm::APSInt Result;
3536
3537 // We can't check the value of a dependent argument.
3538 Expr *Arg = TheCall->getArg(ArgNum);
3539 if (Arg->isTypeDependent() || Arg->isValueDependent())
3540 return false;
3541
3542 // Check constant-ness first.
3543 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3544 return true;
3545
3546 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3547 return false;
3548
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003549 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3550 << Arg->getSourceRange();
Craig Topperdf5beb22017-03-13 17:16:50 +00003551}
3552
Craig Topper51738f82018-04-26 20:14:46 +00003553static bool isX86_32Builtin(unsigned BuiltinID) {
3554 // These builtins only work on x86-32 targets.
3555 switch (BuiltinID) {
3556 case X86::BI__builtin_ia32_readeflags_u32:
3557 case X86::BI__builtin_ia32_writeeflags_u32:
3558 return true;
3559 }
3560
3561 return false;
3562}
3563
Craig Topperf0ddc892016-09-23 04:48:27 +00003564bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3565 if (BuiltinID == X86::BI__builtin_cpu_supports)
3566 return SemaBuiltinCpuSupports(*this, TheCall);
3567
Craig Topper699ae0c2017-08-10 20:28:30 +00003568 if (BuiltinID == X86::BI__builtin_cpu_is)
3569 return SemaBuiltinCpuIs(*this, TheCall);
3570
Craig Topper51738f82018-04-26 20:14:46 +00003571 // Check for 32-bit only builtins on a 64-bit target.
3572 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3573 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003574 return Diag(TheCall->getCallee()->getBeginLoc(),
Craig Topper51738f82018-04-26 20:14:46 +00003575 diag::err_32_bit_builtin_64_bit_tgt);
3576
Craig Toppera7e253e2016-09-23 04:48:31 +00003577 // If the intrinsic has rounding or SAE make sure its valid.
3578 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3579 return true;
3580
Craig Topperdf5beb22017-03-13 17:16:50 +00003581 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3582 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3583 return true;
3584
Craig Topperf0ddc892016-09-23 04:48:27 +00003585 // For intrinsics which take an immediate value as part of the instruction,
3586 // range check them here.
3587 int i = 0, l = 0, u = 0;
3588 switch (BuiltinID) {
3589 default:
3590 return false;
Craig Topper11899b02018-06-05 21:54:35 +00003591 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00003592 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003593 case X86::BI__builtin_ia32_vextractf128_pd256:
3594 case X86::BI__builtin_ia32_vextractf128_ps256:
3595 case X86::BI__builtin_ia32_vextractf128_si256:
3596 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00003597 case X86::BI__builtin_ia32_extractf64x4_mask:
3598 case X86::BI__builtin_ia32_extracti64x4_mask:
3599 case X86::BI__builtin_ia32_extractf32x8_mask:
3600 case X86::BI__builtin_ia32_extracti32x8_mask:
3601 case X86::BI__builtin_ia32_extractf64x2_256_mask:
3602 case X86::BI__builtin_ia32_extracti64x2_256_mask:
3603 case X86::BI__builtin_ia32_extractf32x4_256_mask:
3604 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003605 i = 1; l = 0; u = 1;
3606 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003607 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003608 case X86::BI__builtin_ia32_vinsertf128_pd256:
3609 case X86::BI__builtin_ia32_vinsertf128_ps256:
3610 case X86::BI__builtin_ia32_vinsertf128_si256:
3611 case X86::BI__builtin_ia32_insert128i256:
3612 case X86::BI__builtin_ia32_insertf32x8:
3613 case X86::BI__builtin_ia32_inserti32x8:
3614 case X86::BI__builtin_ia32_insertf64x4:
3615 case X86::BI__builtin_ia32_inserti64x4:
3616 case X86::BI__builtin_ia32_insertf64x2_256:
3617 case X86::BI__builtin_ia32_inserti64x2_256:
3618 case X86::BI__builtin_ia32_insertf32x4_256:
3619 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00003620 i = 2; l = 0; u = 1;
3621 break;
Craig Topperacf56012018-06-08 00:59:27 +00003622 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00003623 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003624 case X86::BI__builtin_ia32_vec_ext_v4si:
3625 case X86::BI__builtin_ia32_vec_ext_v4sf:
3626 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00003627 case X86::BI__builtin_ia32_extractf32x4_mask:
3628 case X86::BI__builtin_ia32_extracti32x4_mask:
3629 case X86::BI__builtin_ia32_extractf64x2_512_mask:
3630 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003631 i = 1; l = 0; u = 3;
3632 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003633 case X86::BI_mm_prefetch:
3634 case X86::BI__builtin_ia32_vec_ext_v8hi:
3635 case X86::BI__builtin_ia32_vec_ext_v8si:
3636 i = 1; l = 0; u = 7;
3637 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00003638 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00003639 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00003640 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00003641 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003642 case X86::BI__builtin_ia32_vec_set_v4si:
3643 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00003644 case X86::BI__builtin_ia32_shuf_f32x4_256:
3645 case X86::BI__builtin_ia32_shuf_f64x2_256:
3646 case X86::BI__builtin_ia32_shuf_i32x4_256:
3647 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00003648 case X86::BI__builtin_ia32_insertf64x2_512:
3649 case X86::BI__builtin_ia32_inserti64x2_512:
3650 case X86::BI__builtin_ia32_insertf32x4:
3651 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00003652 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003653 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00003654 case X86::BI__builtin_ia32_vpermil2pd:
3655 case X86::BI__builtin_ia32_vpermil2pd256:
3656 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00003657 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00003658 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003659 break;
Craig Topper95b0d732015-01-25 23:30:05 +00003660 case X86::BI__builtin_ia32_cmpb128_mask:
3661 case X86::BI__builtin_ia32_cmpw128_mask:
3662 case X86::BI__builtin_ia32_cmpd128_mask:
3663 case X86::BI__builtin_ia32_cmpq128_mask:
3664 case X86::BI__builtin_ia32_cmpb256_mask:
3665 case X86::BI__builtin_ia32_cmpw256_mask:
3666 case X86::BI__builtin_ia32_cmpd256_mask:
3667 case X86::BI__builtin_ia32_cmpq256_mask:
3668 case X86::BI__builtin_ia32_cmpb512_mask:
3669 case X86::BI__builtin_ia32_cmpw512_mask:
3670 case X86::BI__builtin_ia32_cmpd512_mask:
3671 case X86::BI__builtin_ia32_cmpq512_mask:
3672 case X86::BI__builtin_ia32_ucmpb128_mask:
3673 case X86::BI__builtin_ia32_ucmpw128_mask:
3674 case X86::BI__builtin_ia32_ucmpd128_mask:
3675 case X86::BI__builtin_ia32_ucmpq128_mask:
3676 case X86::BI__builtin_ia32_ucmpb256_mask:
3677 case X86::BI__builtin_ia32_ucmpw256_mask:
3678 case X86::BI__builtin_ia32_ucmpd256_mask:
3679 case X86::BI__builtin_ia32_ucmpq256_mask:
3680 case X86::BI__builtin_ia32_ucmpb512_mask:
3681 case X86::BI__builtin_ia32_ucmpw512_mask:
3682 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00003683 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00003684 case X86::BI__builtin_ia32_vpcomub:
3685 case X86::BI__builtin_ia32_vpcomuw:
3686 case X86::BI__builtin_ia32_vpcomud:
3687 case X86::BI__builtin_ia32_vpcomuq:
3688 case X86::BI__builtin_ia32_vpcomb:
3689 case X86::BI__builtin_ia32_vpcomw:
3690 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00003691 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00003692 case X86::BI__builtin_ia32_vec_set_v8hi:
3693 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00003694 i = 2; l = 0; u = 7;
3695 break;
Craig Topperacf56012018-06-08 00:59:27 +00003696 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003697 case X86::BI__builtin_ia32_roundps:
3698 case X86::BI__builtin_ia32_roundpd:
3699 case X86::BI__builtin_ia32_roundps256:
3700 case X86::BI__builtin_ia32_roundpd256:
Craig Topper03a1d482018-06-15 17:03:32 +00003701 case X86::BI__builtin_ia32_getmantpd128_mask:
3702 case X86::BI__builtin_ia32_getmantpd256_mask:
3703 case X86::BI__builtin_ia32_getmantps128_mask:
3704 case X86::BI__builtin_ia32_getmantps256_mask:
3705 case X86::BI__builtin_ia32_getmantpd512_mask:
3706 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003707 case X86::BI__builtin_ia32_vec_ext_v16qi:
3708 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003709 i = 1; l = 0; u = 15;
3710 break;
Craig Topper7d17d722018-06-08 00:00:21 +00003711 case X86::BI__builtin_ia32_pblendd128:
3712 case X86::BI__builtin_ia32_blendps:
3713 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00003714 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003715 case X86::BI__builtin_ia32_roundss:
3716 case X86::BI__builtin_ia32_roundsd:
3717 case X86::BI__builtin_ia32_rangepd128_mask:
3718 case X86::BI__builtin_ia32_rangepd256_mask:
3719 case X86::BI__builtin_ia32_rangepd512_mask:
3720 case X86::BI__builtin_ia32_rangeps128_mask:
3721 case X86::BI__builtin_ia32_rangeps256_mask:
3722 case X86::BI__builtin_ia32_rangeps512_mask:
3723 case X86::BI__builtin_ia32_getmantsd_round_mask:
3724 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003725 case X86::BI__builtin_ia32_vec_set_v16qi:
3726 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003727 i = 2; l = 0; u = 15;
3728 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003729 case X86::BI__builtin_ia32_vec_ext_v32qi:
3730 i = 1; l = 0; u = 31;
3731 break;
Craig Topper39c87102016-05-18 03:18:12 +00003732 case X86::BI__builtin_ia32_cmpps:
3733 case X86::BI__builtin_ia32_cmpss:
3734 case X86::BI__builtin_ia32_cmppd:
3735 case X86::BI__builtin_ia32_cmpsd:
3736 case X86::BI__builtin_ia32_cmpps256:
3737 case X86::BI__builtin_ia32_cmppd256:
3738 case X86::BI__builtin_ia32_cmpps128_mask:
3739 case X86::BI__builtin_ia32_cmppd128_mask:
3740 case X86::BI__builtin_ia32_cmpps256_mask:
3741 case X86::BI__builtin_ia32_cmppd256_mask:
3742 case X86::BI__builtin_ia32_cmpps512_mask:
3743 case X86::BI__builtin_ia32_cmppd512_mask:
3744 case X86::BI__builtin_ia32_cmpsd_mask:
3745 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003746 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00003747 i = 2; l = 0; u = 31;
3748 break;
Craig Topper03f4f042018-06-08 18:00:25 +00003749 case X86::BI__builtin_ia32_permdf256:
3750 case X86::BI__builtin_ia32_permdi256:
3751 case X86::BI__builtin_ia32_permdf512:
3752 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00003753 case X86::BI__builtin_ia32_vpermilps:
3754 case X86::BI__builtin_ia32_vpermilps256:
3755 case X86::BI__builtin_ia32_vpermilpd512:
3756 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00003757 case X86::BI__builtin_ia32_pshufd:
3758 case X86::BI__builtin_ia32_pshufd256:
3759 case X86::BI__builtin_ia32_pshufd512:
3760 case X86::BI__builtin_ia32_pshufhw:
3761 case X86::BI__builtin_ia32_pshufhw256:
3762 case X86::BI__builtin_ia32_pshufhw512:
3763 case X86::BI__builtin_ia32_pshuflw:
3764 case X86::BI__builtin_ia32_pshuflw256:
3765 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00003766 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00003767 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003768 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00003769 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3770 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003771 case X86::BI__builtin_ia32_rndscaleps_128_mask:
3772 case X86::BI__builtin_ia32_rndscalepd_128_mask:
3773 case X86::BI__builtin_ia32_rndscaleps_256_mask:
3774 case X86::BI__builtin_ia32_rndscalepd_256_mask:
3775 case X86::BI__builtin_ia32_rndscaleps_mask:
3776 case X86::BI__builtin_ia32_rndscalepd_mask:
3777 case X86::BI__builtin_ia32_reducepd128_mask:
3778 case X86::BI__builtin_ia32_reducepd256_mask:
3779 case X86::BI__builtin_ia32_reducepd512_mask:
3780 case X86::BI__builtin_ia32_reduceps128_mask:
3781 case X86::BI__builtin_ia32_reduceps256_mask:
3782 case X86::BI__builtin_ia32_reduceps512_mask:
Craig Topper0e9de762018-06-30 01:32:14 +00003783 case X86::BI__builtin_ia32_prold512:
3784 case X86::BI__builtin_ia32_prolq512:
3785 case X86::BI__builtin_ia32_prold128:
3786 case X86::BI__builtin_ia32_prold256:
3787 case X86::BI__builtin_ia32_prolq128:
3788 case X86::BI__builtin_ia32_prolq256:
3789 case X86::BI__builtin_ia32_prord512:
3790 case X86::BI__builtin_ia32_prorq512:
3791 case X86::BI__builtin_ia32_prord128:
3792 case X86::BI__builtin_ia32_prord256:
3793 case X86::BI__builtin_ia32_prorq128:
3794 case X86::BI__builtin_ia32_prorq256:
Craig Topper39c87102016-05-18 03:18:12 +00003795 case X86::BI__builtin_ia32_fpclasspd128_mask:
3796 case X86::BI__builtin_ia32_fpclasspd256_mask:
3797 case X86::BI__builtin_ia32_fpclassps128_mask:
3798 case X86::BI__builtin_ia32_fpclassps256_mask:
3799 case X86::BI__builtin_ia32_fpclassps512_mask:
3800 case X86::BI__builtin_ia32_fpclasspd512_mask:
3801 case X86::BI__builtin_ia32_fpclasssd_mask:
3802 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper31730ae2018-06-14 22:02:35 +00003803 case X86::BI__builtin_ia32_pslldqi128_byteshift:
3804 case X86::BI__builtin_ia32_pslldqi256_byteshift:
3805 case X86::BI__builtin_ia32_pslldqi512_byteshift:
3806 case X86::BI__builtin_ia32_psrldqi128_byteshift:
3807 case X86::BI__builtin_ia32_psrldqi256_byteshift:
3808 case X86::BI__builtin_ia32_psrldqi512_byteshift:
Craig Topper2aa8efc2018-08-31 18:22:52 +00003809 case X86::BI__builtin_ia32_kshiftliqi:
3810 case X86::BI__builtin_ia32_kshiftlihi:
3811 case X86::BI__builtin_ia32_kshiftlisi:
3812 case X86::BI__builtin_ia32_kshiftlidi:
3813 case X86::BI__builtin_ia32_kshiftriqi:
3814 case X86::BI__builtin_ia32_kshiftrihi:
3815 case X86::BI__builtin_ia32_kshiftrisi:
3816 case X86::BI__builtin_ia32_kshiftridi:
Craig Topper39c87102016-05-18 03:18:12 +00003817 i = 1; l = 0; u = 255;
3818 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00003819 case X86::BI__builtin_ia32_vperm2f128_pd256:
3820 case X86::BI__builtin_ia32_vperm2f128_ps256:
3821 case X86::BI__builtin_ia32_vperm2f128_si256:
3822 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00003823 case X86::BI__builtin_ia32_pblendw128:
3824 case X86::BI__builtin_ia32_pblendw256:
3825 case X86::BI__builtin_ia32_blendps256:
3826 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00003827 case X86::BI__builtin_ia32_palignr128:
3828 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00003829 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00003830 case X86::BI__builtin_ia32_alignq512:
3831 case X86::BI__builtin_ia32_alignd512:
3832 case X86::BI__builtin_ia32_alignd128:
3833 case X86::BI__builtin_ia32_alignd256:
3834 case X86::BI__builtin_ia32_alignq128:
3835 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00003836 case X86::BI__builtin_ia32_vcomisd:
3837 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00003838 case X86::BI__builtin_ia32_shuf_f32x4:
3839 case X86::BI__builtin_ia32_shuf_f64x2:
3840 case X86::BI__builtin_ia32_shuf_i32x4:
3841 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00003842 case X86::BI__builtin_ia32_shufpd512:
3843 case X86::BI__builtin_ia32_shufps:
3844 case X86::BI__builtin_ia32_shufps256:
3845 case X86::BI__builtin_ia32_shufps512:
Craig Topper91bbe982018-06-11 06:18:29 +00003846 case X86::BI__builtin_ia32_dbpsadbw128:
3847 case X86::BI__builtin_ia32_dbpsadbw256:
3848 case X86::BI__builtin_ia32_dbpsadbw512:
Craig Topper2527c372018-06-13 07:19:28 +00003849 case X86::BI__builtin_ia32_vpshldd128:
3850 case X86::BI__builtin_ia32_vpshldd256:
3851 case X86::BI__builtin_ia32_vpshldd512:
3852 case X86::BI__builtin_ia32_vpshldq128:
3853 case X86::BI__builtin_ia32_vpshldq256:
3854 case X86::BI__builtin_ia32_vpshldq512:
3855 case X86::BI__builtin_ia32_vpshldw128:
3856 case X86::BI__builtin_ia32_vpshldw256:
3857 case X86::BI__builtin_ia32_vpshldw512:
3858 case X86::BI__builtin_ia32_vpshrdd128:
3859 case X86::BI__builtin_ia32_vpshrdd256:
3860 case X86::BI__builtin_ia32_vpshrdd512:
3861 case X86::BI__builtin_ia32_vpshrdq128:
3862 case X86::BI__builtin_ia32_vpshrdq256:
3863 case X86::BI__builtin_ia32_vpshrdq512:
3864 case X86::BI__builtin_ia32_vpshrdw128:
3865 case X86::BI__builtin_ia32_vpshrdw256:
3866 case X86::BI__builtin_ia32_vpshrdw512:
Craig Topper39c87102016-05-18 03:18:12 +00003867 i = 2; l = 0; u = 255;
3868 break;
3869 case X86::BI__builtin_ia32_fixupimmpd512_mask:
3870 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3871 case X86::BI__builtin_ia32_fixupimmps512_mask:
3872 case X86::BI__builtin_ia32_fixupimmps512_maskz:
3873 case X86::BI__builtin_ia32_fixupimmsd_mask:
3874 case X86::BI__builtin_ia32_fixupimmsd_maskz:
3875 case X86::BI__builtin_ia32_fixupimmss_mask:
3876 case X86::BI__builtin_ia32_fixupimmss_maskz:
3877 case X86::BI__builtin_ia32_fixupimmpd128_mask:
3878 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3879 case X86::BI__builtin_ia32_fixupimmpd256_mask:
3880 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3881 case X86::BI__builtin_ia32_fixupimmps128_mask:
3882 case X86::BI__builtin_ia32_fixupimmps128_maskz:
3883 case X86::BI__builtin_ia32_fixupimmps256_mask:
3884 case X86::BI__builtin_ia32_fixupimmps256_maskz:
3885 case X86::BI__builtin_ia32_pternlogd512_mask:
3886 case X86::BI__builtin_ia32_pternlogd512_maskz:
3887 case X86::BI__builtin_ia32_pternlogq512_mask:
3888 case X86::BI__builtin_ia32_pternlogq512_maskz:
3889 case X86::BI__builtin_ia32_pternlogd128_mask:
3890 case X86::BI__builtin_ia32_pternlogd128_maskz:
3891 case X86::BI__builtin_ia32_pternlogd256_mask:
3892 case X86::BI__builtin_ia32_pternlogd256_maskz:
3893 case X86::BI__builtin_ia32_pternlogq128_mask:
3894 case X86::BI__builtin_ia32_pternlogq128_maskz:
3895 case X86::BI__builtin_ia32_pternlogq256_mask:
3896 case X86::BI__builtin_ia32_pternlogq256_maskz:
3897 i = 3; l = 0; u = 255;
3898 break;
Craig Topper9625db02017-03-12 22:19:10 +00003899 case X86::BI__builtin_ia32_gatherpfdpd:
3900 case X86::BI__builtin_ia32_gatherpfdps:
3901 case X86::BI__builtin_ia32_gatherpfqpd:
3902 case X86::BI__builtin_ia32_gatherpfqps:
3903 case X86::BI__builtin_ia32_scatterpfdpd:
3904 case X86::BI__builtin_ia32_scatterpfdps:
3905 case X86::BI__builtin_ia32_scatterpfqpd:
3906 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00003907 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00003908 break;
Craig Topper39c87102016-05-18 03:18:12 +00003909 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3910 case X86::BI__builtin_ia32_rndscaless_round_mask:
3911 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00003912 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003913 }
Chandler Carruth16e6bc22018-06-21 23:46:09 +00003914
3915 // Note that we don't force a hard error on the range check here, allowing
3916 // template-generated or macro-generated dead code to potentially have out-of-
3917 // range values. These need to code generate, but don't need to necessarily
3918 // make any sense. We use a warning that defaults to an error.
3919 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003920}
3921
Richard Smith55ce3522012-06-25 20:30:08 +00003922/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3923/// parameter with the FormatAttr's correct format_idx and firstDataArg.
3924/// Returns true when the format fits the function and the FormatStringInfo has
3925/// been populated.
3926bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3927 FormatStringInfo *FSI) {
3928 FSI->HasVAListArg = Format->getFirstArg() == 0;
3929 FSI->FormatIdx = Format->getFormatIdx() - 1;
3930 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003931
Richard Smith55ce3522012-06-25 20:30:08 +00003932 // The way the format attribute works in GCC, the implicit this argument
3933 // of member functions is counted. However, it doesn't appear in our own
3934 // lists, so decrement format_idx in that case.
3935 if (IsCXXMember) {
3936 if(FSI->FormatIdx == 0)
3937 return false;
3938 --FSI->FormatIdx;
3939 if (FSI->FirstDataArg != 0)
3940 --FSI->FirstDataArg;
3941 }
3942 return true;
3943}
Mike Stump11289f42009-09-09 15:08:12 +00003944
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003945/// Checks if a the given expression evaluates to null.
3946///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003947/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00003948static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003949 // If the expression has non-null type, it doesn't evaluate to null.
3950 if (auto nullability
3951 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3952 if (*nullability == NullabilityKind::NonNull)
3953 return false;
3954 }
3955
Ted Kremeneka146db32014-01-17 06:24:47 +00003956 // As a special case, transparent unions initialized with zero are
3957 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003958 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00003959 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3960 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003961 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00003962 if (const InitListExpr *ILE =
3963 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003964 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00003965 }
3966
3967 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00003968 return (!Expr->isValueDependent() &&
3969 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3970 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003971}
3972
3973static void CheckNonNullArgument(Sema &S,
3974 const Expr *ArgExpr,
3975 SourceLocation CallSiteLoc) {
3976 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00003977 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3978 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00003979}
3980
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003981bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3982 FormatStringInfo FSI;
3983 if ((GetFormatStringType(Format) == FST_NSString) &&
3984 getFormatStringInfo(Format, false, &FSI)) {
3985 Idx = FSI.FormatIdx;
3986 return true;
3987 }
3988 return false;
3989}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003990
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003991/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003992/// as formatting string to formatting method.
3993static void
3994DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3995 const NamedDecl *FDecl,
3996 Expr **Args,
3997 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003998 unsigned Idx = 0;
3999 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004000 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4001 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004002 Idx = 2;
4003 Format = true;
4004 }
4005 else
4006 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4007 if (S.GetFormatNSStringIdx(I, Idx)) {
4008 Format = true;
4009 break;
4010 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004011 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004012 if (!Format || NumArgs <= Idx)
4013 return;
4014 const Expr *FormatExpr = Args[Idx];
4015 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4016 FormatExpr = CSCE->getSubExpr();
4017 const StringLiteral *FormatString;
4018 if (const ObjCStringLiteral *OSL =
4019 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4020 FormatString = OSL->getString();
4021 else
4022 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4023 if (!FormatString)
4024 return;
4025 if (S.FormatStringHasSArg(FormatString)) {
4026 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4027 << "%s" << 1 << 1;
4028 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4029 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004030 }
4031}
4032
Douglas Gregorb4866e82015-06-19 18:13:19 +00004033/// Determine whether the given type has a non-null nullability annotation.
4034static bool isNonNullType(ASTContext &ctx, QualType type) {
4035 if (auto nullability = type->getNullability(ctx))
4036 return *nullability == NullabilityKind::NonNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00004037
Douglas Gregorb4866e82015-06-19 18:13:19 +00004038 return false;
4039}
4040
Ted Kremenek2bc73332014-01-17 06:24:43 +00004041static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00004042 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00004043 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00004044 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00004045 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004046 assert((FDecl || Proto) && "Need a function declaration or prototype");
4047
Ted Kremenek9aedc152014-01-17 06:24:56 +00004048 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00004049 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00004050 if (FDecl) {
4051 // Handle the nonnull attribute on the function/method declaration itself.
4052 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4053 if (!NonNull->args_size()) {
4054 // Easy case: all pointer arguments are nonnull.
4055 for (const auto *Arg : Args)
4056 if (S.isValidPointerAttrType(Arg->getType()))
4057 CheckNonNullArgument(S, Arg, CallSiteLoc);
4058 return;
4059 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004060
Joel E. Denny81508102018-03-13 14:51:22 +00004061 for (const ParamIdx &Idx : NonNull->args()) {
4062 unsigned IdxAST = Idx.getASTIndex();
4063 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00004064 continue;
4065 if (NonNullArgs.empty())
4066 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00004067 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004068 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004069 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004070 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004071
Douglas Gregorb4866e82015-06-19 18:13:19 +00004072 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4073 // Handle the nonnull attribute on the parameters of the
4074 // function/method.
4075 ArrayRef<ParmVarDecl*> parms;
4076 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4077 parms = FD->parameters();
4078 else
4079 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
Fangrui Song6907ce22018-07-30 19:24:48 +00004080
Douglas Gregorb4866e82015-06-19 18:13:19 +00004081 unsigned ParamIndex = 0;
4082 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4083 I != E; ++I, ++ParamIndex) {
4084 const ParmVarDecl *PVD = *I;
Fangrui Song6907ce22018-07-30 19:24:48 +00004085 if (PVD->hasAttr<NonNullAttr>() ||
Douglas Gregorb4866e82015-06-19 18:13:19 +00004086 isNonNullType(S.Context, PVD->getType())) {
4087 if (NonNullArgs.empty())
4088 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00004089
Douglas Gregorb4866e82015-06-19 18:13:19 +00004090 NonNullArgs.set(ParamIndex);
4091 }
4092 }
4093 } else {
4094 // If we have a non-function, non-method declaration but no
4095 // function prototype, try to dig out the function prototype.
4096 if (!Proto) {
4097 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4098 QualType type = VD->getType().getNonReferenceType();
4099 if (auto pointerType = type->getAs<PointerType>())
4100 type = pointerType->getPointeeType();
4101 else if (auto blockType = type->getAs<BlockPointerType>())
4102 type = blockType->getPointeeType();
4103 // FIXME: data member pointers?
4104
4105 // Dig out the function prototype, if there is one.
4106 Proto = type->getAs<FunctionProtoType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004107 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00004108 }
4109
4110 // Fill in non-null argument information from the nullability
4111 // information on the parameter types (if we have them).
4112 if (Proto) {
4113 unsigned Index = 0;
4114 for (auto paramType : Proto->getParamTypes()) {
4115 if (isNonNullType(S.Context, paramType)) {
4116 if (NonNullArgs.empty())
4117 NonNullArgs.resize(Args.size());
Fangrui Song6907ce22018-07-30 19:24:48 +00004118
Douglas Gregorb4866e82015-06-19 18:13:19 +00004119 NonNullArgs.set(Index);
4120 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004121
Douglas Gregorb4866e82015-06-19 18:13:19 +00004122 ++Index;
4123 }
4124 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004125 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004126
Douglas Gregorb4866e82015-06-19 18:13:19 +00004127 // Check for non-null arguments.
Fangrui Song6907ce22018-07-30 19:24:48 +00004128 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
Douglas Gregorb4866e82015-06-19 18:13:19 +00004129 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00004130 if (NonNullArgs[ArgIndex])
4131 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004132 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004133}
4134
Richard Smith55ce3522012-06-25 20:30:08 +00004135/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00004136/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4137/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004138void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00004139 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4140 bool IsMemberFunction, SourceLocation Loc,
4141 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00004142 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00004143 if (CurContext->isDependentContext())
4144 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00004145
Ted Kremenekb8176da2010-09-09 04:33:05 +00004146 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00004147 llvm::SmallBitVector CheckedVarArgs;
4148 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004149 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004150 // Only create vector if there are format attributes.
4151 CheckedVarArgs.resize(Args.size());
4152
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004153 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00004154 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004155 }
Richard Smithd7293d72013-08-05 18:49:43 +00004156 }
Richard Smith55ce3522012-06-25 20:30:08 +00004157
4158 // Refuse POD arguments that weren't caught by the format string
4159 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00004160 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4161 if (CallType != VariadicDoesNotApply &&
4162 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004163 unsigned NumParams = Proto ? Proto->getNumParams()
4164 : FDecl && isa<FunctionDecl>(FDecl)
4165 ? cast<FunctionDecl>(FDecl)->getNumParams()
4166 : FDecl && isa<ObjCMethodDecl>(FDecl)
4167 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4168 : 0;
4169
Alp Toker9cacbab2014-01-20 20:26:09 +00004170 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004171 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00004172 if (const Expr *Arg = Args[ArgIdx]) {
4173 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4174 checkVariadicArgument(Arg, CallType);
4175 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004176 }
Richard Smithd7293d72013-08-05 18:49:43 +00004177 }
Mike Stump11289f42009-09-09 15:08:12 +00004178
Douglas Gregorb4866e82015-06-19 18:13:19 +00004179 if (FDecl || Proto) {
4180 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004181
Richard Trieu41bc0992013-06-22 00:20:41 +00004182 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004183 if (FDecl) {
4184 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00004185 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004186 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004187 }
George Burgess IVce6284b2017-01-28 02:19:40 +00004188
4189 if (FD)
4190 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00004191}
4192
4193/// CheckConstructorCall - Check a constructor call for correctness and safety
4194/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004195void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4196 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004197 const FunctionProtoType *Proto,
4198 SourceLocation Loc) {
4199 VariadicCallType CallType =
4200 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00004201 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4202 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00004203}
4204
4205/// CheckFunctionCall - Check a direct function call for various correctness
4206/// and safety properties not strictly enforced by the C type system.
4207bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4208 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004209 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4210 isa<CXXMethodDecl>(FDecl);
4211 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4212 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00004213 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4214 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00004215 Expr** Args = TheCall->getArgs();
4216 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00004217
4218 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00004219 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004220 // If this is a call to a member operator, hide the first argument
4221 // from checkCall.
4222 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00004223 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00004224 ++Args;
4225 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00004226 } else if (IsMemberFunction)
4227 ImplicitThis =
4228 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4229
4230 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00004231 IsMemberFunction, TheCall->getRParenLoc(),
4232 TheCall->getCallee()->getSourceRange(), CallType);
4233
4234 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4235 // None of the checks below are needed for functions that don't have
4236 // simple names (e.g., C++ conversion functions).
4237 if (!FnInfo)
4238 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004239
Richard Trieua7f30b12016-12-06 01:42:28 +00004240 CheckAbsoluteValueFunction(TheCall, FDecl);
4241 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00004242
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004243 if (getLangOpts().ObjC)
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004244 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004245
Anna Zaks22122702012-01-17 00:37:07 +00004246 unsigned CMId = FDecl->getMemoryFunctionKind();
4247 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00004248 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00004249
Anna Zaks201d4892012-01-13 21:52:01 +00004250 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00004251 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00004252 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00004253 else if (CMId == Builtin::BIstrncat)
4254 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00004255 else
Anna Zaks22122702012-01-17 00:37:07 +00004256 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004257
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004258 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00004259}
4260
Fangrui Song6907ce22018-07-30 19:24:48 +00004261bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00004262 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00004263 VariadicCallType CallType =
4264 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004265
George Burgess IVce6284b2017-01-28 02:19:40 +00004266 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4267 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004268 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004269
4270 return false;
4271}
4272
Richard Trieu664c4c62013-06-20 21:03:13 +00004273bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4274 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00004275 QualType Ty;
4276 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004277 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004278 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004279 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004280 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004281 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004282
Douglas Gregorb4866e82015-06-19 18:13:19 +00004283 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4284 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004285 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004286
Richard Trieu664c4c62013-06-20 21:03:13 +00004287 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00004288 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00004289 CallType = VariadicDoesNotApply;
4290 } else if (Ty->isBlockPointerType()) {
4291 CallType = VariadicBlock;
4292 } else { // Ty->isFunctionPointerType()
4293 CallType = VariadicFunction;
4294 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004295
George Burgess IVce6284b2017-01-28 02:19:40 +00004296 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00004297 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4298 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00004299 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00004300
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004301 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00004302}
4303
Richard Trieu41bc0992013-06-22 00:20:41 +00004304/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4305/// such as function pointers returned from functions.
4306bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004307 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00004308 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00004309 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00004310 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004311 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00004312 TheCall->getCallee()->getSourceRange(), CallType);
4313
4314 return false;
4315}
4316
Tim Northovere94a34c2014-03-11 10:49:14 +00004317static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00004318 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00004319 return false;
4320
JF Bastiendda2cb12016-04-18 18:01:49 +00004321 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00004322 switch (Op) {
4323 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004324 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00004325 llvm_unreachable("There is no ordering argument for an init");
4326
4327 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004328 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00004329 case AtomicExpr::AO__atomic_load_n:
4330 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00004331 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4332 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004333
4334 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004335 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00004336 case AtomicExpr::AO__atomic_store:
4337 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00004338 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4339 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4340 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004341
4342 default:
4343 return true;
4344 }
4345}
4346
Richard Smithfeea8832012-04-12 05:08:17 +00004347ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4348 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004349 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4350 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004351
Yaxun Liu39195062017-08-04 18:16:31 +00004352 // All the non-OpenCL operations take one of the following forms.
4353 // The OpenCL operations take the __c11 forms with one extra argument for
4354 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00004355 enum {
4356 // C __c11_atomic_init(A *, C)
4357 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004358
Richard Smithfeea8832012-04-12 05:08:17 +00004359 // C __c11_atomic_load(A *, int)
4360 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004361
Richard Smithfeea8832012-04-12 05:08:17 +00004362 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00004363 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004364
Eric Fiselier8d662442016-03-30 23:39:56 +00004365 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00004366 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004367
Richard Smithfeea8832012-04-12 05:08:17 +00004368 // C __c11_atomic_add(A *, M, int)
4369 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004370
Richard Smithfeea8832012-04-12 05:08:17 +00004371 // C __atomic_exchange_n(A *, CP, int)
4372 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004373
Richard Smithfeea8832012-04-12 05:08:17 +00004374 // void __atomic_exchange(A *, C *, CP, int)
4375 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004376
Richard Smithfeea8832012-04-12 05:08:17 +00004377 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4378 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004379
Richard Smithfeea8832012-04-12 05:08:17 +00004380 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4381 GNUCmpXchg
4382 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004383
Yaxun Liu39195062017-08-04 18:16:31 +00004384 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00004385 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4386 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00004387 // where:
4388 // C is an appropriate type,
4389 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4390 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4391 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4392 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004393
Yaxun Liu39195062017-08-04 18:16:31 +00004394 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4395 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4396 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00004397 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4398 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4399 AtomicExpr::AO__atomic_load,
4400 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00004401 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4402 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4403 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4404 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4405 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00004406 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4407 Op == AtomicExpr::AO__atomic_store_n ||
4408 Op == AtomicExpr::AO__atomic_exchange_n ||
4409 Op == AtomicExpr::AO__atomic_compare_exchange_n;
4410 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004411 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00004412
4413 switch (Op) {
4414 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004415 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00004416 Form = Init;
4417 break;
4418
4419 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004420 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004421 case AtomicExpr::AO__atomic_load_n:
4422 Form = Load;
4423 break;
4424
Richard Smithfeea8832012-04-12 05:08:17 +00004425 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00004426 Form = LoadCopy;
4427 break;
4428
4429 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004430 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00004431 case AtomicExpr::AO__atomic_store:
4432 case AtomicExpr::AO__atomic_store_n:
4433 Form = Copy;
4434 break;
4435
4436 case AtomicExpr::AO__c11_atomic_fetch_add:
4437 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00004438 case AtomicExpr::AO__opencl_atomic_fetch_add:
4439 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4440 case AtomicExpr::AO__opencl_atomic_fetch_min:
4441 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004442 case AtomicExpr::AO__atomic_fetch_add:
4443 case AtomicExpr::AO__atomic_fetch_sub:
4444 case AtomicExpr::AO__atomic_add_fetch:
4445 case AtomicExpr::AO__atomic_sub_fetch:
4446 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00004447 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00004448 case AtomicExpr::AO__c11_atomic_fetch_and:
4449 case AtomicExpr::AO__c11_atomic_fetch_or:
4450 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00004451 case AtomicExpr::AO__opencl_atomic_fetch_and:
4452 case AtomicExpr::AO__opencl_atomic_fetch_or:
4453 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00004454 case AtomicExpr::AO__atomic_fetch_and:
4455 case AtomicExpr::AO__atomic_fetch_or:
4456 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004457 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004458 case AtomicExpr::AO__atomic_and_fetch:
4459 case AtomicExpr::AO__atomic_or_fetch:
4460 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004461 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00004462 Form = Arithmetic;
4463 break;
4464
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004465 case AtomicExpr::AO__atomic_fetch_min:
4466 case AtomicExpr::AO__atomic_fetch_max:
4467 IsMinMax = true;
4468 Form = Arithmetic;
4469 break;
4470
Richard Smithfeea8832012-04-12 05:08:17 +00004471 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00004472 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00004473 case AtomicExpr::AO__atomic_exchange_n:
4474 Form = Xchg;
4475 break;
4476
4477 case AtomicExpr::AO__atomic_exchange:
4478 Form = GNUXchg;
4479 break;
4480
4481 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4482 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00004483 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4484 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004485 Form = C11CmpXchg;
4486 break;
4487
4488 case AtomicExpr::AO__atomic_compare_exchange:
4489 case AtomicExpr::AO__atomic_compare_exchange_n:
4490 Form = GNUCmpXchg;
4491 break;
4492 }
4493
Yaxun Liu39195062017-08-04 18:16:31 +00004494 unsigned AdjustedNumArgs = NumArgs[Form];
4495 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4496 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00004497 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00004498 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004499 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4500 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4501 << TheCall->getCallee()->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004502 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00004503 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004504 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004505 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004506 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4507 << TheCall->getCallee()->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004508 return ExprError();
4509 }
4510
Richard Smithfeea8832012-04-12 05:08:17 +00004511 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004512 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00004513 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4514 if (ConvertedPtr.isInvalid())
4515 return ExprError();
4516
4517 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004518 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4519 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004520 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4521 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004522 return ExprError();
4523 }
4524
Richard Smithfeea8832012-04-12 05:08:17 +00004525 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4526 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4527 QualType ValType = AtomTy; // 'C'
4528 if (IsC11) {
4529 if (!AtomTy->isAtomicType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004530 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4531 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004532 return ExprError();
4533 }
JF Bastienb4b1f592018-08-02 17:35:46 +00004534 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
Yaxun Liu39195062017-08-04 18:16:31 +00004535 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004536 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00004537 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4538 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00004539 return ExprError();
4540 }
Richard Smithfeea8832012-04-12 05:08:17 +00004541 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00004542 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004543 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004544 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4545 << Ptr->getType() << Ptr->getSourceRange();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004546 return ExprError();
4547 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004548 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004549
Richard Smithfeea8832012-04-12 05:08:17 +00004550 // For an arithmetic operation, the implied arithmetic must be well-formed.
4551 if (Form == Arithmetic) {
4552 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004553 if (IsAddSub && !ValType->isIntegerType()
4554 && !ValType->isPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004555 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4556 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004557 return ExprError();
4558 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004559 if (IsMinMax) {
4560 const BuiltinType *BT = ValType->getAs<BuiltinType>();
4561 if (!BT || (BT->getKind() != BuiltinType::Int &&
4562 BT->getKind() != BuiltinType::UInt)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004563 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004564 return ExprError();
4565 }
4566 }
4567 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004568 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4569 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004570 return ExprError();
4571 }
David Majnemere85cff82015-01-28 05:48:06 +00004572 if (IsC11 && ValType->isPointerType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004573 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
David Majnemere85cff82015-01-28 05:48:06 +00004574 diag::err_incomplete_type)) {
4575 return ExprError();
4576 }
Richard Smithfeea8832012-04-12 05:08:17 +00004577 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4578 // For __atomic_*_n operations, the value type must be a scalar integral or
4579 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004580 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4581 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004582 return ExprError();
4583 }
4584
Eli Friedmanaa769812013-09-11 03:49:34 +00004585 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4586 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00004587 // For GNU atomics, require a trivially-copyable type. This is not part of
4588 // the GNU atomics specification, but we enforce it for sanity.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004589 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4590 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004591 return ExprError();
4592 }
4593
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004594 switch (ValType.getObjCLifetime()) {
4595 case Qualifiers::OCL_None:
4596 case Qualifiers::OCL_ExplicitNone:
4597 // okay
4598 break;
4599
4600 case Qualifiers::OCL_Weak:
4601 case Qualifiers::OCL_Strong:
4602 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00004603 // FIXME: Can this happen? By this point, ValType should be known
4604 // to be trivially copyable.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004605 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4606 << ValType << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004607 return ExprError();
4608 }
4609
JF Bastien7f0a05a2018-05-25 00:07:09 +00004610 // All atomic operations have an overload which takes a pointer to a volatile
4611 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4612 // into the result or the other operands. Similarly atomic_load takes a
4613 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00004614 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00004615 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004616 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00004617 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4618 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004619 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00004620 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004621 ResultType = Context.BoolTy;
4622
Richard Smithfeea8832012-04-12 05:08:17 +00004623 // The type of a parameter passed 'by value'. In the GNU atomics, such
4624 // arguments are actually passed as pointers.
4625 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00004626 bool IsPassedByAddress = false;
4627 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00004628 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00004629 IsPassedByAddress = true;
4630 }
Richard Smithfeea8832012-04-12 05:08:17 +00004631
JF Bastien7f0a05a2018-05-25 00:07:09 +00004632 // The first argument's non-CV pointer type is used to deduce the type of
4633 // subsequent arguments, except for:
4634 // - weak flag (always converted to bool)
4635 // - memory order (always converted to int)
4636 // - scope (always converted to int)
4637 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004638 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00004639 if (i < NumVals[Form] + 1) {
4640 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00004641 case 0:
4642 // The first argument is always a pointer. It has a fixed type.
4643 // It is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004644 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
JF Bastien7f0a05a2018-05-25 00:07:09 +00004645 // Nothing else to do: we already know all we want about this pointer.
4646 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00004647 case 1:
4648 // The second argument is the non-atomic operand. For arithmetic, this
4649 // is always passed by value, and for a compare_exchange it is always
4650 // passed by address. For the rest, GNU uses by-address and C11 uses
4651 // by-value.
4652 assert(Form != Load);
4653 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4654 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004655 else if (Form == Copy || Form == Xchg) {
4656 if (IsPassedByAddress)
4657 // The value pointer is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004658 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
Richard Smithfeea8832012-04-12 05:08:17 +00004659 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004660 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00004661 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004662 else {
4663 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00004664 // The value pointer is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004665 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
Alexander Richardson6d989432017-10-15 18:48:14 +00004666 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004667 // Keep address space of non-atomic pointer type.
4668 if (const PointerType *PtrTy =
4669 ValArg->getType()->getAs<PointerType>()) {
4670 AS = PtrTy->getPointeeType().getAddressSpace();
4671 }
4672 Ty = Context.getPointerType(
4673 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4674 }
Richard Smithfeea8832012-04-12 05:08:17 +00004675 break;
4676 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00004677 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00004678 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4679 if (IsPassedByAddress)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004680 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
Richard Smithfeea8832012-04-12 05:08:17 +00004681 Ty = ByValType;
4682 break;
4683 case 3:
4684 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4685 Ty = Context.BoolTy;
4686 break;
4687 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004688 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00004689 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004690 Ty = Context.IntTy;
4691 }
Richard Smithfeea8832012-04-12 05:08:17 +00004692
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004693 InitializedEntity Entity =
4694 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00004695 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004696 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4697 if (Arg.isInvalid())
4698 return true;
4699 TheCall->setArg(i, Arg.get());
4700 }
4701
Richard Smithfeea8832012-04-12 05:08:17 +00004702 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004703 SmallVector<Expr*, 5> SubExprs;
4704 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00004705 switch (Form) {
4706 case Init:
4707 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00004708 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004709 break;
4710 case Load:
4711 SubExprs.push_back(TheCall->getArg(1)); // Order
4712 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00004713 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00004714 case Copy:
4715 case Arithmetic:
4716 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004717 SubExprs.push_back(TheCall->getArg(2)); // Order
4718 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004719 break;
4720 case GNUXchg:
4721 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4722 SubExprs.push_back(TheCall->getArg(3)); // Order
4723 SubExprs.push_back(TheCall->getArg(1)); // Val1
4724 SubExprs.push_back(TheCall->getArg(2)); // Val2
4725 break;
4726 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004727 SubExprs.push_back(TheCall->getArg(3)); // Order
4728 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004729 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00004730 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00004731 break;
4732 case GNUCmpXchg:
4733 SubExprs.push_back(TheCall->getArg(4)); // Order
4734 SubExprs.push_back(TheCall->getArg(1)); // Val1
4735 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4736 SubExprs.push_back(TheCall->getArg(2)); // Val2
4737 SubExprs.push_back(TheCall->getArg(3)); // Weak
4738 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004739 }
Tim Northovere94a34c2014-03-11 10:49:14 +00004740
4741 if (SubExprs.size() >= 2 && Form != Init) {
4742 llvm::APSInt Result(32);
4743 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4744 !isValidOrderingForOp(Result.getSExtValue(), Op))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004745 Diag(SubExprs[1]->getBeginLoc(),
Tim Northoverc83472e2014-03-11 11:35:10 +00004746 diag::warn_atomic_op_has_invalid_memory_order)
4747 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00004748 }
4749
Yaxun Liu30d652a2017-08-15 16:02:49 +00004750 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4751 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4752 llvm::APSInt Result(32);
4753 if (Scope->isIntegerConstantExpr(Result, Context) &&
4754 !ScopeModel->isValid(Result.getZExtValue())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004755 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
Yaxun Liu30d652a2017-08-15 16:02:49 +00004756 << Scope->getSourceRange();
4757 }
4758 SubExprs.push_back(Scope);
4759 }
4760
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004761 AtomicExpr *AE =
4762 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4763 ResultType, Op, TheCall->getRParenLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00004764
Fariborz Jahanian615de762013-05-28 17:37:39 +00004765 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00004766 Op == AtomicExpr::AO__c11_atomic_store ||
4767 Op == AtomicExpr::AO__opencl_atomic_load ||
4768 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00004769 Context.AtomicUsesUnsupportedLibcall(AE))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004770 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
Yaxun Liu39195062017-08-04 18:16:31 +00004771 << ((Op == AtomicExpr::AO__c11_atomic_load ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004772 Op == AtomicExpr::AO__opencl_atomic_load)
4773 ? 0
4774 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004775
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004776 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004777}
4778
John McCall29ad95b2011-08-27 01:09:30 +00004779/// checkBuiltinArgument - Given a call to a builtin function, perform
4780/// normal type-checking on the given argument, updating the call in
4781/// place. This is useful when a builtin function requires custom
4782/// type-checking for some of its arguments but not necessarily all of
4783/// them.
4784///
4785/// Returns true on error.
4786static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4787 FunctionDecl *Fn = E->getDirectCallee();
4788 assert(Fn && "builtin call without direct callee!");
4789
4790 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4791 InitializedEntity Entity =
4792 InitializedEntity::InitializeParameter(S.Context, Param);
4793
4794 ExprResult Arg = E->getArg(0);
4795 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4796 if (Arg.isInvalid())
4797 return true;
4798
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004799 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00004800 return false;
4801}
4802
JF Bastiene77b48b2018-09-10 20:42:56 +00004803/// We have a call to a function like __sync_fetch_and_add, which is an
4804/// overloaded function based on the pointer type of its first argument.
4805/// The main ActOnCallExpr routines have already promoted the types of
4806/// arguments because all of these calls are prototyped as void(...).
Chris Lattnerdc046542009-05-08 06:58:22 +00004807///
4808/// This function goes through and does final semantic checking for these
JF Bastiene77b48b2018-09-10 20:42:56 +00004809/// builtins, as well as generating any warnings.
John McCalldadc5752010-08-24 06:29:42 +00004810ExprResult
4811Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
JF Bastiene77b48b2018-09-10 20:42:56 +00004812 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4813 Expr *Callee = TheCall->getCallee();
4814 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
Chris Lattnerdc046542009-05-08 06:58:22 +00004815 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4816
4817 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004818 if (TheCall->getNumArgs() < 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004819 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
JF Bastiene77b48b2018-09-10 20:42:56 +00004820 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004821 return ExprError();
4822 }
Mike Stump11289f42009-09-09 15:08:12 +00004823
Chris Lattnerdc046542009-05-08 06:58:22 +00004824 // Inspect the first argument of the atomic builtin. This should always be
4825 // a pointer type, whose element is an integral scalar or pointer type.
4826 // Because it is a pointer type, we don't have to worry about any implicit
4827 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004828 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00004829 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00004830 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4831 if (FirstArgResult.isInvalid())
4832 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004833 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00004834 TheCall->setArg(0, FirstArg);
4835
John McCall31168b02011-06-15 23:02:42 +00004836 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4837 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004838 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4839 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004840 return ExprError();
4841 }
Mike Stump11289f42009-09-09 15:08:12 +00004842
John McCall31168b02011-06-15 23:02:42 +00004843 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00004844 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004845 !ValType->isBlockPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004846 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4847 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004848 return ExprError();
4849 }
Chris Lattnerdc046542009-05-08 06:58:22 +00004850
Aaron Ballmana383c942018-05-05 17:38:42 +00004851 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004852 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
Aaron Ballmana383c942018-05-05 17:38:42 +00004853 << FirstArg->getType() << FirstArg->getSourceRange();
4854 return ExprError();
4855 }
4856
John McCall31168b02011-06-15 23:02:42 +00004857 switch (ValType.getObjCLifetime()) {
4858 case Qualifiers::OCL_None:
4859 case Qualifiers::OCL_ExplicitNone:
4860 // okay
4861 break;
4862
4863 case Qualifiers::OCL_Weak:
4864 case Qualifiers::OCL_Strong:
4865 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004866 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4867 << ValType << FirstArg->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004868 return ExprError();
4869 }
4870
John McCallb50451a2011-10-05 07:41:44 +00004871 // Strip any qualifiers off ValType.
4872 ValType = ValType.getUnqualifiedType();
4873
Chandler Carruth3973af72010-07-18 20:54:12 +00004874 // The majority of builtins return a value, but a few have special return
4875 // types, so allow them to override appropriately below.
4876 QualType ResultType = ValType;
4877
Chris Lattnerdc046542009-05-08 06:58:22 +00004878 // We need to figure out which concrete builtin this maps onto. For example,
4879 // __sync_fetch_and_add with a 2 byte object turns into
4880 // __sync_fetch_and_add_2.
4881#define BUILTIN_ROW(x) \
4882 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4883 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00004884
Chris Lattnerdc046542009-05-08 06:58:22 +00004885 static const unsigned BuiltinIndices[][5] = {
4886 BUILTIN_ROW(__sync_fetch_and_add),
4887 BUILTIN_ROW(__sync_fetch_and_sub),
4888 BUILTIN_ROW(__sync_fetch_and_or),
4889 BUILTIN_ROW(__sync_fetch_and_and),
4890 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00004891 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00004892
Chris Lattnerdc046542009-05-08 06:58:22 +00004893 BUILTIN_ROW(__sync_add_and_fetch),
4894 BUILTIN_ROW(__sync_sub_and_fetch),
4895 BUILTIN_ROW(__sync_and_and_fetch),
4896 BUILTIN_ROW(__sync_or_and_fetch),
4897 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00004898 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00004899
Chris Lattnerdc046542009-05-08 06:58:22 +00004900 BUILTIN_ROW(__sync_val_compare_and_swap),
4901 BUILTIN_ROW(__sync_bool_compare_and_swap),
4902 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00004903 BUILTIN_ROW(__sync_lock_release),
4904 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00004905 };
Mike Stump11289f42009-09-09 15:08:12 +00004906#undef BUILTIN_ROW
4907
Chris Lattnerdc046542009-05-08 06:58:22 +00004908 // Determine the index of the size.
4909 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00004910 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00004911 case 1: SizeIndex = 0; break;
4912 case 2: SizeIndex = 1; break;
4913 case 4: SizeIndex = 2; break;
4914 case 8: SizeIndex = 3; break;
4915 case 16: SizeIndex = 4; break;
4916 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004917 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4918 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004919 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00004920 }
Mike Stump11289f42009-09-09 15:08:12 +00004921
Chris Lattnerdc046542009-05-08 06:58:22 +00004922 // Each of these builtins has one pointer argument, followed by some number of
4923 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4924 // that we ignore. Find out which row of BuiltinIndices to read from as well
4925 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00004926 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00004927 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00004928 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00004929 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00004930 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Fangrui Song6907ce22018-07-30 19:24:48 +00004931 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +00004932 case Builtin::BI__sync_fetch_and_add_1:
4933 case Builtin::BI__sync_fetch_and_add_2:
4934 case Builtin::BI__sync_fetch_and_add_4:
4935 case Builtin::BI__sync_fetch_and_add_8:
4936 case Builtin::BI__sync_fetch_and_add_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004937 BuiltinIndex = 0;
Douglas Gregor73722482011-11-28 16:30:08 +00004938 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004939
4940 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +00004941 case Builtin::BI__sync_fetch_and_sub_1:
4942 case Builtin::BI__sync_fetch_and_sub_2:
4943 case Builtin::BI__sync_fetch_and_sub_4:
4944 case Builtin::BI__sync_fetch_and_sub_8:
4945 case Builtin::BI__sync_fetch_and_sub_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004946 BuiltinIndex = 1;
Douglas Gregor73722482011-11-28 16:30:08 +00004947 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004948
4949 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +00004950 case Builtin::BI__sync_fetch_and_or_1:
4951 case Builtin::BI__sync_fetch_and_or_2:
4952 case Builtin::BI__sync_fetch_and_or_4:
4953 case Builtin::BI__sync_fetch_and_or_8:
4954 case Builtin::BI__sync_fetch_and_or_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004955 BuiltinIndex = 2;
Douglas Gregor73722482011-11-28 16:30:08 +00004956 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004957
4958 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +00004959 case Builtin::BI__sync_fetch_and_and_1:
4960 case Builtin::BI__sync_fetch_and_and_2:
4961 case Builtin::BI__sync_fetch_and_and_4:
4962 case Builtin::BI__sync_fetch_and_and_8:
4963 case Builtin::BI__sync_fetch_and_and_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004964 BuiltinIndex = 3;
Douglas Gregor73722482011-11-28 16:30:08 +00004965 break;
Mike Stump11289f42009-09-09 15:08:12 +00004966
Fangrui Song6907ce22018-07-30 19:24:48 +00004967 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +00004968 case Builtin::BI__sync_fetch_and_xor_1:
4969 case Builtin::BI__sync_fetch_and_xor_2:
4970 case Builtin::BI__sync_fetch_and_xor_4:
4971 case Builtin::BI__sync_fetch_and_xor_8:
4972 case Builtin::BI__sync_fetch_and_xor_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004973 BuiltinIndex = 4;
Douglas Gregor73722482011-11-28 16:30:08 +00004974 break;
4975
Fangrui Song6907ce22018-07-30 19:24:48 +00004976 case Builtin::BI__sync_fetch_and_nand:
Hal Finkeld2208b52014-10-02 20:53:50 +00004977 case Builtin::BI__sync_fetch_and_nand_1:
4978 case Builtin::BI__sync_fetch_and_nand_2:
4979 case Builtin::BI__sync_fetch_and_nand_4:
4980 case Builtin::BI__sync_fetch_and_nand_8:
4981 case Builtin::BI__sync_fetch_and_nand_16:
4982 BuiltinIndex = 5;
4983 WarnAboutSemanticsChange = true;
4984 break;
4985
Fangrui Song6907ce22018-07-30 19:24:48 +00004986 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004987 case Builtin::BI__sync_add_and_fetch_1:
4988 case Builtin::BI__sync_add_and_fetch_2:
4989 case Builtin::BI__sync_add_and_fetch_4:
4990 case Builtin::BI__sync_add_and_fetch_8:
4991 case Builtin::BI__sync_add_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004992 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00004993 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004994
4995 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004996 case Builtin::BI__sync_sub_and_fetch_1:
4997 case Builtin::BI__sync_sub_and_fetch_2:
4998 case Builtin::BI__sync_sub_and_fetch_4:
4999 case Builtin::BI__sync_sub_and_fetch_8:
5000 case Builtin::BI__sync_sub_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005001 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00005002 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005003
5004 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005005 case Builtin::BI__sync_and_and_fetch_1:
5006 case Builtin::BI__sync_and_and_fetch_2:
5007 case Builtin::BI__sync_and_and_fetch_4:
5008 case Builtin::BI__sync_and_and_fetch_8:
5009 case Builtin::BI__sync_and_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005010 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00005011 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005012
5013 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005014 case Builtin::BI__sync_or_and_fetch_1:
5015 case Builtin::BI__sync_or_and_fetch_2:
5016 case Builtin::BI__sync_or_and_fetch_4:
5017 case Builtin::BI__sync_or_and_fetch_8:
5018 case Builtin::BI__sync_or_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005019 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00005020 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005021
5022 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00005023 case Builtin::BI__sync_xor_and_fetch_1:
5024 case Builtin::BI__sync_xor_and_fetch_2:
5025 case Builtin::BI__sync_xor_and_fetch_4:
5026 case Builtin::BI__sync_xor_and_fetch_8:
5027 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005028 BuiltinIndex = 10;
5029 break;
5030
Fangrui Song6907ce22018-07-30 19:24:48 +00005031 case Builtin::BI__sync_nand_and_fetch:
Hal Finkeld2208b52014-10-02 20:53:50 +00005032 case Builtin::BI__sync_nand_and_fetch_1:
5033 case Builtin::BI__sync_nand_and_fetch_2:
5034 case Builtin::BI__sync_nand_and_fetch_4:
5035 case Builtin::BI__sync_nand_and_fetch_8:
5036 case Builtin::BI__sync_nand_and_fetch_16:
5037 BuiltinIndex = 11;
5038 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00005039 break;
Mike Stump11289f42009-09-09 15:08:12 +00005040
Chris Lattnerdc046542009-05-08 06:58:22 +00005041 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005042 case Builtin::BI__sync_val_compare_and_swap_1:
5043 case Builtin::BI__sync_val_compare_and_swap_2:
5044 case Builtin::BI__sync_val_compare_and_swap_4:
5045 case Builtin::BI__sync_val_compare_and_swap_8:
5046 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005047 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00005048 NumFixed = 2;
5049 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005050
Chris Lattnerdc046542009-05-08 06:58:22 +00005051 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005052 case Builtin::BI__sync_bool_compare_and_swap_1:
5053 case Builtin::BI__sync_bool_compare_and_swap_2:
5054 case Builtin::BI__sync_bool_compare_and_swap_4:
5055 case Builtin::BI__sync_bool_compare_and_swap_8:
5056 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005057 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00005058 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00005059 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00005060 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005061
JF Bastien7f0a05a2018-05-25 00:07:09 +00005062 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00005063 case Builtin::BI__sync_lock_test_and_set_1:
5064 case Builtin::BI__sync_lock_test_and_set_2:
5065 case Builtin::BI__sync_lock_test_and_set_4:
5066 case Builtin::BI__sync_lock_test_and_set_8:
5067 case Builtin::BI__sync_lock_test_and_set_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005068 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00005069 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005070
Chris Lattnerdc046542009-05-08 06:58:22 +00005071 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00005072 case Builtin::BI__sync_lock_release_1:
5073 case Builtin::BI__sync_lock_release_2:
5074 case Builtin::BI__sync_lock_release_4:
5075 case Builtin::BI__sync_lock_release_8:
5076 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005077 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00005078 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00005079 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00005080 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005081
5082 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005083 case Builtin::BI__sync_swap_1:
5084 case Builtin::BI__sync_swap_2:
5085 case Builtin::BI__sync_swap_4:
5086 case Builtin::BI__sync_swap_8:
5087 case Builtin::BI__sync_swap_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005088 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00005089 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00005090 }
Mike Stump11289f42009-09-09 15:08:12 +00005091
Chris Lattnerdc046542009-05-08 06:58:22 +00005092 // Now that we know how many fixed arguments we expect, first check that we
5093 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005094 if (TheCall->getNumArgs() < 1+NumFixed) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005095 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5096 << 0 << 1 + NumFixed << TheCall->getNumArgs()
JF Bastiene77b48b2018-09-10 20:42:56 +00005097 << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005098 return ExprError();
5099 }
Mike Stump11289f42009-09-09 15:08:12 +00005100
JF Bastiene77b48b2018-09-10 20:42:56 +00005101 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5102 << Callee->getSourceRange();
5103
Hal Finkeld2208b52014-10-02 20:53:50 +00005104 if (WarnAboutSemanticsChange) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005105 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
JF Bastiene77b48b2018-09-10 20:42:56 +00005106 << Callee->getSourceRange();
Hal Finkeld2208b52014-10-02 20:53:50 +00005107 }
5108
Chris Lattner5b9241b2009-05-08 15:36:58 +00005109 // Get the decl for the concrete builtin from this, we can tell what the
5110 // concrete integer type we should convert to is.
5111 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00005112 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005113 FunctionDecl *NewBuiltinDecl;
5114 if (NewBuiltinID == BuiltinID)
5115 NewBuiltinDecl = FDecl;
5116 else {
5117 // Perform builtin lookup to avoid redeclaring it.
5118 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005119 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005120 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5121 assert(Res.getFoundDecl());
5122 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005123 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005124 return ExprError();
5125 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005126
John McCallcf142162010-08-07 06:22:56 +00005127 // The first argument --- the pointer --- has a fixed type; we
5128 // deduce the types of the rest of the arguments accordingly. Walk
5129 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00005130 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00005131 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00005132
Chris Lattnerdc046542009-05-08 06:58:22 +00005133 // GCC does an implicit conversion to the pointer or integer ValType. This
5134 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00005135 // Initialize the argument.
5136 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5137 ValType, /*consume*/ false);
5138 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00005139 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005140 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005141
Chris Lattnerdc046542009-05-08 06:58:22 +00005142 // Okay, we have something that *can* be converted to the right type. Check
5143 // to see if there is a potentially weird extension going on here. This can
5144 // happen when you do an atomic operation on something like an char* and
5145 // pass in 42. The 42 gets converted to char. This is even more strange
5146 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00005147 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005148 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00005149 }
Mike Stump11289f42009-09-09 15:08:12 +00005150
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005151 // Create a new DeclRefExpr to refer to the new decl.
5152 DeclRefExpr* NewDRE = DeclRefExpr::Create(
5153 Context,
5154 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00005155 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005156 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00005157 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005158 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00005159 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005160 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00005161
Chris Lattnerdc046542009-05-08 06:58:22 +00005162 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00005163 // FIXME: This loses syntactic information.
5164 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5165 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5166 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005167 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00005168
Chandler Carruthbc8cab12010-07-18 07:23:17 +00005169 // Change the result type of the call to match the original value type. This
5170 // is arbitrary, but the codegen for these builtins ins design to handle it
5171 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00005172 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005173
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005174 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00005175}
5176
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005177/// SemaBuiltinNontemporalOverloaded - We have a call to
5178/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5179/// overloaded function based on the pointer type of its last argument.
5180///
5181/// This function goes through and does final semantic checking for these
5182/// builtins.
5183ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5184 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5185 DeclRefExpr *DRE =
5186 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5187 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5188 unsigned BuiltinID = FDecl->getBuiltinID();
5189 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5190 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5191 "Unexpected nontemporal load/store builtin!");
5192 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5193 unsigned numArgs = isStore ? 2 : 1;
5194
5195 // Ensure that we have the proper number of arguments.
5196 if (checkArgCount(*this, TheCall, numArgs))
5197 return ExprError();
5198
5199 // Inspect the last argument of the nontemporal builtin. This should always
5200 // be a pointer type, from which we imply the type of the memory access.
5201 // Because it is a pointer type, we don't have to worry about any implicit
5202 // casts here.
5203 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5204 ExprResult PointerArgResult =
5205 DefaultFunctionArrayLvalueConversion(PointerArg);
5206
5207 if (PointerArgResult.isInvalid())
5208 return ExprError();
5209 PointerArg = PointerArgResult.get();
5210 TheCall->setArg(numArgs - 1, PointerArg);
5211
5212 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5213 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005214 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005215 << PointerArg->getType() << PointerArg->getSourceRange();
5216 return ExprError();
5217 }
5218
5219 QualType ValType = pointerType->getPointeeType();
5220
5221 // Strip any qualifiers off ValType.
5222 ValType = ValType.getUnqualifiedType();
5223 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5224 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5225 !ValType->isVectorType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005226 Diag(DRE->getBeginLoc(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005227 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5228 << PointerArg->getType() << PointerArg->getSourceRange();
5229 return ExprError();
5230 }
5231
5232 if (!isStore) {
5233 TheCall->setType(ValType);
5234 return TheCallResult;
5235 }
5236
5237 ExprResult ValArg = TheCall->getArg(0);
5238 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5239 Context, ValType, /*consume*/ false);
5240 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5241 if (ValArg.isInvalid())
5242 return ExprError();
5243
5244 TheCall->setArg(0, ValArg.get());
5245 TheCall->setType(Context.VoidTy);
5246 return TheCallResult;
5247}
5248
Chris Lattner6436fb62009-02-18 06:01:06 +00005249/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00005250/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00005251/// Note: It might also make sense to do the UTF-16 conversion here (would
5252/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00005253bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00005254 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00005255 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5256
Douglas Gregorfb65e592011-07-27 05:40:30 +00005257 if (!Literal || !Literal->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005258 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5259 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00005260 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00005261 }
Mike Stump11289f42009-09-09 15:08:12 +00005262
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005263 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005264 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005265 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00005266 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5267 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5268 llvm::UTF16 *ToPtr = &ToBuf[0];
5269
5270 llvm::ConversionResult Result =
5271 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5272 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005273 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00005274 if (Result != llvm::conversionOK)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005275 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5276 << Arg->getSourceRange();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005277 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00005278 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005279}
5280
Mehdi Amini06d367c2016-10-24 20:39:34 +00005281/// CheckObjCString - Checks that the format string argument to the os_log()
5282/// and os_trace() functions is correct, and converts it to const char *.
5283ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5284 Arg = Arg->IgnoreParenCasts();
5285 auto *Literal = dyn_cast<StringLiteral>(Arg);
5286 if (!Literal) {
5287 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5288 Literal = ObjcLiteral->getString();
5289 }
5290 }
5291
5292 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5293 return ExprError(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005294 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005295 << Arg->getSourceRange());
5296 }
5297
5298 ExprResult Result(Literal);
5299 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5300 InitializedEntity Entity =
5301 InitializedEntity::InitializeParameter(Context, ResultTy, false);
5302 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5303 return Result;
5304}
5305
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005306/// Check that the user is calling the appropriate va_start builtin for the
5307/// target and calling convention.
5308static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5309 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5310 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00005311 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005312 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00005313 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5314 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005315 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005316 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5317 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5318 if (IsMSVAStart) {
5319 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00005320 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005321 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005322 diag::err_ms_va_start_used_in_sysv_function);
5323 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00005324 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005325 // On x64 Windows, don't allow this in System V ABI functions.
5326 // (Yes, that means there's no corresponding way to support variadic
5327 // System V ABI functions on Windows.)
5328 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00005329 (!IsWindows && CC == CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005330 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005331 diag::err_va_start_used_in_wrong_abi_function)
5332 << !IsWindows;
5333 }
5334 return false;
5335 }
5336
5337 if (IsMSVAStart)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005338 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005339 return false;
5340}
5341
5342static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5343 ParmVarDecl **LastParam = nullptr) {
5344 // Determine whether the current function, block, or obj-c method is variadic
5345 // and get its parameter list.
5346 bool IsVariadic = false;
5347 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00005348 DeclContext *Caller = S.CurContext;
5349 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5350 IsVariadic = Block->isVariadic();
5351 Params = Block->parameters();
5352 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005353 IsVariadic = FD->isVariadic();
5354 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005355 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005356 IsVariadic = MD->isVariadic();
5357 // FIXME: This isn't correct for methods (results in bogus warning).
5358 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005359 } else if (isa<CapturedDecl>(Caller)) {
5360 // We don't support va_start in a CapturedDecl.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005361 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005362 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005363 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00005364 // This must be some other declcontext that parses exprs.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005365 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005366 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005367 }
5368
5369 if (!IsVariadic) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005370 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005371 return true;
5372 }
5373
5374 if (LastParam)
5375 *LastParam = Params.empty() ? nullptr : Params.back();
5376
5377 return false;
5378}
5379
Aaron Ballman68d50642018-06-19 14:53:20 +00005380/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5381/// for validity. Emit an error and return true on failure; return false
5382/// on success.
5383bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5384 Expr *Fn = TheCall->getCallee();
5385
5386 if (checkVAStartABI(*this, BuiltinID, Fn))
5387 return true;
5388
5389 if (TheCall->getNumArgs() > 2) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005390 Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005391 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005392 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5393 << Fn->getSourceRange()
5394 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005395 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005396 return true;
5397 }
5398
5399 if (TheCall->getNumArgs() < 2) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005400 return Diag(TheCall->getEndLoc(),
5401 diag::err_typecheck_call_too_few_args_at_least)
5402 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Aaron Ballman68d50642018-06-19 14:53:20 +00005403 }
5404
5405 // Type-check the first argument normally.
5406 if (checkBuiltinArgument(*this, TheCall, 0))
5407 return true;
5408
5409 // Check that the current function is variadic, and get its last parameter.
5410 ParmVarDecl *LastParam;
5411 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5412 return true;
5413
5414 // Verify that the second argument to the builtin is the last argument of the
5415 // current function or method.
5416 bool SecondArgIsLastNamedArgument = false;
5417 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5418
5419 // These are valid if SecondArgIsLastNamedArgument is false after the next
5420 // block.
5421 QualType Type;
5422 SourceLocation ParamLoc;
5423 bool IsCRegister = false;
5424
5425 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5426 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5427 SecondArgIsLastNamedArgument = PV == LastParam;
5428
5429 Type = PV->getType();
5430 ParamLoc = PV->getLocation();
5431 IsCRegister =
5432 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5433 }
5434 }
5435
5436 if (!SecondArgIsLastNamedArgument)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005437 Diag(TheCall->getArg(1)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005438 diag::warn_second_arg_of_va_start_not_last_named_param);
5439 else if (IsCRegister || Type->isReferenceType() ||
5440 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5441 // Promotable integers are UB, but enumerations need a bit of
5442 // extra checking to see what their promotable type actually is.
5443 if (!Type->isPromotableIntegerType())
5444 return false;
5445 if (!Type->isEnumeralType())
5446 return true;
5447 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5448 return !(ED &&
5449 Context.typesAreCompatible(ED->getPromotionType(), Type));
5450 }()) {
5451 unsigned Reason = 0;
5452 if (Type->isReferenceType()) Reason = 1;
5453 else if (IsCRegister) Reason = 2;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005454 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
Aaron Ballman68d50642018-06-19 14:53:20 +00005455 Diag(ParamLoc, diag::note_parameter_type) << Type;
5456 }
5457
5458 TheCall->setType(Context.VoidTy);
5459 return false;
5460}
5461
5462bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5463 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5464 // const char *named_addr);
5465
5466 Expr *Func = Call->getCallee();
5467
5468 if (Call->getNumArgs() < 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005469 return Diag(Call->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005470 diag::err_typecheck_call_too_few_args_at_least)
5471 << 0 /*function call*/ << 3 << Call->getNumArgs();
5472
5473 // Type-check the first argument normally.
5474 if (checkBuiltinArgument(*this, Call, 0))
5475 return true;
5476
5477 // Check that the current function is variadic.
5478 if (checkVAStartIsInVariadicFunction(*this, Func))
5479 return true;
5480
5481 // __va_start on Windows does not validate the parameter qualifiers
5482
5483 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5484 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5485
5486 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5487 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5488
5489 const QualType &ConstCharPtrTy =
5490 Context.getPointerType(Context.CharTy.withConst());
5491 if (!Arg1Ty->isPointerType() ||
5492 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005493 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5494 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5495 << 0 /* qualifier difference */
5496 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005497 << 2 << Arg1->getType() << ConstCharPtrTy;
5498
5499 const QualType SizeTy = Context.getSizeType();
5500 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005501 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5502 << Arg2->getType() << SizeTy << 1 /* different class */
5503 << 0 /* qualifier difference */
5504 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005505 << 3 << Arg2->getType() << SizeTy;
5506
5507 return false;
5508}
5509
5510/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5511/// friends. This is declared to take (...), so we have to check everything.
5512bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5513 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005514 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5515 << 0 << 2 << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005516 if (TheCall->getNumArgs() > 2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005517 return Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005518 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005519 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5520 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005521 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005522
5523 ExprResult OrigArg0 = TheCall->getArg(0);
5524 ExprResult OrigArg1 = TheCall->getArg(1);
5525
5526 // Do standard promotions between the two arguments, returning their common
5527 // type.
5528 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5529 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5530 return true;
5531
5532 // Make sure any conversions are pushed back into the call; this is
5533 // type safe since unordered compare builtins are declared as "_Bool
5534 // foo(...)".
5535 TheCall->setArg(0, OrigArg0.get());
5536 TheCall->setArg(1, OrigArg1.get());
5537
5538 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5539 return false;
5540
5541 // If the common type isn't a real floating type, then the arguments were
5542 // invalid for this operation.
5543 if (Res.isNull() || !Res->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005544 return Diag(OrigArg0.get()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005545 diag::err_typecheck_call_invalid_ordered_compare)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005546 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5547 << SourceRange(OrigArg0.get()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005548 OrigArg1.get()->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005549
5550 return false;
5551}
5552
5553/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5554/// __builtin_isnan and friends. This is declared to take (...), so we have
5555/// to check everything. We expect the last argument to be a floating point
5556/// value.
5557bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5558 if (TheCall->getNumArgs() < NumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005559 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5560 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005561 if (TheCall->getNumArgs() > NumArgs)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005562 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005563 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005564 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5565 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005566 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005567
5568 Expr *OrigArg = TheCall->getArg(NumArgs-1);
5569
5570 if (OrigArg->isTypeDependent())
5571 return false;
5572
5573 // This operation requires a non-_Complex floating-point number.
5574 if (!OrigArg->getType()->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005575 return Diag(OrigArg->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005576 diag::err_typecheck_call_invalid_unary_fp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005577 << OrigArg->getType() << OrigArg->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005578
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005579 // If this is an implicit conversion from float -> float, double, or
5580 // long double, remove it.
Aaron Ballman68d50642018-06-19 14:53:20 +00005581 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5582 // Only remove standard FloatCasts, leaving other casts inplace
5583 if (Cast->getCastKind() == CK_FloatingCast) {
5584 Expr *CastArg = Cast->getSubExpr();
5585 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005586 assert(
5587 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5588 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5589 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5590 "promotion from float to either float, double, or long double is "
5591 "the only expected cast here");
Aaron Ballman68d50642018-06-19 14:53:20 +00005592 Cast->setSubExpr(nullptr);
5593 TheCall->setArg(NumArgs-1, CastArg);
5594 }
5595 }
5596 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005597
Aaron Ballman68d50642018-06-19 14:53:20 +00005598 return false;
5599}
5600
5601// Customized Sema Checking for VSX builtins that have the following signature:
5602// vector [...] builtinName(vector [...], vector [...], const int);
5603// Which takes the same type of vectors (any legal vector type) for the first
5604// two arguments and takes compile time constant for the third argument.
5605// Example builtins are :
5606// vector double vec_xxpermdi(vector double, vector double, int);
5607// vector short vec_xxsldwi(vector short, vector short, int);
5608bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5609 unsigned ExpectedNumArgs = 3;
5610 if (TheCall->getNumArgs() < ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005611 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005612 diag::err_typecheck_call_too_few_args_at_least)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005613 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
Aaron Ballman68d50642018-06-19 14:53:20 +00005614 << TheCall->getSourceRange();
5615
5616 if (TheCall->getNumArgs() > ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005617 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005618 diag::err_typecheck_call_too_many_args_at_most)
5619 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5620 << TheCall->getSourceRange();
5621
5622 // Check the third argument is a compile time constant
5623 llvm::APSInt Value;
5624 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005625 return Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005626 diag::err_vsx_builtin_nonconstant_argument)
5627 << 3 /* argument index */ << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005628 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005629 TheCall->getArg(2)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005630
5631 QualType Arg1Ty = TheCall->getArg(0)->getType();
5632 QualType Arg2Ty = TheCall->getArg(1)->getType();
5633
5634 // Check the type of argument 1 and argument 2 are vectors.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005635 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
Aaron Ballman68d50642018-06-19 14:53:20 +00005636 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5637 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5638 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5639 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005640 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005641 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005642 }
5643
5644 // Check the first two arguments are the same type.
5645 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5646 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5647 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005648 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005649 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005650 }
5651
5652 // When default clang type checking is turned off and the customized type
5653 // checking is used, the returning type of the function must be explicitly
5654 // set. Otherwise it is _Bool by default.
5655 TheCall->setType(Arg1Ty);
5656
5657 return false;
5658}
5659
5660/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5661// This is declared to take (...), so we have to check everything.
5662ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5663 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005664 return ExprError(Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005665 diag::err_typecheck_call_too_few_args_at_least)
5666 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5667 << TheCall->getSourceRange());
5668
5669 // Determine which of the following types of shufflevector we're checking:
5670 // 1) unary, vector mask: (lhs, mask)
5671 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5672 QualType resType = TheCall->getArg(0)->getType();
5673 unsigned numElements = 0;
5674
5675 if (!TheCall->getArg(0)->isTypeDependent() &&
5676 !TheCall->getArg(1)->isTypeDependent()) {
5677 QualType LHSType = TheCall->getArg(0)->getType();
5678 QualType RHSType = TheCall->getArg(1)->getType();
5679
5680 if (!LHSType->isVectorType() || !RHSType->isVectorType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005681 return ExprError(
5682 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5683 << TheCall->getDirectCallee()
5684 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005685 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005686
5687 numElements = LHSType->getAs<VectorType>()->getNumElements();
5688 unsigned numResElements = TheCall->getNumArgs() - 2;
5689
5690 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5691 // with mask. If so, verify that RHS is an integer vector type with the
5692 // same number of elts as lhs.
5693 if (TheCall->getNumArgs() == 2) {
5694 if (!RHSType->hasIntegerRepresentation() ||
5695 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005696 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005697 diag::err_vec_builtin_incompatible_vector)
5698 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005699 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005700 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005701 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005702 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005703 diag::err_vec_builtin_incompatible_vector)
5704 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005705 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005706 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005707 } else if (numElements != numResElements) {
5708 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5709 resType = Context.getVectorType(eltType, numResElements,
5710 VectorType::GenericVector);
5711 }
5712 }
5713
5714 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5715 if (TheCall->getArg(i)->isTypeDependent() ||
5716 TheCall->getArg(i)->isValueDependent())
5717 continue;
5718
5719 llvm::APSInt Result(32);
5720 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005721 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005722 diag::err_shufflevector_nonconstant_argument)
5723 << TheCall->getArg(i)->getSourceRange());
5724
5725 // Allow -1 which will be translated to undef in the IR.
5726 if (Result.isSigned() && Result.isAllOnesValue())
5727 continue;
5728
5729 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005730 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005731 diag::err_shufflevector_argument_too_large)
5732 << TheCall->getArg(i)->getSourceRange());
5733 }
5734
5735 SmallVector<Expr*, 32> exprs;
5736
5737 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5738 exprs.push_back(TheCall->getArg(i));
5739 TheCall->setArg(i, nullptr);
5740 }
5741
5742 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005743 TheCall->getCallee()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005744 TheCall->getRParenLoc());
5745}
5746
5747/// SemaConvertVectorExpr - Handle __builtin_convertvector
5748ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5749 SourceLocation BuiltinLoc,
5750 SourceLocation RParenLoc) {
5751 ExprValueKind VK = VK_RValue;
5752 ExprObjectKind OK = OK_Ordinary;
5753 QualType DstTy = TInfo->getType();
5754 QualType SrcTy = E->getType();
5755
5756 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5757 return ExprError(Diag(BuiltinLoc,
5758 diag::err_convertvector_non_vector)
5759 << E->getSourceRange());
5760 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5761 return ExprError(Diag(BuiltinLoc,
5762 diag::err_convertvector_non_vector_type));
5763
5764 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5765 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5766 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5767 if (SrcElts != DstElts)
5768 return ExprError(Diag(BuiltinLoc,
5769 diag::err_convertvector_incompatible_vector)
5770 << E->getSourceRange());
5771 }
5772
5773 return new (Context)
5774 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5775}
5776
5777/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5778// This is declared to take (const void*, ...) and can take two
5779// optional constant int args.
5780bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5781 unsigned NumArgs = TheCall->getNumArgs();
5782
5783 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005784 return Diag(TheCall->getEndLoc(),
5785 diag::err_typecheck_call_too_many_args_at_most)
5786 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005787
5788 // Argument 0 is checked for us and the remaining arguments must be
5789 // constant integers.
5790 for (unsigned i = 1; i != NumArgs; ++i)
Richard Sandiford28940af2014-04-16 08:47:51 +00005791 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005792 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005793
Warren Hunt20e4a5d2014-02-21 23:08:53 +00005794 return false;
5795}
5796
Hal Finkelf0417332014-07-17 14:25:55 +00005797/// SemaBuiltinAssume - Handle __assume (MS Extension).
5798// __assume does not evaluate its arguments, and should warn if its argument
5799// has side effects.
5800bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5801 Expr *Arg = TheCall->getArg(0);
5802 if (Arg->isInstantiationDependent()) return false;
5803
5804 if (Arg->HasSideEffects(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005805 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5806 << Arg->getSourceRange()
5807 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
Hal Finkelbcc06082014-09-07 22:58:14 +00005808
5809 return false;
5810}
5811
David Majnemer86b1bfa2016-10-31 18:07:57 +00005812/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00005813/// as (size_t, size_t) where the second size_t must be a power of 2 greater
5814/// than 8.
5815bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5816 // The alignment must be a constant integer.
5817 Expr *Arg = TheCall->getArg(1);
5818
5819 // We can't check the value of a dependent argument.
5820 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00005821 if (const auto *UE =
5822 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
Richard Smith6822bd72018-10-26 19:26:45 +00005823 if (UE->getKind() == UETT_AlignOf ||
5824 UE->getKind() == UETT_PreferredAlignOf)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005825 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5826 << Arg->getSourceRange();
David Majnemer86b1bfa2016-10-31 18:07:57 +00005827
David Majnemer51169932016-10-31 05:37:48 +00005828 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5829
5830 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005831 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5832 << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005833
5834 if (Result < Context.getCharWidth())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005835 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5836 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005837
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005838 if (Result > std::numeric_limits<int32_t>::max())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005839 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5840 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005841 }
5842
5843 return false;
5844}
5845
5846/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00005847/// as (const void*, size_t, ...) and can take one optional constant int arg.
5848bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5849 unsigned NumArgs = TheCall->getNumArgs();
5850
5851 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005852 return Diag(TheCall->getEndLoc(),
5853 diag::err_typecheck_call_too_many_args_at_most)
5854 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00005855
5856 // The alignment must be a constant integer.
5857 Expr *Arg = TheCall->getArg(1);
5858
5859 // We can't check the value of a dependent argument.
5860 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5861 llvm::APSInt Result;
5862 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5863 return true;
5864
5865 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005866 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5867 << Arg->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00005868 }
5869
5870 if (NumArgs > 2) {
5871 ExprResult Arg(TheCall->getArg(2));
5872 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5873 Context.getSizeType(), false);
5874 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5875 if (Arg.isInvalid()) return true;
5876 TheCall->setArg(2, Arg.get());
5877 }
Hal Finkelf0417332014-07-17 14:25:55 +00005878
5879 return false;
5880}
5881
Mehdi Amini06d367c2016-10-24 20:39:34 +00005882bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5883 unsigned BuiltinID =
5884 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5885 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5886
5887 unsigned NumArgs = TheCall->getNumArgs();
5888 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5889 if (NumArgs < NumRequiredArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005890 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005891 << 0 /* function call */ << NumRequiredArgs << NumArgs
5892 << TheCall->getSourceRange();
5893 }
5894 if (NumArgs >= NumRequiredArgs + 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005895 return Diag(TheCall->getEndLoc(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005896 diag::err_typecheck_call_too_many_args_at_most)
5897 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5898 << TheCall->getSourceRange();
5899 }
5900 unsigned i = 0;
5901
5902 // For formatting call, check buffer arg.
5903 if (!IsSizeCall) {
5904 ExprResult Arg(TheCall->getArg(i));
5905 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5906 Context, Context.VoidPtrTy, false);
5907 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5908 if (Arg.isInvalid())
5909 return true;
5910 TheCall->setArg(i, Arg.get());
5911 i++;
5912 }
5913
5914 // Check string literal arg.
5915 unsigned FormatIdx = i;
5916 {
5917 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5918 if (Arg.isInvalid())
5919 return true;
5920 TheCall->setArg(i, Arg.get());
5921 i++;
5922 }
5923
5924 // Make sure variadic args are scalar.
5925 unsigned FirstDataArg = i;
5926 while (i < NumArgs) {
5927 ExprResult Arg = DefaultVariadicArgumentPromotion(
5928 TheCall->getArg(i), VariadicFunction, nullptr);
5929 if (Arg.isInvalid())
5930 return true;
5931 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5932 if (ArgSize.getQuantity() >= 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005933 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005934 << i << (int)ArgSize.getQuantity() << 0xff
5935 << TheCall->getSourceRange();
5936 }
5937 TheCall->setArg(i, Arg.get());
5938 i++;
5939 }
5940
5941 // Check formatting specifiers. NOTE: We're only doing this for the non-size
5942 // call to avoid duplicate diagnostics.
5943 if (!IsSizeCall) {
5944 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5945 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5946 bool Success = CheckFormatArguments(
5947 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005948 VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005949 CheckedVarArgs);
5950 if (!Success)
5951 return true;
5952 }
5953
5954 if (IsSizeCall) {
5955 TheCall->setType(Context.getSizeType());
5956 } else {
5957 TheCall->setType(Context.VoidPtrTy);
5958 }
5959 return false;
5960}
5961
Eric Christopher8d0c6212010-04-17 02:26:23 +00005962/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5963/// TheCall is a constant expression.
5964bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5965 llvm::APSInt &Result) {
5966 Expr *Arg = TheCall->getArg(ArgNum);
5967 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5968 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00005969
Eric Christopher8d0c6212010-04-17 02:26:23 +00005970 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00005971
Eric Christopher8d0c6212010-04-17 02:26:23 +00005972 if (!Arg->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005973 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5974 << FDecl->getDeclName() << Arg->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00005975
Chris Lattnerd545ad12009-09-23 06:06:36 +00005976 return false;
5977}
5978
Richard Sandiford28940af2014-04-16 08:47:51 +00005979/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5980/// TheCall is a constant expression in the range [Low, High].
5981bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005982 int Low, int High, bool RangeIsError) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00005983 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005984
5985 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00005986 Expr *Arg = TheCall->getArg(ArgNum);
5987 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005988 return false;
5989
Eric Christopher8d0c6212010-04-17 02:26:23 +00005990 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00005991 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005992 return true;
5993
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005994 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5995 if (RangeIsError)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005996 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005997 << Result.toString(10) << Low << High << Arg->getSourceRange();
5998 else
5999 // Defer the warning until we know if the code will be emitted so that
6000 // dead code can ignore this.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006001 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6002 PDiag(diag::warn_argument_invalid_range)
6003 << Result.toString(10) << Low << High
6004 << Arg->getSourceRange());
Chandler Carruth16e6bc22018-06-21 23:46:09 +00006005 }
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00006006
6007 return false;
6008}
6009
Simon Dardis1f90f2d2016-10-19 17:50:52 +00006010/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6011/// TheCall is a constant expression is a multiple of Num..
6012bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6013 unsigned Num) {
6014 llvm::APSInt Result;
6015
6016 // We can't check the value of a dependent argument.
6017 Expr *Arg = TheCall->getArg(ArgNum);
6018 if (Arg->isTypeDependent() || Arg->isValueDependent())
6019 return false;
6020
6021 // Check constant-ness first.
6022 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6023 return true;
6024
6025 if (Result.getSExtValue() % Num != 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006026 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6027 << Num << Arg->getSourceRange();
Simon Dardis1f90f2d2016-10-19 17:50:52 +00006028
6029 return false;
6030}
6031
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006032/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6033/// TheCall is an ARM/AArch64 special register string literal.
6034bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6035 int ArgNum, unsigned ExpectedFieldNum,
6036 bool AllowName) {
6037 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6038 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6039 BuiltinID == ARM::BI__builtin_arm_rsr ||
6040 BuiltinID == ARM::BI__builtin_arm_rsrp ||
6041 BuiltinID == ARM::BI__builtin_arm_wsr ||
6042 BuiltinID == ARM::BI__builtin_arm_wsrp;
6043 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6044 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6045 BuiltinID == AArch64::BI__builtin_arm_rsr ||
6046 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6047 BuiltinID == AArch64::BI__builtin_arm_wsr ||
6048 BuiltinID == AArch64::BI__builtin_arm_wsrp;
6049 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6050
6051 // We can't check the value of a dependent argument.
6052 Expr *Arg = TheCall->getArg(ArgNum);
6053 if (Arg->isTypeDependent() || Arg->isValueDependent())
6054 return false;
6055
6056 // Check if the argument is a string literal.
6057 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006058 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006059 << Arg->getSourceRange();
6060
6061 // Check the type of special register given.
6062 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6063 SmallVector<StringRef, 6> Fields;
6064 Reg.split(Fields, ":");
6065
6066 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006067 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006068 << Arg->getSourceRange();
6069
6070 // If the string is the name of a register then we cannot check that it is
6071 // valid here but if the string is of one the forms described in ACLE then we
6072 // can check that the supplied fields are integers and within the valid
6073 // ranges.
6074 if (Fields.size() > 1) {
6075 bool FiveFields = Fields.size() == 5;
6076
6077 bool ValidString = true;
6078 if (IsARMBuiltin) {
6079 ValidString &= Fields[0].startswith_lower("cp") ||
6080 Fields[0].startswith_lower("p");
6081 if (ValidString)
6082 Fields[0] =
6083 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6084
6085 ValidString &= Fields[2].startswith_lower("c");
6086 if (ValidString)
6087 Fields[2] = Fields[2].drop_front(1);
6088
6089 if (FiveFields) {
6090 ValidString &= Fields[3].startswith_lower("c");
6091 if (ValidString)
6092 Fields[3] = Fields[3].drop_front(1);
6093 }
6094 }
6095
6096 SmallVector<int, 5> Ranges;
6097 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00006098 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006099 else
6100 Ranges.append({15, 7, 15});
6101
6102 for (unsigned i=0; i<Fields.size(); ++i) {
6103 int IntField;
6104 ValidString &= !Fields[i].getAsInteger(10, IntField);
6105 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6106 }
6107
6108 if (!ValidString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006109 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006110 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006111 } else if (IsAArch64Builtin && Fields.size() == 1) {
6112 // If the register name is one of those that appear in the condition below
6113 // and the special register builtin being used is one of the write builtins,
6114 // then we require that the argument provided for writing to the register
6115 // is an integer constant expression. This is because it will be lowered to
6116 // an MSR (immediate) instruction, so we need to know the immediate at
6117 // compile time.
6118 if (TheCall->getNumArgs() != 2)
6119 return false;
6120
6121 std::string RegLower = Reg.lower();
6122 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6123 RegLower != "pan" && RegLower != "uao")
6124 return false;
6125
6126 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6127 }
6128
6129 return false;
6130}
6131
Eli Friedmanc97d0142009-05-03 06:04:26 +00006132/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006133/// This checks that the target supports __builtin_longjmp and
6134/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006135bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006136 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006137 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006138 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006139
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006140 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00006141 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00006142
Eric Christopher8d0c6212010-04-17 02:26:23 +00006143 // TODO: This is less than ideal. Overload this to take a value.
6144 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6145 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006146
Eric Christopher8d0c6212010-04-17 02:26:23 +00006147 if (Result != 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006148 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006149 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006150
6151 return false;
6152}
6153
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006154/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6155/// This checks that the target supports __builtin_setjmp.
6156bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6157 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006158 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006159 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006160 return false;
6161}
6162
Richard Smithd7293d72013-08-05 18:49:43 +00006163namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006164
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006165class UncoveredArgHandler {
6166 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006167
6168 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006169 SmallVector<const Expr *, 4> DiagnosticExprs;
6170
6171public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006172 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006173
6174 bool hasUncoveredArg() const {
6175 return (FirstUncoveredArg >= 0);
6176 }
6177
6178 unsigned getUncoveredArg() const {
6179 assert(hasUncoveredArg() && "no uncovered argument");
6180 return FirstUncoveredArg;
6181 }
6182
6183 void setAllCovered() {
6184 // A string has been found with all arguments covered, so clear out
6185 // the diagnostics.
6186 DiagnosticExprs.clear();
6187 FirstUncoveredArg = AllCovered;
6188 }
6189
6190 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6191 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6192
6193 // Don't update if a previous string covers all arguments.
6194 if (FirstUncoveredArg == AllCovered)
6195 return;
6196
6197 // UncoveredArgHandler tracks the highest uncovered argument index
6198 // and with it all the strings that match this index.
6199 if (NewFirstUncoveredArg == FirstUncoveredArg)
6200 DiagnosticExprs.push_back(StrExpr);
6201 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6202 DiagnosticExprs.clear();
6203 DiagnosticExprs.push_back(StrExpr);
6204 FirstUncoveredArg = NewFirstUncoveredArg;
6205 }
6206 }
6207
6208 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6209};
6210
Richard Smithd7293d72013-08-05 18:49:43 +00006211enum StringLiteralCheckType {
6212 SLCT_NotALiteral,
6213 SLCT_UncheckedLiteral,
6214 SLCT_CheckedLiteral
6215};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006216
6217} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00006218
Stephen Hines648c3692016-09-16 01:07:04 +00006219static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6220 BinaryOperatorKind BinOpKind,
6221 bool AddendIsRight) {
6222 unsigned BitWidth = Offset.getBitWidth();
6223 unsigned AddendBitWidth = Addend.getBitWidth();
6224 // There might be negative interim results.
6225 if (Addend.isUnsigned()) {
6226 Addend = Addend.zext(++AddendBitWidth);
6227 Addend.setIsSigned(true);
6228 }
6229 // Adjust the bit width of the APSInts.
6230 if (AddendBitWidth > BitWidth) {
6231 Offset = Offset.sext(AddendBitWidth);
6232 BitWidth = AddendBitWidth;
6233 } else if (BitWidth > AddendBitWidth) {
6234 Addend = Addend.sext(BitWidth);
6235 }
6236
6237 bool Ov = false;
6238 llvm::APSInt ResOffset = Offset;
6239 if (BinOpKind == BO_Add)
6240 ResOffset = Offset.sadd_ov(Addend, Ov);
6241 else {
6242 assert(AddendIsRight && BinOpKind == BO_Sub &&
6243 "operator must be add or sub with addend on the right");
6244 ResOffset = Offset.ssub_ov(Addend, Ov);
6245 }
6246
6247 // We add an offset to a pointer here so we should support an offset as big as
6248 // possible.
6249 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006250 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6251 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00006252 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00006253 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6254 return;
6255 }
6256
6257 Offset = ResOffset;
6258}
6259
6260namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006261
Stephen Hines648c3692016-09-16 01:07:04 +00006262// This is a wrapper class around StringLiteral to support offsetted string
6263// literals as format strings. It takes the offset into account when returning
6264// the string and its length or the source locations to display notes correctly.
6265class FormatStringLiteral {
6266 const StringLiteral *FExpr;
6267 int64_t Offset;
6268
6269 public:
6270 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6271 : FExpr(fexpr), Offset(Offset) {}
6272
6273 StringRef getString() const {
6274 return FExpr->getString().drop_front(Offset);
6275 }
6276
6277 unsigned getByteLength() const {
6278 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6279 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006280
Stephen Hines648c3692016-09-16 01:07:04 +00006281 unsigned getLength() const { return FExpr->getLength() - Offset; }
6282 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6283
6284 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6285
6286 QualType getType() const { return FExpr->getType(); }
6287
6288 bool isAscii() const { return FExpr->isAscii(); }
6289 bool isWide() const { return FExpr->isWide(); }
6290 bool isUTF8() const { return FExpr->isUTF8(); }
6291 bool isUTF16() const { return FExpr->isUTF16(); }
6292 bool isUTF32() const { return FExpr->isUTF32(); }
6293 bool isPascal() const { return FExpr->isPascal(); }
6294
6295 SourceLocation getLocationOfByte(
6296 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6297 const TargetInfo &Target, unsigned *StartToken = nullptr,
6298 unsigned *StartTokenByteOffset = nullptr) const {
6299 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6300 StartToken, StartTokenByteOffset);
6301 }
6302
Stephen Kelly724e9e52018-08-09 20:05:03 +00006303 SourceLocation getBeginLoc() const LLVM_READONLY {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006304 return FExpr->getBeginLoc().getLocWithOffset(Offset);
Stephen Hines648c3692016-09-16 01:07:04 +00006305 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006306
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006307 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
Stephen Hines648c3692016-09-16 01:07:04 +00006308};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006309
6310} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00006311
6312static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006313 const Expr *OrigFormatExpr,
6314 ArrayRef<const Expr *> Args,
6315 bool HasVAListArg, unsigned format_idx,
6316 unsigned firstDataArg,
6317 Sema::FormatStringType Type,
6318 bool inFunctionCall,
6319 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006320 llvm::SmallBitVector &CheckedVarArgs,
6321 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006322
Richard Smith55ce3522012-06-25 20:30:08 +00006323// Determine if an expression is a string literal or constant string.
6324// If this function returns false on the arguments to a function expecting a
6325// format string, we will usually need to emit a warning.
6326// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00006327static StringLiteralCheckType
6328checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6329 bool HasVAListArg, unsigned format_idx,
6330 unsigned firstDataArg, Sema::FormatStringType Type,
6331 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006332 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006333 UncoveredArgHandler &UncoveredArg,
6334 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00006335 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00006336 assert(Offset.isSigned() && "invalid offset");
6337
Douglas Gregorc25f7662009-05-19 22:10:17 +00006338 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00006339 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006340
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006341 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00006342
Richard Smithd7293d72013-08-05 18:49:43 +00006343 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00006344 // Technically -Wformat-nonliteral does not warn about this case.
6345 // The behavior of printf and friends in this case is implementation
6346 // dependent. Ideally if the format string cannot be null then
6347 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00006348 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00006349
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006350 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00006351 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006352 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00006353 // The expression is a literal if both sub-expressions were, and it was
6354 // completely checked only if both sub-expressions were checked.
6355 const AbstractConditionalOperator *C =
6356 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006357
6358 // Determine whether it is necessary to check both sub-expressions, for
6359 // example, because the condition expression is a constant that can be
6360 // evaluated at compile time.
6361 bool CheckLeft = true, CheckRight = true;
6362
6363 bool Cond;
6364 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6365 if (Cond)
6366 CheckRight = false;
6367 else
6368 CheckLeft = false;
6369 }
6370
Stephen Hines648c3692016-09-16 01:07:04 +00006371 // We need to maintain the offsets for the right and the left hand side
6372 // separately to check if every possible indexed expression is a valid
6373 // string literal. They might have different offsets for different string
6374 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006375 StringLiteralCheckType Left;
6376 if (!CheckLeft)
6377 Left = SLCT_UncheckedLiteral;
6378 else {
6379 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6380 HasVAListArg, format_idx, firstDataArg,
6381 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00006382 CheckedVarArgs, UncoveredArg, Offset);
6383 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006384 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00006385 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006386 }
6387
Richard Smith55ce3522012-06-25 20:30:08 +00006388 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00006389 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006390 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006391 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006392 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006393
6394 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006395 }
6396
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006397 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00006398 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6399 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006400
John McCallc07a0c72011-02-17 10:25:35 +00006401 case Stmt::OpaqueValueExprClass:
6402 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6403 E = src;
6404 goto tryAgain;
6405 }
Richard Smith55ce3522012-06-25 20:30:08 +00006406 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00006407
Ted Kremeneka8890832011-02-24 23:03:04 +00006408 case Stmt::PredefinedExprClass:
6409 // While __func__, etc., are technically not string literals, they
6410 // cannot contain format specifiers and thus are not a security
6411 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00006412 return SLCT_UncheckedLiteral;
Fangrui Song6907ce22018-07-30 19:24:48 +00006413
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006414 case Stmt::DeclRefExprClass: {
6415 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006416
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006417 // As an exception, do not flag errors for variables binding to
6418 // const string literals.
6419 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6420 bool isConstant = false;
6421 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006422
Richard Smithd7293d72013-08-05 18:49:43 +00006423 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6424 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00006425 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00006426 isConstant = T.isConstant(S.Context) &&
6427 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00006428 } else if (T->isObjCObjectPointerType()) {
6429 // In ObjC, there is usually no "const ObjectPointer" type,
6430 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00006431 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006432 }
Mike Stump11289f42009-09-09 15:08:12 +00006433
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006434 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006435 if (const Expr *Init = VD->getAnyInitializer()) {
6436 // Look through initializers like const char c[] = { "foo" }
6437 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6438 if (InitList->isStringLiteralInit())
6439 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6440 }
Richard Smithd7293d72013-08-05 18:49:43 +00006441 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006442 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006443 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006444 /*InFunctionCall*/ false, CheckedVarArgs,
6445 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006446 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006447 }
Mike Stump11289f42009-09-09 15:08:12 +00006448
Anders Carlssonb012ca92009-06-28 19:55:58 +00006449 // For vprintf* functions (i.e., HasVAListArg==true), we add a
6450 // special check to see if the format string is a function parameter
6451 // of the function calling the printf function. If the function
6452 // has an attribute indicating it is a printf-like function, then we
6453 // should suppress warnings concerning non-literals being used in a call
6454 // to a vprintf function. For example:
6455 //
6456 // void
6457 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6458 // va_list ap;
6459 // va_start(ap, fmt);
6460 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
6461 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00006462 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006463 if (HasVAListArg) {
6464 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6465 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6466 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00006467 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006468 // adjust for implicit parameter
6469 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6470 if (MD->isInstance())
6471 ++PVIndex;
6472 // We also check if the formats are compatible.
6473 // We can't pass a 'scanf' string to a 'printf' function.
6474 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00006475 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00006476 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006477 }
6478 }
6479 }
6480 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006481 }
Mike Stump11289f42009-09-09 15:08:12 +00006482
Richard Smith55ce3522012-06-25 20:30:08 +00006483 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006484 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006485
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006486 case Stmt::CallExprClass:
6487 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006488 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006489 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
Michael Krusef18adbb2018-07-04 01:37:11 +00006490 bool IsFirst = true;
6491 StringLiteralCheckType CommonResult;
6492 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00006493 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Michael Krusef18adbb2018-07-04 01:37:11 +00006494 StringLiteralCheckType Result = checkFormatStringExpr(
6495 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6496 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6497 if (IsFirst) {
6498 CommonResult = Result;
6499 IsFirst = false;
6500 }
6501 }
6502 if (!IsFirst)
6503 return CommonResult;
6504
6505 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006506 unsigned BuiltinID = FD->getBuiltinID();
6507 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6508 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6509 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00006510 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006511 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006512 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006513 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006514 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006515 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006516 }
6517 }
Mike Stump11289f42009-09-09 15:08:12 +00006518
Richard Smith55ce3522012-06-25 20:30:08 +00006519 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006520 }
Alex Lorenzd9007142016-10-24 09:42:34 +00006521 case Stmt::ObjCMessageExprClass: {
6522 const auto *ME = cast<ObjCMessageExpr>(E);
6523 if (const auto *ND = ME->getMethodDecl()) {
6524 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00006525 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00006526 return checkFormatStringExpr(
6527 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6528 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6529 }
6530 }
6531
6532 return SLCT_NotALiteral;
6533 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006534 case Stmt::ObjCStringLiteralClass:
6535 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00006536 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006537
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006538 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006539 StrE = ObjCFExpr->getString();
6540 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006541 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006542
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006543 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00006544 if (Offset.isNegative() || Offset > StrE->getLength()) {
6545 // TODO: It would be better to have an explicit warning for out of
6546 // bounds literals.
6547 return SLCT_NotALiteral;
6548 }
6549 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6550 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006551 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006552 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00006553 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006554 }
Mike Stump11289f42009-09-09 15:08:12 +00006555
Richard Smith55ce3522012-06-25 20:30:08 +00006556 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006557 }
Stephen Hines648c3692016-09-16 01:07:04 +00006558 case Stmt::BinaryOperatorClass: {
Stephen Hines648c3692016-09-16 01:07:04 +00006559 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6560
6561 // A string literal + an int offset is still a string literal.
6562 if (BinOp->isAdditiveOp()) {
Fangrui Song407659a2018-11-30 23:41:18 +00006563 Expr::EvalResult LResult, RResult;
6564
Stephen Hines648c3692016-09-16 01:07:04 +00006565 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6566 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6567
6568 if (LIsInt != RIsInt) {
6569 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6570
6571 if (LIsInt) {
6572 if (BinOpKind == BO_Add) {
Fangrui Song407659a2018-11-30 23:41:18 +00006573 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
Stephen Hines648c3692016-09-16 01:07:04 +00006574 E = BinOp->getRHS();
6575 goto tryAgain;
6576 }
6577 } else {
Fangrui Song407659a2018-11-30 23:41:18 +00006578 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
Stephen Hines648c3692016-09-16 01:07:04 +00006579 E = BinOp->getLHS();
6580 goto tryAgain;
6581 }
6582 }
Stephen Hines648c3692016-09-16 01:07:04 +00006583 }
George Burgess IVd273aab2016-09-22 00:00:26 +00006584
6585 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00006586 }
6587 case Stmt::UnaryOperatorClass: {
6588 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6589 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006590 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Fangrui Song407659a2018-11-30 23:41:18 +00006591 Expr::EvalResult IndexResult;
Stephen Hines648c3692016-09-16 01:07:04 +00006592 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
Fangrui Song407659a2018-11-30 23:41:18 +00006593 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6594 /*RHS is int*/ true);
Stephen Hines648c3692016-09-16 01:07:04 +00006595 E = ASE->getBase();
6596 goto tryAgain;
6597 }
6598 }
6599
6600 return SLCT_NotALiteral;
6601 }
Mike Stump11289f42009-09-09 15:08:12 +00006602
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006603 default:
Richard Smith55ce3522012-06-25 20:30:08 +00006604 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006605 }
6606}
6607
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006608Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00006609 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00006610 .Case("scanf", FST_Scanf)
6611 .Cases("printf", "printf0", FST_Printf)
6612 .Cases("NSString", "CFString", FST_NSString)
6613 .Case("strftime", FST_Strftime)
6614 .Case("strfmon", FST_Strfmon)
6615 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6616 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6617 .Case("os_trace", FST_OSLog)
6618 .Case("os_log", FST_OSLog)
6619 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006620}
6621
Jordan Rose3e0ec582012-07-19 18:10:23 +00006622/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00006623/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00006624/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006625bool Sema::CheckFormatArguments(const FormatAttr *Format,
6626 ArrayRef<const Expr *> Args,
6627 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006628 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00006629 SourceLocation Loc, SourceRange Range,
6630 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00006631 FormatStringInfo FSI;
6632 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006633 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00006634 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00006635 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00006636 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006637}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00006638
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006639bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006640 bool HasVAListArg, unsigned format_idx,
6641 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006642 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00006643 SourceLocation Loc, SourceRange Range,
6644 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00006645 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006646 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006647 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00006648 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006649 }
Mike Stump11289f42009-09-09 15:08:12 +00006650
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006651 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006652
Chris Lattnerb87b1b32007-08-10 20:18:51 +00006653 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00006654 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006655 // Dynamically generated format strings are difficult to
6656 // automatically vet at compile time. Requiring that format strings
6657 // are string literals: (1) permits the checking of format strings by
6658 // the compiler and thereby (2) can practically remove the source of
6659 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00006660
Mike Stump11289f42009-09-09 15:08:12 +00006661 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00006662 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00006663 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00006664 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006665 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00006666 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00006667 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6668 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006669 /*IsFunctionCall*/ true, CheckedVarArgs,
6670 UncoveredArg,
6671 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006672
6673 // Generate a diagnostic where an uncovered argument is detected.
6674 if (UncoveredArg.hasUncoveredArg()) {
6675 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6676 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6677 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6678 }
6679
Richard Smith55ce3522012-06-25 20:30:08 +00006680 if (CT != SLCT_NotALiteral)
6681 // Literal format string found, check done!
6682 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00006683
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00006684 // Strftime is particular as it always uses a single 'time' argument,
6685 // so it is safe to pass a non-literal string.
6686 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00006687 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00006688
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00006689 // Do not emit diag when the string param is a macro expansion and the
6690 // format is either NSString or CFString. This is a hack to prevent
6691 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6692 // which are usually used in place of NS and CF string literals.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006693 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006694 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00006695 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00006696
Chris Lattnercc5d1c22009-04-29 04:59:47 +00006697 // If there are no arguments specified, warn with -Wformat-security, otherwise
6698 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006699 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00006700 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6701 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006702 switch (Type) {
6703 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006704 break;
6705 case FST_Kprintf:
6706 case FST_FreeBSDKPrintf:
6707 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00006708 Diag(FormatLoc, diag::note_format_security_fixit)
6709 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006710 break;
6711 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00006712 Diag(FormatLoc, diag::note_format_security_fixit)
6713 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006714 break;
6715 }
6716 } else {
6717 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00006718 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006719 }
Richard Smith55ce3522012-06-25 20:30:08 +00006720 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006721}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006722
Ted Kremenekab278de2010-01-28 23:39:18 +00006723namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006724
Ted Kremenek02087932010-07-16 02:11:22 +00006725class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6726protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00006727 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00006728 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00006729 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006730 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00006731 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00006732 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00006733 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00006734 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006735 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00006736 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00006737 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006738 bool usesPositionalArgs = false;
6739 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006740 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00006741 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00006742 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006743 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006744
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006745public:
Stephen Hines648c3692016-09-16 01:07:04 +00006746 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006747 const Expr *origFormatExpr,
6748 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006749 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006750 ArrayRef<const Expr *> Args, unsigned formatIdx,
6751 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006752 llvm::SmallBitVector &CheckedVarArgs,
6753 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006754 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6755 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6756 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00006757 inFunctionCall(inFunctionCall), CallType(callType),
6758 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00006759 CoveredArgs.resize(numDataArgs);
6760 CoveredArgs.reset();
6761 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006762
Ted Kremenek019d2242010-01-29 01:50:07 +00006763 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006764
Ted Kremenek02087932010-07-16 02:11:22 +00006765 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006766 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006767
Jordan Rose92303592012-09-08 04:00:03 +00006768 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00006769 const analyze_format_string::FormatSpecifier &FS,
6770 const analyze_format_string::ConversionSpecifier &CS,
6771 const char *startSpecifier, unsigned specifierLen,
6772 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00006773
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006774 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00006775 const analyze_format_string::FormatSpecifier &FS,
6776 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006777
6778 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00006779 const analyze_format_string::ConversionSpecifier &CS,
6780 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006781
Craig Toppere14c0f82014-03-12 04:55:44 +00006782 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00006783
Craig Toppere14c0f82014-03-12 04:55:44 +00006784 void HandleInvalidPosition(const char *startSpecifier,
6785 unsigned specifierLen,
6786 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00006787
Craig Toppere14c0f82014-03-12 04:55:44 +00006788 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00006789
Craig Toppere14c0f82014-03-12 04:55:44 +00006790 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006791
Richard Trieu03cf7b72011-10-28 00:41:25 +00006792 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00006793 static void
6794 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6795 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6796 bool IsStringLocation, Range StringRange,
6797 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00006798
Ted Kremenek02087932010-07-16 02:11:22 +00006799protected:
Ted Kremenekce815422010-07-19 21:25:57 +00006800 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6801 const char *startSpec,
6802 unsigned specifierLen,
6803 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00006804
6805 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6806 const char *startSpec,
6807 unsigned specifierLen);
Fangrui Song6907ce22018-07-30 19:24:48 +00006808
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006809 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00006810 CharSourceRange getSpecifierRange(const char *startSpecifier,
6811 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00006812 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006813
Ted Kremenek5739de72010-01-29 01:06:55 +00006814 const Expr *getDataArg(unsigned i) const;
Fangrui Song6907ce22018-07-30 19:24:48 +00006815
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006816 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6817 const analyze_format_string::ConversionSpecifier &CS,
6818 const char *startSpecifier, unsigned specifierLen,
6819 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00006820
6821 template <typename Range>
6822 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6823 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006824 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00006825};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006826
6827} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006828
Ted Kremenek02087932010-07-16 02:11:22 +00006829SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00006830 return OrigFormatExpr->getSourceRange();
6831}
6832
Ted Kremenek02087932010-07-16 02:11:22 +00006833CharSourceRange CheckFormatHandler::
6834getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00006835 SourceLocation Start = getLocationOfByte(startSpecifier);
6836 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
6837
6838 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00006839 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00006840
6841 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006842}
6843
Ted Kremenek02087932010-07-16 02:11:22 +00006844SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00006845 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6846 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00006847}
6848
Ted Kremenek02087932010-07-16 02:11:22 +00006849void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6850 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00006851 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6852 getLocationOfByte(startSpecifier),
6853 /*IsStringLocation*/true,
6854 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00006855}
6856
Jordan Rose92303592012-09-08 04:00:03 +00006857void CheckFormatHandler::HandleInvalidLengthModifier(
6858 const analyze_format_string::FormatSpecifier &FS,
6859 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00006860 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00006861 using namespace analyze_format_string;
6862
6863 const LengthModifier &LM = FS.getLengthModifier();
6864 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6865
6866 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00006867 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00006868 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00006869 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00006870 getLocationOfByte(LM.getStart()),
6871 /*IsStringLocation*/true,
6872 getSpecifierRange(startSpecifier, specifierLen));
6873
6874 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6875 << FixedLM->toString()
6876 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6877
6878 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00006879 FixItHint Hint;
6880 if (DiagID == diag::warn_format_nonsensical_length)
6881 Hint = FixItHint::CreateRemoval(LMRange);
6882
6883 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00006884 getLocationOfByte(LM.getStart()),
6885 /*IsStringLocation*/true,
6886 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00006887 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00006888 }
6889}
6890
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006891void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00006892 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006893 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00006894 using namespace analyze_format_string;
6895
6896 const LengthModifier &LM = FS.getLengthModifier();
6897 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6898
6899 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00006900 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00006901 if (FixedLM) {
6902 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6903 << LM.toString() << 0,
6904 getLocationOfByte(LM.getStart()),
6905 /*IsStringLocation*/true,
6906 getSpecifierRange(startSpecifier, specifierLen));
6907
6908 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6909 << FixedLM->toString()
6910 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6911
6912 } else {
6913 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6914 << LM.toString() << 0,
6915 getLocationOfByte(LM.getStart()),
6916 /*IsStringLocation*/true,
6917 getSpecifierRange(startSpecifier, specifierLen));
6918 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006919}
6920
6921void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6922 const analyze_format_string::ConversionSpecifier &CS,
6923 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00006924 using namespace analyze_format_string;
6925
6926 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00006927 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00006928 if (FixedCS) {
6929 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6930 << CS.toString() << /*conversion specifier*/1,
6931 getLocationOfByte(CS.getStart()),
6932 /*IsStringLocation*/true,
6933 getSpecifierRange(startSpecifier, specifierLen));
6934
6935 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6936 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6937 << FixedCS->toString()
6938 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6939 } else {
6940 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6941 << CS.toString() << /*conversion specifier*/1,
6942 getLocationOfByte(CS.getStart()),
6943 /*IsStringLocation*/true,
6944 getSpecifierRange(startSpecifier, specifierLen));
6945 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006946}
6947
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00006948void CheckFormatHandler::HandlePosition(const char *startPos,
6949 unsigned posLen) {
6950 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6951 getLocationOfByte(startPos),
6952 /*IsStringLocation*/true,
6953 getSpecifierRange(startPos, posLen));
6954}
6955
Ted Kremenekd1668192010-02-27 01:41:03 +00006956void
Ted Kremenek02087932010-07-16 02:11:22 +00006957CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
6958 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006959 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
6960 << (unsigned) p,
6961 getLocationOfByte(startPos), /*IsStringLocation*/true,
6962 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00006963}
6964
Ted Kremenek02087932010-07-16 02:11:22 +00006965void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00006966 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6968 getLocationOfByte(startPos),
6969 /*IsStringLocation*/true,
6970 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00006971}
6972
Ted Kremenek02087932010-07-16 02:11:22 +00006973void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006974 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00006975 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006976 EmitFormatDiagnostic(
6977 S.PDiag(diag::warn_printf_format_string_contains_null_char),
6978 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6979 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00006980 }
Ted Kremenek02087932010-07-16 02:11:22 +00006981}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006982
Jordan Rose58bbe422012-07-19 18:10:08 +00006983// Note that this may return NULL if there was an error parsing or building
6984// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00006985const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006986 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00006987}
6988
6989void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006990 // Does the number of data arguments exceed the number of
6991 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00006992 if (!HasVAListArg) {
6993 // Find any arguments that weren't covered.
6994 CoveredArgs.flip();
6995 signed notCoveredArg = CoveredArgs.find_first();
6996 if (notCoveredArg >= 0) {
6997 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006998 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6999 } else {
7000 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00007001 }
7002 }
7003}
7004
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007005void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7006 const Expr *ArgExpr) {
7007 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7008 "Invalid state");
7009
7010 if (!ArgExpr)
7011 return;
7012
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007013 SourceLocation Loc = ArgExpr->getBeginLoc();
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007014
7015 if (S.getSourceManager().isInSystemMacro(Loc))
7016 return;
7017
7018 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7019 for (auto E : DiagnosticExprs)
7020 PDiag << E->getSourceRange();
7021
7022 CheckFormatHandler::EmitFormatDiagnostic(
7023 S, IsFunctionCall, DiagnosticExprs[0],
7024 PDiag, Loc, /*IsStringLocation*/false,
7025 DiagnosticExprs[0]->getSourceRange());
7026}
7027
Ted Kremenekce815422010-07-19 21:25:57 +00007028bool
7029CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7030 SourceLocation Loc,
7031 const char *startSpec,
7032 unsigned specifierLen,
7033 const char *csStart,
7034 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00007035 bool keepGoing = true;
7036 if (argIndex < NumDataArgs) {
7037 // Consider the argument coverered, even though the specifier doesn't
7038 // make sense.
7039 CoveredArgs.set(argIndex);
7040 }
7041 else {
7042 // If argIndex exceeds the number of data arguments we
7043 // don't issue a warning because that is just a cascade of warnings (and
7044 // they may have intended '%%' anyway). We don't want to continue processing
7045 // the format string after this point, however, as we will like just get
7046 // gibberish when trying to match arguments.
7047 keepGoing = false;
7048 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007049
7050 StringRef Specifier(csStart, csLen);
7051
7052 // If the specifier in non-printable, it could be the first byte of a UTF-8
7053 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7054 // hex value.
7055 std::string CodePointStr;
7056 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00007057 llvm::UTF32 CodePoint;
7058 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7059 const llvm::UTF8 *E =
7060 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7061 llvm::ConversionResult Result =
7062 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007063
Justin Lebar90910552016-09-30 00:38:45 +00007064 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007065 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00007066 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00007067 }
7068
7069 llvm::raw_string_ostream OS(CodePointStr);
7070 if (CodePoint < 256)
7071 OS << "\\x" << llvm::format("%02x", CodePoint);
7072 else if (CodePoint <= 0xFFFF)
7073 OS << "\\u" << llvm::format("%04x", CodePoint);
7074 else
7075 OS << "\\U" << llvm::format("%08x", CodePoint);
7076 OS.flush();
7077 Specifier = CodePointStr;
7078 }
7079
7080 EmitFormatDiagnostic(
7081 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7082 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7083
Ted Kremenekce815422010-07-19 21:25:57 +00007084 return keepGoing;
7085}
7086
Richard Trieu03cf7b72011-10-28 00:41:25 +00007087void
7088CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7089 const char *startSpec,
7090 unsigned specifierLen) {
7091 EmitFormatDiagnostic(
7092 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7093 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7094}
7095
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007096bool
7097CheckFormatHandler::CheckNumArgs(
7098 const analyze_format_string::FormatSpecifier &FS,
7099 const analyze_format_string::ConversionSpecifier &CS,
7100 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7101
7102 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007103 PartialDiagnostic PDiag = FS.usesPositionalArg()
7104 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7105 << (argIndex+1) << NumDataArgs)
7106 : S.PDiag(diag::warn_printf_insufficient_data_args);
7107 EmitFormatDiagnostic(
7108 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7109 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007110
7111 // Since more arguments than conversion tokens are given, by extension
7112 // all arguments are covered, so mark this as so.
7113 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007114 return false;
7115 }
7116 return true;
7117}
7118
Richard Trieu03cf7b72011-10-28 00:41:25 +00007119template<typename Range>
7120void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7121 SourceLocation Loc,
7122 bool IsStringLocation,
7123 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00007124 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007125 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00007126 Loc, IsStringLocation, StringRange, FixIt);
7127}
7128
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007129/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00007130/// so that the function call and string are in diagnostic messages.
7131///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007132/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00007133/// call and only one diagnostic message will be produced. Otherwise, an
7134/// extra note will be emitted pointing to location of the format string.
7135///
7136/// \param ArgumentExpr the expression that is passed as the format string
7137/// argument in the function call. Used for getting locations when two
7138/// diagnostics are emitted.
7139///
7140/// \param PDiag the callee should already have provided any strings for the
7141/// diagnostic message. This function only adds locations and fixits
7142/// to diagnostics.
7143///
7144/// \param Loc primary location for diagnostic. If two diagnostics are
7145/// required, one will be at Loc and a new SourceLocation will be created for
7146/// the other one.
7147///
7148/// \param IsStringLocation if true, Loc points to the format string should be
7149/// used for the note. Otherwise, Loc points to the argument list and will
7150/// be used with PDiag.
7151///
7152/// \param StringRange some or all of the string to highlight. This is
7153/// templated so it can accept either a CharSourceRange or a SourceRange.
7154///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007155/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00007156template <typename Range>
7157void CheckFormatHandler::EmitFormatDiagnostic(
7158 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7159 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7160 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00007161 if (InFunctionCall) {
7162 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7163 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007164 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00007165 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007166 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7167 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00007168
7169 const Sema::SemaDiagnosticBuilder &Note =
7170 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7171 diag::note_format_string_defined);
7172
7173 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007174 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00007175 }
7176}
7177
Ted Kremenek02087932010-07-16 02:11:22 +00007178//===--- CHECK: Printf format string checking ------------------------------===//
7179
7180namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007181
Ted Kremenek02087932010-07-16 02:11:22 +00007182class CheckPrintfHandler : public CheckFormatHandler {
7183public:
Stephen Hines648c3692016-09-16 01:07:04 +00007184 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007185 const Expr *origFormatExpr,
7186 const Sema::FormatStringType type, unsigned firstDataArg,
7187 unsigned numDataArgs, bool isObjC, const char *beg,
7188 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00007189 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00007190 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007191 llvm::SmallBitVector &CheckedVarArgs,
7192 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007193 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7194 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7195 inFunctionCall, CallType, CheckedVarArgs,
7196 UncoveredArg) {}
7197
7198 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7199
7200 /// Returns true if '%@' specifiers are allowed in the format string.
7201 bool allowsObjCArg() const {
7202 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7203 FSType == Sema::FST_OSTrace;
7204 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00007205
Ted Kremenek02087932010-07-16 02:11:22 +00007206 bool HandleInvalidPrintfConversionSpecifier(
7207 const analyze_printf::PrintfSpecifier &FS,
7208 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007209 unsigned specifierLen) override;
7210
Akira Hatanakad572cf42018-11-06 07:05:14 +00007211 void handleInvalidMaskType(StringRef MaskType) override;
7212
Ted Kremenek02087932010-07-16 02:11:22 +00007213 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7214 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007215 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007216 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7217 const char *StartSpecifier,
7218 unsigned SpecifierLen,
7219 const Expr *E);
7220
Ted Kremenek02087932010-07-16 02:11:22 +00007221 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7222 const char *startSpecifier, unsigned specifierLen);
7223 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7224 const analyze_printf::OptionalAmount &Amt,
7225 unsigned type,
7226 const char *startSpecifier, unsigned specifierLen);
7227 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7228 const analyze_printf::OptionalFlag &flag,
7229 const char *startSpecifier, unsigned specifierLen);
7230 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7231 const analyze_printf::OptionalFlag &ignoredFlag,
7232 const analyze_printf::OptionalFlag &flag,
7233 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007234 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00007235 const Expr *E);
Fangrui Song6907ce22018-07-30 19:24:48 +00007236
Ted Kremenek2b417712015-07-02 05:39:16 +00007237 void HandleEmptyObjCModifierFlag(const char *startFlag,
7238 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007239
Ted Kremenek2b417712015-07-02 05:39:16 +00007240 void HandleInvalidObjCModifierFlag(const char *startFlag,
7241 unsigned flagLen) override;
7242
7243 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7244 const char *flagsEnd,
Fangrui Song6907ce22018-07-30 19:24:48 +00007245 const char *conversionPosition)
Ted Kremenek2b417712015-07-02 05:39:16 +00007246 override;
7247};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007248
7249} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00007250
7251bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7252 const analyze_printf::PrintfSpecifier &FS,
7253 const char *startSpecifier,
7254 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007255 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007256 FS.getConversionSpecifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00007257
Ted Kremenekce815422010-07-19 21:25:57 +00007258 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7259 getLocationOfByte(CS.getStart()),
7260 startSpecifier, specifierLen,
7261 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00007262}
7263
Akira Hatanakad572cf42018-11-06 07:05:14 +00007264void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7265 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7266}
7267
Ted Kremenek02087932010-07-16 02:11:22 +00007268bool CheckPrintfHandler::HandleAmount(
7269 const analyze_format_string::OptionalAmount &Amt,
7270 unsigned k, const char *startSpecifier,
7271 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007272 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007273 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00007274 unsigned argIndex = Amt.getArgIndex();
7275 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007276 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7277 << k,
7278 getLocationOfByte(Amt.getStart()),
7279 /*IsStringLocation*/true,
7280 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007281 // Don't do any more checking. We will just emit
7282 // spurious errors.
7283 return false;
7284 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007285
Ted Kremenek5739de72010-01-29 01:06:55 +00007286 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00007287 // Although not in conformance with C99, we also allow the argument to be
7288 // an 'unsigned int' as that is a reasonably safe case. GCC also
7289 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00007290 CoveredArgs.set(argIndex);
7291 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007292 if (!Arg)
7293 return false;
7294
Ted Kremenek5739de72010-01-29 01:06:55 +00007295 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007296
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007297 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7298 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007299
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007300 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007301 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007302 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00007303 << T << Arg->getSourceRange(),
7304 getLocationOfByte(Amt.getStart()),
7305 /*IsStringLocation*/true,
7306 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007307 // Don't do any more checking. We will just emit
7308 // spurious errors.
7309 return false;
7310 }
7311 }
7312 }
7313 return true;
7314}
Ted Kremenek5739de72010-01-29 01:06:55 +00007315
Tom Careb49ec692010-06-17 19:00:27 +00007316void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00007317 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007318 const analyze_printf::OptionalAmount &Amt,
7319 unsigned type,
7320 const char *startSpecifier,
7321 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007322 const analyze_printf::PrintfConversionSpecifier &CS =
7323 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00007324
Richard Trieu03cf7b72011-10-28 00:41:25 +00007325 FixItHint fixit =
7326 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7327 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7328 Amt.getConstantLength()))
7329 : FixItHint();
7330
7331 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7332 << type << CS.toString(),
7333 getLocationOfByte(Amt.getStart()),
7334 /*IsStringLocation*/true,
7335 getSpecifierRange(startSpecifier, specifierLen),
7336 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00007337}
7338
Ted Kremenek02087932010-07-16 02:11:22 +00007339void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007340 const analyze_printf::OptionalFlag &flag,
7341 const char *startSpecifier,
7342 unsigned specifierLen) {
7343 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007344 const analyze_printf::PrintfConversionSpecifier &CS =
7345 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00007346 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7347 << flag.toString() << CS.toString(),
7348 getLocationOfByte(flag.getPosition()),
7349 /*IsStringLocation*/true,
7350 getSpecifierRange(startSpecifier, specifierLen),
7351 FixItHint::CreateRemoval(
7352 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007353}
7354
7355void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00007356 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007357 const analyze_printf::OptionalFlag &ignoredFlag,
7358 const analyze_printf::OptionalFlag &flag,
7359 const char *startSpecifier,
7360 unsigned specifierLen) {
7361 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00007362 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7363 << ignoredFlag.toString() << flag.toString(),
7364 getLocationOfByte(ignoredFlag.getPosition()),
7365 /*IsStringLocation*/true,
7366 getSpecifierRange(startSpecifier, specifierLen),
7367 FixItHint::CreateRemoval(
7368 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007369}
7370
Ted Kremenek2b417712015-07-02 05:39:16 +00007371void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7372 unsigned flagLen) {
7373 // Warn about an empty flag.
7374 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7375 getLocationOfByte(startFlag),
7376 /*IsStringLocation*/true,
7377 getSpecifierRange(startFlag, flagLen));
7378}
7379
7380void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7381 unsigned flagLen) {
7382 // Warn about an invalid flag.
7383 auto Range = getSpecifierRange(startFlag, flagLen);
7384 StringRef flag(startFlag, flagLen);
7385 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7386 getLocationOfByte(startFlag),
7387 /*IsStringLocation*/true,
7388 Range, FixItHint::CreateRemoval(Range));
7389}
7390
7391void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7392 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7393 // Warn about using '[...]' without a '@' conversion.
7394 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7395 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7396 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7397 getLocationOfByte(conversionPosition),
7398 /*IsStringLocation*/true,
7399 Range, FixItHint::CreateRemoval(Range));
7400}
7401
Richard Smith55ce3522012-06-25 20:30:08 +00007402// Determines if the specified is a C++ class or struct containing
7403// a member with the specified name and kind (e.g. a CXXMethodDecl named
7404// "c_str()").
7405template<typename MemberKind>
7406static llvm::SmallPtrSet<MemberKind*, 1>
7407CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7408 const RecordType *RT = Ty->getAs<RecordType>();
7409 llvm::SmallPtrSet<MemberKind*, 1> Results;
7410
7411 if (!RT)
7412 return Results;
7413 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00007414 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00007415 return Results;
7416
Alp Tokerb6cc5922014-05-03 03:45:55 +00007417 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00007418 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00007419 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00007420
7421 // We just need to include all members of the right kind turned up by the
7422 // filter, at this point.
7423 if (S.LookupQualifiedName(R, RT->getDecl()))
7424 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7425 NamedDecl *decl = (*I)->getUnderlyingDecl();
7426 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7427 Results.insert(FK);
7428 }
7429 return Results;
7430}
7431
Richard Smith2868a732014-02-28 01:36:39 +00007432/// Check if we could call '.c_str()' on an object.
7433///
7434/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7435/// allow the call, or if it would be ambiguous).
7436bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007437 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7438
Richard Smith2868a732014-02-28 01:36:39 +00007439 MethodSet Results =
7440 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7441 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7442 MI != ME; ++MI)
7443 if ((*MI)->getMinRequiredArguments() == 0)
7444 return true;
7445 return false;
7446}
7447
Richard Smith55ce3522012-06-25 20:30:08 +00007448// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007449// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00007450// Returns true when a c_str() conversion method is found.
7451bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00007452 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007453 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00007454
7455 MethodSet Results =
7456 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7457
7458 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7459 MI != ME; ++MI) {
7460 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00007461 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00007462 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00007463 // FIXME: Suggest parens if the expression needs them.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007464 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007465 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7466 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
Richard Smith55ce3522012-06-25 20:30:08 +00007467 return true;
7468 }
7469 }
7470
7471 return false;
7472}
7473
Ted Kremenekab278de2010-01-28 23:39:18 +00007474bool
Ted Kremenek02087932010-07-16 02:11:22 +00007475CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00007476 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00007477 const char *startSpecifier,
7478 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007479 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007480 using namespace analyze_printf;
7481
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007482 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00007483
Ted Kremenek6cd69422010-07-19 22:01:06 +00007484 if (FS.consumesDataArgument()) {
7485 if (atFirstArg) {
7486 atFirstArg = false;
7487 usesPositionalArgs = FS.usesPositionalArg();
7488 }
7489 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007490 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7491 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007492 return false;
7493 }
Ted Kremenek5739de72010-01-29 01:06:55 +00007494 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007495
Ted Kremenekd1668192010-02-27 01:41:03 +00007496 // First check if the field width, precision, and conversion specifier
7497 // have matching data arguments.
7498 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7499 startSpecifier, specifierLen)) {
7500 return false;
7501 }
7502
7503 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7504 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007505 return false;
7506 }
7507
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007508 if (!CS.consumesDataArgument()) {
7509 // FIXME: Technically specifying a precision or field width here
7510 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00007511 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007512 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007513
Ted Kremenek4a49d982010-02-26 19:18:41 +00007514 // Consume the argument.
7515 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00007516 if (argIndex < NumDataArgs) {
7517 // The check to see if the argIndex is valid will come later.
7518 // We set the bit here because we may exit early from this
7519 // function if we encounter some other error.
7520 CoveredArgs.set(argIndex);
7521 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00007522
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007523 // FreeBSD kernel extensions.
7524 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7525 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7526 // We need at least two arguments.
7527 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7528 return false;
7529
7530 // Claim the second argument.
7531 CoveredArgs.set(argIndex + 1);
7532
7533 // Type check the first argument (int for %b, pointer for %D)
7534 const Expr *Ex = getDataArg(argIndex);
7535 const analyze_printf::ArgType &AT =
7536 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7537 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7538 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7539 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007540 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7541 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7542 << false << Ex->getSourceRange(),
7543 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7544 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007545
7546 // Type check the second argument (char * for both %b and %D)
7547 Ex = getDataArg(argIndex + 1);
7548 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7549 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7550 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007551 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7552 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7553 << false << Ex->getSourceRange(),
7554 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7555 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007556
7557 return true;
7558 }
7559
Ted Kremenek4a49d982010-02-26 19:18:41 +00007560 // Check for using an Objective-C specific conversion specifier
7561 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00007562 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00007563 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7564 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00007565 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007566
Mehdi Amini06d367c2016-10-24 20:39:34 +00007567 // %P can only be used with os_log.
7568 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7569 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7570 specifierLen);
7571 }
7572
7573 // %n is not allowed with os_log.
7574 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7575 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7576 getLocationOfByte(CS.getStart()),
7577 /*IsStringLocation*/ false,
7578 getSpecifierRange(startSpecifier, specifierLen));
7579
7580 return true;
7581 }
7582
7583 // Only scalars are allowed for os_trace.
7584 if (FSType == Sema::FST_OSTrace &&
7585 (CS.getKind() == ConversionSpecifier::PArg ||
7586 CS.getKind() == ConversionSpecifier::sArg ||
7587 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7588 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7589 specifierLen);
7590 }
7591
7592 // Check for use of public/private annotation outside of os_log().
7593 if (FSType != Sema::FST_OSLog) {
7594 if (FS.isPublic().isSet()) {
7595 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7596 << "public",
7597 getLocationOfByte(FS.isPublic().getPosition()),
7598 /*IsStringLocation*/ false,
7599 getSpecifierRange(startSpecifier, specifierLen));
7600 }
7601 if (FS.isPrivate().isSet()) {
7602 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7603 << "private",
7604 getLocationOfByte(FS.isPrivate().getPosition()),
7605 /*IsStringLocation*/ false,
7606 getSpecifierRange(startSpecifier, specifierLen));
7607 }
7608 }
7609
Tom Careb49ec692010-06-17 19:00:27 +00007610 // Check for invalid use of field width
7611 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00007612 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00007613 startSpecifier, specifierLen);
7614 }
7615
7616 // Check for invalid use of precision
7617 if (!FS.hasValidPrecision()) {
7618 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7619 startSpecifier, specifierLen);
7620 }
7621
Mehdi Amini06d367c2016-10-24 20:39:34 +00007622 // Precision is mandatory for %P specifier.
7623 if (CS.getKind() == ConversionSpecifier::PArg &&
7624 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7625 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7626 getLocationOfByte(startSpecifier),
7627 /*IsStringLocation*/ false,
7628 getSpecifierRange(startSpecifier, specifierLen));
7629 }
7630
Tom Careb49ec692010-06-17 19:00:27 +00007631 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00007632 if (!FS.hasValidThousandsGroupingPrefix())
7633 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007634 if (!FS.hasValidLeadingZeros())
7635 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7636 if (!FS.hasValidPlusPrefix())
7637 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00007638 if (!FS.hasValidSpacePrefix())
7639 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007640 if (!FS.hasValidAlternativeForm())
7641 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7642 if (!FS.hasValidLeftJustified())
7643 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7644
7645 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00007646 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7647 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7648 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007649 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7650 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7651 startSpecifier, specifierLen);
7652
7653 // Check the length modifier is valid with the given conversion specifier.
Matt Arsenault58fc8082019-01-29 20:49:54 +00007654 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7655 S.getLangOpts()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007656 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7657 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007658 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007659 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007660 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007661 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7662 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00007663
Jordan Rose92303592012-09-08 04:00:03 +00007664 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7665 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7666
Ted Kremenek9fcd8302010-01-29 01:43:31 +00007667 // The remaining checks depend on the data arguments.
7668 if (HasVAListArg)
7669 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007670
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007671 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00007672 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007673
Jordan Rose58bbe422012-07-19 18:10:08 +00007674 const Expr *Arg = getDataArg(argIndex);
7675 if (!Arg)
7676 return true;
7677
7678 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00007679}
7680
Jordan Roseaee34382012-09-05 22:56:26 +00007681static bool requiresParensToAddCast(const Expr *E) {
7682 // FIXME: We should have a general way to reason about operator
7683 // precedence and whether parens are actually needed here.
7684 // Take care of a few common cases where they aren't.
7685 const Expr *Inside = E->IgnoreImpCasts();
7686 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7687 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7688
7689 switch (Inside->getStmtClass()) {
7690 case Stmt::ArraySubscriptExprClass:
7691 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007692 case Stmt::CharacterLiteralClass:
7693 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007694 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007695 case Stmt::FloatingLiteralClass:
7696 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007697 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007698 case Stmt::ObjCArrayLiteralClass:
7699 case Stmt::ObjCBoolLiteralExprClass:
7700 case Stmt::ObjCBoxedExprClass:
7701 case Stmt::ObjCDictionaryLiteralClass:
7702 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007703 case Stmt::ObjCIvarRefExprClass:
7704 case Stmt::ObjCMessageExprClass:
7705 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007706 case Stmt::ObjCStringLiteralClass:
7707 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007708 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007709 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007710 case Stmt::UnaryOperatorClass:
7711 return false;
7712 default:
7713 return true;
7714 }
7715}
7716
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007717static std::pair<QualType, StringRef>
7718shouldNotPrintDirectly(const ASTContext &Context,
7719 QualType IntendedTy,
7720 const Expr *E) {
7721 // Use a 'while' to peel off layers of typedefs.
7722 QualType TyTy = IntendedTy;
7723 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7724 StringRef Name = UserTy->getDecl()->getName();
7725 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00007726 .Case("CFIndex", Context.getNSIntegerType())
7727 .Case("NSInteger", Context.getNSIntegerType())
7728 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007729 .Case("SInt32", Context.IntTy)
7730 .Case("UInt32", Context.UnsignedIntTy)
7731 .Default(QualType());
7732
7733 if (!CastTy.isNull())
7734 return std::make_pair(CastTy, Name);
7735
7736 TyTy = UserTy->desugar();
7737 }
7738
7739 // Strip parens if necessary.
7740 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7741 return shouldNotPrintDirectly(Context,
7742 PE->getSubExpr()->getType(),
7743 PE->getSubExpr());
7744
7745 // If this is a conditional expression, then its result type is constructed
7746 // via usual arithmetic conversions and thus there might be no necessary
7747 // typedef sugar there. Recurse to operands to check for NSInteger &
7748 // Co. usage condition.
7749 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7750 QualType TrueTy, FalseTy;
7751 StringRef TrueName, FalseName;
7752
7753 std::tie(TrueTy, TrueName) =
7754 shouldNotPrintDirectly(Context,
7755 CO->getTrueExpr()->getType(),
7756 CO->getTrueExpr());
7757 std::tie(FalseTy, FalseName) =
7758 shouldNotPrintDirectly(Context,
7759 CO->getFalseExpr()->getType(),
7760 CO->getFalseExpr());
7761
7762 if (TrueTy == FalseTy)
7763 return std::make_pair(TrueTy, TrueName);
7764 else if (TrueTy.isNull())
7765 return std::make_pair(FalseTy, FalseName);
7766 else if (FalseTy.isNull())
7767 return std::make_pair(TrueTy, TrueName);
7768 }
7769
7770 return std::make_pair(QualType(), StringRef());
7771}
7772
Aaron Ballman94d2d092018-12-18 15:54:38 +00007773/// Return true if \p ICE is an implicit argument promotion of an arithmetic
7774/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7775/// type do not count.
7776static bool
7777isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
7778 QualType From = ICE->getSubExpr()->getType();
7779 QualType To = ICE->getType();
7780 // It's an integer promotion if the destination type is the promoted
7781 // source type.
7782 if (ICE->getCastKind() == CK_IntegralCast &&
7783 From->isPromotableIntegerType() &&
7784 S.Context.getPromotedIntegerType(From) == To)
7785 return true;
7786 // Look through vector types, since we do default argument promotion for
7787 // those in OpenCL.
7788 if (const auto *VecTy = From->getAs<ExtVectorType>())
7789 From = VecTy->getElementType();
7790 if (const auto *VecTy = To->getAs<ExtVectorType>())
7791 To = VecTy->getElementType();
7792 // It's a floating promotion if the source type is a lower rank.
7793 return ICE->getCastKind() == CK_FloatingCast &&
7794 S.Context.getFloatingTypeOrder(From, To) < 0;
7795}
7796
Richard Smith55ce3522012-06-25 20:30:08 +00007797bool
7798CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7799 const char *StartSpecifier,
7800 unsigned SpecifierLen,
7801 const Expr *E) {
7802 using namespace analyze_format_string;
7803 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007804
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007805 // Now type check the data expression that matches the
7806 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00007807 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00007808 if (!AT.isValid())
7809 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00007810
Jordan Rose598ec092012-12-05 18:44:40 +00007811 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00007812 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7813 ExprTy = TET->getUnderlyingExpr()->getType();
7814 }
7815
JF Bastienec7d7f32018-06-22 21:54:40 +00007816 const analyze_printf::ArgType::MatchKind Match =
7817 AT.matchesType(S.Context, ExprTy);
7818 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7819 if (Match == analyze_printf::ArgType::Match)
Jordan Rose22b74712012-09-05 22:56:19 +00007820 return true;
Jordan Rose98709982012-06-04 22:48:57 +00007821
Jordan Rose22b74712012-09-05 22:56:19 +00007822 // Look through argument promotions for our error message's reported type.
7823 // This includes the integral and floating promotions, but excludes array
Aaron Ballman94d2d092018-12-18 15:54:38 +00007824 // and function pointer decay (seeing that an argument intended to be a
7825 // string has type 'char [6]' is probably more confusing than 'char *') and
7826 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
Jordan Rose22b74712012-09-05 22:56:19 +00007827 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Aaron Ballman94d2d092018-12-18 15:54:38 +00007828 if (isArithmeticArgumentPromotion(S, ICE)) {
Jordan Rose22b74712012-09-05 22:56:19 +00007829 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00007830 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00007831
7832 // Check if we didn't match because of an implicit cast from a 'char'
7833 // or 'short' to an 'int'. This is done because printf is a varargs
7834 // function.
7835 if (ICE->getType() == S.Context.IntTy ||
7836 ICE->getType() == S.Context.UnsignedIntTy) {
7837 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00007838 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00007839 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00007840 }
Jordan Rose98709982012-06-04 22:48:57 +00007841 }
Jordan Rose598ec092012-12-05 18:44:40 +00007842 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7843 // Special case for 'a', which has type 'int' in C.
7844 // Note, however, that we do /not/ want to treat multibyte constants like
7845 // 'MooV' as characters! This form is deprecated but still exists.
7846 if (ExprTy == S.Context.IntTy)
7847 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7848 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00007849 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007850
Jordan Rosebc53ed12014-05-31 04:12:14 +00007851 // Look through enums to their underlying type.
7852 bool IsEnum = false;
7853 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7854 ExprTy = EnumTy->getDecl()->getIntegerType();
7855 IsEnum = true;
7856 }
7857
Jordan Rose0e5badd2012-12-05 18:44:49 +00007858 // %C in an Objective-C context prints a unichar, not a wchar_t.
7859 // If the argument is an integer of some kind, believe the %C and suggest
7860 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00007861 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00007862 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00007863 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7864 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7865 !ExprTy->isCharType()) {
7866 // 'unichar' is defined as a typedef of unsigned short, but we should
7867 // prefer using the typedef if it is visible.
7868 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00007869
7870 // While we are here, check if the value is an IntegerLiteral that happens
7871 // to be within the valid range.
7872 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7873 const llvm::APInt &V = IL->getValue();
7874 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7875 return true;
7876 }
7877
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007878 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
Jordan Rose0e5badd2012-12-05 18:44:49 +00007879 Sema::LookupOrdinaryName);
7880 if (S.LookupName(Result, S.getCurScope())) {
7881 NamedDecl *ND = Result.getFoundDecl();
7882 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7883 if (TD->getUnderlyingType() == IntendedTy)
7884 IntendedTy = S.Context.getTypedefType(TD);
7885 }
7886 }
7887 }
7888
7889 // Special-case some of Darwin's platform-independence types by suggesting
7890 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007891 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00007892 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007893 QualType CastTy;
7894 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7895 if (!CastTy.isNull()) {
Alex Lorenzb2043ac2018-07-05 22:51:11 +00007896 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
JF Bastienec7d7f32018-06-22 21:54:40 +00007897 // (long in ASTContext). Only complain to pedants.
7898 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
Alex Lorenzb2043ac2018-07-05 22:51:11 +00007899 (AT.isSizeT() || AT.isPtrdiffT()) &&
7900 AT.matchesType(S.Context, CastTy))
JF Bastienec7d7f32018-06-22 21:54:40 +00007901 Pedantic = true;
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007902 IntendedTy = CastTy;
7903 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00007904 }
7905 }
7906
Jordan Rose22b74712012-09-05 22:56:19 +00007907 // We may be able to offer a FixItHint if it is a supported type.
7908 PrintfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00007909 bool Success =
Mehdi Amini06d367c2016-10-24 20:39:34 +00007910 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007911
JF Bastienec7d7f32018-06-22 21:54:40 +00007912 if (Success) {
Jordan Rose22b74712012-09-05 22:56:19 +00007913 // Get the fix string from the fixed format specifier
7914 SmallString<16> buf;
7915 llvm::raw_svector_ostream os(buf);
7916 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007917
Jordan Roseaee34382012-09-05 22:56:26 +00007918 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7919
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007920 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
JF Bastienec7d7f32018-06-22 21:54:40 +00007921 unsigned Diag =
7922 Pedantic
7923 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7924 : diag::warn_format_conversion_argument_type_mismatch;
Jordan Rose0e5badd2012-12-05 18:44:49 +00007925 // In this case, the specifier is wrong and should be changed to match
7926 // the argument.
JF Bastienec7d7f32018-06-22 21:54:40 +00007927 EmitFormatDiagnostic(S.PDiag(Diag)
Daniel Jasperad8d8492015-03-04 14:18:20 +00007928 << AT.getRepresentativeTypeName(S.Context)
7929 << IntendedTy << IsEnum << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007930 E->getBeginLoc(),
Daniel Jasperad8d8492015-03-04 14:18:20 +00007931 /*IsStringLocation*/ false, SpecRange,
7932 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00007933 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00007934 // The canonical type for formatting this value is different from the
7935 // actual type of the expression. (This occurs, for example, with Darwin's
7936 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7937 // should be printed as 'long' for 64-bit compatibility.)
7938 // Rather than emitting a normal format/argument mismatch, we want to
7939 // add a cast to the recommended type (and correct the format string
7940 // if necessary).
7941 SmallString<16> CastBuf;
7942 llvm::raw_svector_ostream CastFix(CastBuf);
7943 CastFix << "(";
7944 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7945 CastFix << ")";
7946
7947 SmallVector<FixItHint,4> Hints;
Fangrui Song6907ce22018-07-30 19:24:48 +00007948 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00007949 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7950
7951 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7952 // If there's already a cast present, just replace it.
7953 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7954 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7955
7956 } else if (!requiresParensToAddCast(E)) {
7957 // If the expression has high enough precedence,
7958 // just write the C-style cast.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007959 Hints.push_back(
7960 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00007961 } else {
7962 // Otherwise, add parens around the expression as well as the cast.
7963 CastFix << "(";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007964 Hints.push_back(
7965 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00007966
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007967 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
Jordan Roseaee34382012-09-05 22:56:26 +00007968 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7969 }
7970
Jordan Rose0e5badd2012-12-05 18:44:49 +00007971 if (ShouldNotPrintDirectly) {
7972 // The expression has a type that should not be printed directly.
7973 // We extract the name from the typedef because we don't want to show
7974 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007975 StringRef Name;
7976 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
7977 Name = TypedefTy->getDecl()->getName();
7978 else
7979 Name = CastTyName;
JF Bastienec7d7f32018-06-22 21:54:40 +00007980 unsigned Diag = Pedantic
7981 ? diag::warn_format_argument_needs_cast_pedantic
7982 : diag::warn_format_argument_needs_cast;
7983 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7984 << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007985 E->getBeginLoc(), /*IsStringLocation=*/false,
Jordan Rose0e5badd2012-12-05 18:44:49 +00007986 SpecRange, Hints);
7987 } else {
7988 // In this case, the expression could be printed using a different
Fangrui Song6907ce22018-07-30 19:24:48 +00007989 // specifier, but we've decided that the specifier is probably correct
Jordan Rose0e5badd2012-12-05 18:44:49 +00007990 // and we should cast instead. Just use the normal warning message.
7991 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007992 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7993 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
7994 << E->getSourceRange(),
7995 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
Jordan Rose0e5badd2012-12-05 18:44:49 +00007996 }
Jordan Roseaee34382012-09-05 22:56:26 +00007997 }
Jordan Rose22b74712012-09-05 22:56:19 +00007998 } else {
7999 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8000 SpecifierLen);
8001 // Since the warning for passing non-POD types to variadic functions
8002 // was deferred until now, we emit a warning for non-POD
8003 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00008004 switch (S.isValidVarArgType(ExprTy)) {
8005 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00008006 case Sema::VAK_ValidInCXX11: {
JF Bastienec7d7f32018-06-22 21:54:40 +00008007 unsigned Diag =
8008 Pedantic
8009 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8010 : diag::warn_format_conversion_argument_type_mismatch;
Richard Smithd7293d72013-08-05 18:49:43 +00008011
Seth Cantrellb4802962015-03-04 03:12:10 +00008012 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00008013 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
Seth Cantrellb4802962015-03-04 03:12:10 +00008014 << IsEnum << CSR << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008015 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Seth Cantrellb4802962015-03-04 03:12:10 +00008016 break;
8017 }
Richard Smithd7293d72013-08-05 18:49:43 +00008018 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00008019 case Sema::VAK_MSVCUndefined:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008020 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8021 << S.getLangOpts().CPlusPlus11 << ExprTy
8022 << CallType
8023 << AT.getRepresentativeTypeName(S.Context) << CSR
8024 << E->getSourceRange(),
8025 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00008026 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00008027 break;
8028
8029 case Sema::VAK_Invalid:
8030 if (ExprTy->isObjCObjectType())
8031 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008032 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8033 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8034 << AT.getRepresentativeTypeName(S.Context) << CSR
8035 << E->getSourceRange(),
8036 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00008037 else
8038 // FIXME: If this is an initializer list, suggest removing the braces
8039 // or inserting a cast to the target type.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008040 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8041 << isa<InitListExpr>(E) << ExprTy << CallType
8042 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
Richard Smithd7293d72013-08-05 18:49:43 +00008043 break;
8044 }
8045
8046 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8047 "format string specifier index out of range");
8048 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00008049 }
8050
Ted Kremenekab278de2010-01-28 23:39:18 +00008051 return true;
8052}
8053
Ted Kremenek02087932010-07-16 02:11:22 +00008054//===--- CHECK: Scanf format string checking ------------------------------===//
8055
Fangrui Song6907ce22018-07-30 19:24:48 +00008056namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008057
Ted Kremenek02087932010-07-16 02:11:22 +00008058class CheckScanfHandler : public CheckFormatHandler {
8059public:
Stephen Hines648c3692016-09-16 01:07:04 +00008060 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00008061 const Expr *origFormatExpr, Sema::FormatStringType type,
8062 unsigned firstDataArg, unsigned numDataArgs,
8063 const char *beg, bool hasVAListArg,
8064 ArrayRef<const Expr *> Args, unsigned formatIdx,
8065 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00008066 llvm::SmallBitVector &CheckedVarArgs,
8067 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00008068 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8069 numDataArgs, beg, hasVAListArg, Args, formatIdx,
8070 inFunctionCall, CallType, CheckedVarArgs,
8071 UncoveredArg) {}
8072
Ted Kremenek02087932010-07-16 02:11:22 +00008073 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8074 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00008075 unsigned specifierLen) override;
Fangrui Song6907ce22018-07-30 19:24:48 +00008076
Ted Kremenekce815422010-07-19 21:25:57 +00008077 bool HandleInvalidScanfConversionSpecifier(
8078 const analyze_scanf::ScanfSpecifier &FS,
8079 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00008080 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008081
Craig Toppere14c0f82014-03-12 04:55:44 +00008082 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00008083};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008084
8085} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00008086
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008087void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8088 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008089 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8090 getLocationOfByte(end), /*IsStringLocation*/true,
8091 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00008092}
8093
Ted Kremenekce815422010-07-19 21:25:57 +00008094bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8095 const analyze_scanf::ScanfSpecifier &FS,
8096 const char *startSpecifier,
8097 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008098 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00008099 FS.getConversionSpecifier();
8100
8101 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8102 getLocationOfByte(CS.getStart()),
8103 startSpecifier, specifierLen,
8104 CS.getStart(), CS.getLength());
8105}
8106
Ted Kremenek02087932010-07-16 02:11:22 +00008107bool CheckScanfHandler::HandleScanfSpecifier(
8108 const analyze_scanf::ScanfSpecifier &FS,
8109 const char *startSpecifier,
8110 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00008111 using namespace analyze_scanf;
Fangrui Song6907ce22018-07-30 19:24:48 +00008112 using namespace analyze_format_string;
Ted Kremenek02087932010-07-16 02:11:22 +00008113
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008114 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00008115
Ted Kremenek6cd69422010-07-19 22:01:06 +00008116 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8117 // be used to decide if we are using positional arguments consistently.
8118 if (FS.consumesDataArgument()) {
8119 if (atFirstArg) {
8120 atFirstArg = false;
8121 usesPositionalArgs = FS.usesPositionalArg();
8122 }
8123 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008124 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8125 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00008126 return false;
8127 }
Ted Kremenek02087932010-07-16 02:11:22 +00008128 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008129
Ted Kremenek02087932010-07-16 02:11:22 +00008130 // Check if the field with is non-zero.
8131 const OptionalAmount &Amt = FS.getFieldWidth();
8132 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8133 if (Amt.getConstantAmount() == 0) {
8134 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8135 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00008136 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8137 getLocationOfByte(Amt.getStart()),
8138 /*IsStringLocation*/true, R,
8139 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00008140 }
8141 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008142
Ted Kremenek02087932010-07-16 02:11:22 +00008143 if (!FS.consumesDataArgument()) {
8144 // FIXME: Technically specifying a precision or field width here
8145 // makes no sense. Worth issuing a warning at some point.
8146 return true;
8147 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008148
Ted Kremenek02087932010-07-16 02:11:22 +00008149 // Consume the argument.
8150 unsigned argIndex = FS.getArgIndex();
8151 if (argIndex < NumDataArgs) {
8152 // The check to see if the argIndex is valid will come later.
8153 // We set the bit here because we may exit early from this
8154 // function if we encounter some other error.
8155 CoveredArgs.set(argIndex);
8156 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008157
Ted Kremenek4407ea42010-07-20 20:04:47 +00008158 // Check the length modifier is valid with the given conversion specifier.
Matt Arsenault58fc8082019-01-29 20:49:54 +00008159 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8160 S.getLangOpts()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00008161 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8162 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00008163 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008164 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00008165 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008166 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8167 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00008168
Jordan Rose92303592012-09-08 04:00:03 +00008169 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8170 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8171
Ted Kremenek02087932010-07-16 02:11:22 +00008172 // The remaining checks depend on the data arguments.
8173 if (HasVAListArg)
8174 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008175
Ted Kremenek6adb7e32010-07-26 19:45:42 +00008176 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00008177 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00008178
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008179 // Check that the argument type matches the format specifier.
8180 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00008181 if (!Ex)
8182 return true;
8183
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00008184 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00008185
8186 if (!AT.isValid()) {
8187 return true;
8188 }
8189
JF Bastienec7d7f32018-06-22 21:54:40 +00008190 analyze_format_string::ArgType::MatchKind Match =
Seth Cantrellb4802962015-03-04 03:12:10 +00008191 AT.matchesType(S.Context, Ex->getType());
JF Bastienec7d7f32018-06-22 21:54:40 +00008192 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8193 if (Match == analyze_format_string::ArgType::Match)
Seth Cantrell79340072015-03-04 05:58:08 +00008194 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008195
Seth Cantrell79340072015-03-04 05:58:08 +00008196 ScanfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00008197 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
Seth Cantrell79340072015-03-04 05:58:08 +00008198 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008199
JF Bastienec7d7f32018-06-22 21:54:40 +00008200 unsigned Diag =
8201 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8202 : diag::warn_format_conversion_argument_type_mismatch;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008203
JF Bastienec7d7f32018-06-22 21:54:40 +00008204 if (Success) {
Seth Cantrell79340072015-03-04 05:58:08 +00008205 // Get the fix string from the fixed format specifier.
8206 SmallString<128> buf;
8207 llvm::raw_svector_ostream os(buf);
8208 fixedFS.toString(os);
8209
8210 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00008211 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
Seth Cantrell79340072015-03-04 05:58:08 +00008212 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008213 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008214 /*IsStringLocation*/ false,
8215 getSpecifierRange(startSpecifier, specifierLen),
8216 FixItHint::CreateReplacement(
8217 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8218 } else {
JF Bastienec7d7f32018-06-22 21:54:40 +00008219 EmitFormatDiagnostic(S.PDiag(Diag)
Seth Cantrell79340072015-03-04 05:58:08 +00008220 << AT.getRepresentativeTypeName(S.Context)
8221 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008222 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008223 /*IsStringLocation*/ false,
8224 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008225 }
8226
Ted Kremenek02087932010-07-16 02:11:22 +00008227 return true;
8228}
8229
Stephen Hines648c3692016-09-16 01:07:04 +00008230static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008231 const Expr *OrigFormatExpr,
8232 ArrayRef<const Expr *> Args,
8233 bool HasVAListArg, unsigned format_idx,
8234 unsigned firstDataArg,
8235 Sema::FormatStringType Type,
8236 bool inFunctionCall,
8237 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00008238 llvm::SmallBitVector &CheckedVarArgs,
8239 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00008240 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00008241 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008242 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008243 S, inFunctionCall, Args[format_idx],
8244 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8245 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008246 return;
8247 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008248
Ted Kremenekab278de2010-01-28 23:39:18 +00008249 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008250 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00008251 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008252 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008253 const ConstantArrayType *T =
8254 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008255 assert(T && "String literal not of constant array type!");
8256 size_t TypeSize = T->getSize().getZExtValue();
8257 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00008258 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008259
8260 // Emit a warning if the string literal is truncated and does not contain an
8261 // embedded null character.
8262 if (TypeSize <= StrRef.size() &&
8263 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8264 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008265 S, inFunctionCall, Args[format_idx],
8266 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008267 FExpr->getBeginLoc(),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008268 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8269 return;
8270 }
8271
Ted Kremenekab278de2010-01-28 23:39:18 +00008272 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00008273 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008274 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008275 S, inFunctionCall, Args[format_idx],
8276 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8277 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008278 return;
8279 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008280
8281 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00008282 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8283 Type == Sema::FST_OSTrace) {
8284 CheckPrintfHandler H(
8285 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8286 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8287 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8288 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008289
Hans Wennborg23926bd2011-12-15 10:25:47 +00008290 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008291 S.getLangOpts(),
8292 S.Context.getTargetInfo(),
8293 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00008294 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008295 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00008296 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8297 numDataArgs, Str, HasVAListArg, Args, format_idx,
8298 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008299
Hans Wennborg23926bd2011-12-15 10:25:47 +00008300 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008301 S.getLangOpts(),
8302 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00008303 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00008304 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00008305}
8306
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00008307bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8308 // Str - The format string. NOTE: this is NOT null-terminated!
8309 StringRef StrRef = FExpr->getString();
8310 const char *Str = StrRef.data();
8311 // Account for cases where the string literal is truncated in a declaration.
8312 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8313 assert(T && "String literal not of constant array type!");
8314 size_t TypeSize = T->getSize().getZExtValue();
8315 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8316 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8317 getLangOpts(),
8318 Context.getTargetInfo());
8319}
8320
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008321//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8322
8323// Returns the related absolute value function that is larger, of 0 if one
8324// does not exist.
8325static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8326 switch (AbsFunction) {
8327 default:
8328 return 0;
8329
8330 case Builtin::BI__builtin_abs:
8331 return Builtin::BI__builtin_labs;
8332 case Builtin::BI__builtin_labs:
8333 return Builtin::BI__builtin_llabs;
8334 case Builtin::BI__builtin_llabs:
8335 return 0;
8336
8337 case Builtin::BI__builtin_fabsf:
8338 return Builtin::BI__builtin_fabs;
8339 case Builtin::BI__builtin_fabs:
8340 return Builtin::BI__builtin_fabsl;
8341 case Builtin::BI__builtin_fabsl:
8342 return 0;
8343
8344 case Builtin::BI__builtin_cabsf:
8345 return Builtin::BI__builtin_cabs;
8346 case Builtin::BI__builtin_cabs:
8347 return Builtin::BI__builtin_cabsl;
8348 case Builtin::BI__builtin_cabsl:
8349 return 0;
8350
8351 case Builtin::BIabs:
8352 return Builtin::BIlabs;
8353 case Builtin::BIlabs:
8354 return Builtin::BIllabs;
8355 case Builtin::BIllabs:
8356 return 0;
8357
8358 case Builtin::BIfabsf:
8359 return Builtin::BIfabs;
8360 case Builtin::BIfabs:
8361 return Builtin::BIfabsl;
8362 case Builtin::BIfabsl:
8363 return 0;
8364
8365 case Builtin::BIcabsf:
8366 return Builtin::BIcabs;
8367 case Builtin::BIcabs:
8368 return Builtin::BIcabsl;
8369 case Builtin::BIcabsl:
8370 return 0;
8371 }
8372}
8373
8374// Returns the argument type of the absolute value function.
8375static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8376 unsigned AbsType) {
8377 if (AbsType == 0)
8378 return QualType();
8379
8380 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8381 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8382 if (Error != ASTContext::GE_None)
8383 return QualType();
8384
8385 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8386 if (!FT)
8387 return QualType();
8388
8389 if (FT->getNumParams() != 1)
8390 return QualType();
8391
8392 return FT->getParamType(0);
8393}
8394
8395// Returns the best absolute value function, or zero, based on type and
8396// current absolute value function.
8397static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8398 unsigned AbsFunctionKind) {
8399 unsigned BestKind = 0;
8400 uint64_t ArgSize = Context.getTypeSize(ArgType);
8401 for (unsigned Kind = AbsFunctionKind; Kind != 0;
8402 Kind = getLargerAbsoluteValueFunction(Kind)) {
8403 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8404 if (Context.getTypeSize(ParamType) >= ArgSize) {
8405 if (BestKind == 0)
8406 BestKind = Kind;
8407 else if (Context.hasSameType(ParamType, ArgType)) {
8408 BestKind = Kind;
8409 break;
8410 }
8411 }
8412 }
8413 return BestKind;
8414}
8415
8416enum AbsoluteValueKind {
8417 AVK_Integer,
8418 AVK_Floating,
8419 AVK_Complex
8420};
8421
8422static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8423 if (T->isIntegralOrEnumerationType())
8424 return AVK_Integer;
8425 if (T->isRealFloatingType())
8426 return AVK_Floating;
8427 if (T->isAnyComplexType())
8428 return AVK_Complex;
8429
8430 llvm_unreachable("Type not integer, floating, or complex");
8431}
8432
8433// Changes the absolute value function to a different type. Preserves whether
8434// the function is a builtin.
8435static unsigned changeAbsFunction(unsigned AbsKind,
8436 AbsoluteValueKind ValueKind) {
8437 switch (ValueKind) {
8438 case AVK_Integer:
8439 switch (AbsKind) {
8440 default:
8441 return 0;
8442 case Builtin::BI__builtin_fabsf:
8443 case Builtin::BI__builtin_fabs:
8444 case Builtin::BI__builtin_fabsl:
8445 case Builtin::BI__builtin_cabsf:
8446 case Builtin::BI__builtin_cabs:
8447 case Builtin::BI__builtin_cabsl:
8448 return Builtin::BI__builtin_abs;
8449 case Builtin::BIfabsf:
8450 case Builtin::BIfabs:
8451 case Builtin::BIfabsl:
8452 case Builtin::BIcabsf:
8453 case Builtin::BIcabs:
8454 case Builtin::BIcabsl:
8455 return Builtin::BIabs;
8456 }
8457 case AVK_Floating:
8458 switch (AbsKind) {
8459 default:
8460 return 0;
8461 case Builtin::BI__builtin_abs:
8462 case Builtin::BI__builtin_labs:
8463 case Builtin::BI__builtin_llabs:
8464 case Builtin::BI__builtin_cabsf:
8465 case Builtin::BI__builtin_cabs:
8466 case Builtin::BI__builtin_cabsl:
8467 return Builtin::BI__builtin_fabsf;
8468 case Builtin::BIabs:
8469 case Builtin::BIlabs:
8470 case Builtin::BIllabs:
8471 case Builtin::BIcabsf:
8472 case Builtin::BIcabs:
8473 case Builtin::BIcabsl:
8474 return Builtin::BIfabsf;
8475 }
8476 case AVK_Complex:
8477 switch (AbsKind) {
8478 default:
8479 return 0;
8480 case Builtin::BI__builtin_abs:
8481 case Builtin::BI__builtin_labs:
8482 case Builtin::BI__builtin_llabs:
8483 case Builtin::BI__builtin_fabsf:
8484 case Builtin::BI__builtin_fabs:
8485 case Builtin::BI__builtin_fabsl:
8486 return Builtin::BI__builtin_cabsf;
8487 case Builtin::BIabs:
8488 case Builtin::BIlabs:
8489 case Builtin::BIllabs:
8490 case Builtin::BIfabsf:
8491 case Builtin::BIfabs:
8492 case Builtin::BIfabsl:
8493 return Builtin::BIcabsf;
8494 }
8495 }
8496 llvm_unreachable("Unable to convert function");
8497}
8498
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00008499static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008500 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8501 if (!FnInfo)
8502 return 0;
8503
8504 switch (FDecl->getBuiltinID()) {
8505 default:
8506 return 0;
8507 case Builtin::BI__builtin_abs:
8508 case Builtin::BI__builtin_fabs:
8509 case Builtin::BI__builtin_fabsf:
8510 case Builtin::BI__builtin_fabsl:
8511 case Builtin::BI__builtin_labs:
8512 case Builtin::BI__builtin_llabs:
8513 case Builtin::BI__builtin_cabs:
8514 case Builtin::BI__builtin_cabsf:
8515 case Builtin::BI__builtin_cabsl:
8516 case Builtin::BIabs:
8517 case Builtin::BIlabs:
8518 case Builtin::BIllabs:
8519 case Builtin::BIfabs:
8520 case Builtin::BIfabsf:
8521 case Builtin::BIfabsl:
8522 case Builtin::BIcabs:
8523 case Builtin::BIcabsf:
8524 case Builtin::BIcabsl:
8525 return FDecl->getBuiltinID();
8526 }
8527 llvm_unreachable("Unknown Builtin type");
8528}
8529
8530// If the replacement is valid, emit a note with replacement function.
8531// Additionally, suggest including the proper header if not already included.
8532static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00008533 unsigned AbsKind, QualType ArgType) {
8534 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00008535 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00008536 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00008537 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8538 FunctionName = "std::abs";
8539 if (ArgType->isIntegralOrEnumerationType()) {
8540 HeaderName = "cstdlib";
8541 } else if (ArgType->isRealFloatingType()) {
8542 HeaderName = "cmath";
8543 } else {
8544 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008545 }
Richard Trieubeffb832014-04-15 23:47:53 +00008546
8547 // Lookup all std::abs
8548 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00008549 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00008550 R.suppressDiagnostics();
8551 S.LookupQualifiedName(R, Std);
8552
8553 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008554 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00008555 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8556 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8557 } else {
8558 FDecl = dyn_cast<FunctionDecl>(I);
8559 }
8560 if (!FDecl)
8561 continue;
8562
8563 // Found std::abs(), check that they are the right ones.
8564 if (FDecl->getNumParams() != 1)
8565 continue;
8566
8567 // Check that the parameter type can handle the argument.
8568 QualType ParamType = FDecl->getParamDecl(0)->getType();
8569 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8570 S.Context.getTypeSize(ArgType) <=
8571 S.Context.getTypeSize(ParamType)) {
8572 // Found a function, don't need the header hint.
8573 EmitHeaderHint = false;
8574 break;
8575 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008576 }
Richard Trieubeffb832014-04-15 23:47:53 +00008577 }
8578 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00008579 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00008580 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8581
8582 if (HeaderName) {
8583 DeclarationName DN(&S.Context.Idents.get(FunctionName));
8584 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8585 R.suppressDiagnostics();
8586 S.LookupName(R, S.getCurScope());
8587
8588 if (R.isSingleResult()) {
8589 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8590 if (FD && FD->getBuiltinID() == AbsKind) {
8591 EmitHeaderHint = false;
8592 } else {
8593 return;
8594 }
8595 } else if (!R.empty()) {
8596 return;
8597 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008598 }
8599 }
8600
8601 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00008602 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008603
Richard Trieubeffb832014-04-15 23:47:53 +00008604 if (!HeaderName)
8605 return;
8606
8607 if (!EmitHeaderHint)
8608 return;
8609
Alp Toker5d96e0a2014-07-11 20:53:51 +00008610 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8611 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00008612}
8613
Richard Trieua7f30b12016-12-06 01:42:28 +00008614template <std::size_t StrLen>
8615static bool IsStdFunction(const FunctionDecl *FDecl,
8616 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00008617 if (!FDecl)
8618 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00008619 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00008620 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00008621 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00008622 return false;
8623
8624 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008625}
8626
8627// Warn when using the wrong abs() function.
8628void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00008629 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008630 if (Call->getNumArgs() != 1)
8631 return;
8632
8633 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00008634 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00008635 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008636 return;
8637
8638 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8639 QualType ParamType = Call->getArg(0)->getType();
8640
Alp Toker5d96e0a2014-07-11 20:53:51 +00008641 // Unsigned types cannot be negative. Suggest removing the absolute value
8642 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008643 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00008644 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00008645 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008646 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8647 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00008648 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008649 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8650 return;
8651 }
8652
David Majnemer7f77eb92015-11-15 03:04:34 +00008653 // Taking the absolute value of a pointer is very suspicious, they probably
8654 // wanted to index into an array, dereference a pointer, call a function, etc.
8655 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8656 unsigned DiagType = 0;
8657 if (ArgType->isFunctionType())
8658 DiagType = 1;
8659 else if (ArgType->isArrayType())
8660 DiagType = 2;
8661
8662 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8663 return;
8664 }
8665
Richard Trieubeffb832014-04-15 23:47:53 +00008666 // std::abs has overloads which prevent most of the absolute value problems
8667 // from occurring.
8668 if (IsStdAbs)
8669 return;
8670
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008671 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8672 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8673
8674 // The argument and parameter are the same kind. Check if they are the right
8675 // size.
8676 if (ArgValueKind == ParamValueKind) {
8677 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8678 return;
8679
8680 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8681 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8682 << FDecl << ArgType << ParamType;
8683
8684 if (NewAbsKind == 0)
8685 return;
8686
8687 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00008688 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008689 return;
8690 }
8691
8692 // ArgValueKind != ParamValueKind
8693 // The wrong type of absolute value function was used. Attempt to find the
8694 // proper one.
8695 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8696 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8697 if (NewAbsKind == 0)
8698 return;
8699
8700 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8701 << FDecl << ParamValueKind << ArgValueKind;
8702
8703 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00008704 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008705}
8706
Richard Trieu67c00712016-12-05 23:41:46 +00008707//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00008708void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8709 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00008710 if (!Call || !FDecl) return;
8711
8712 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008713 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00008714 if (Call->getExprLoc().isMacroID()) return;
8715
8716 // Only care about the one template argument, two function parameter std::max
8717 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00008718 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00008719 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8720 if (!ArgList) return;
8721 if (ArgList->size() != 1) return;
8722
8723 // Check that template type argument is unsigned integer.
8724 const auto& TA = ArgList->get(0);
8725 if (TA.getKind() != TemplateArgument::Type) return;
8726 QualType ArgType = TA.getAsType();
8727 if (!ArgType->isUnsignedIntegerType()) return;
8728
8729 // See if either argument is a literal zero.
8730 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8731 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8732 if (!MTE) return false;
8733 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8734 if (!Num) return false;
8735 if (Num->getValue() != 0) return false;
8736 return true;
8737 };
8738
8739 const Expr *FirstArg = Call->getArg(0);
8740 const Expr *SecondArg = Call->getArg(1);
8741 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8742 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8743
8744 // Only warn when exactly one argument is zero.
8745 if (IsFirstArgZero == IsSecondArgZero) return;
8746
8747 SourceRange FirstRange = FirstArg->getSourceRange();
8748 SourceRange SecondRange = SecondArg->getSourceRange();
8749
8750 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8751
8752 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8753 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8754
8755 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8756 SourceRange RemovalRange;
8757 if (IsFirstArgZero) {
8758 RemovalRange = SourceRange(FirstRange.getBegin(),
8759 SecondRange.getBegin().getLocWithOffset(-1));
8760 } else {
8761 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8762 SecondRange.getEnd());
8763 }
8764
8765 Diag(Call->getExprLoc(), diag::note_remove_max_call)
8766 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8767 << FixItHint::CreateRemoval(RemovalRange);
8768}
8769
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008770//===--- CHECK: Standard memory functions ---------------------------------===//
8771
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008772/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00008773/// such as memcmp, strncat, etc and warns if it's a comparison.
8774///
8775/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8776static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8777 IdentifierInfo *FnName,
8778 SourceLocation FnLoc,
8779 SourceLocation RParenLoc) {
8780 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8781 if (!Size)
8782 return false;
8783
Richard Smithc70f1d62017-12-14 15:16:18 +00008784 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8785 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00008786 return false;
8787
Nico Weber0e6daef2013-12-26 23:38:39 +00008788 SourceRange SizeRange = Size->getSourceRange();
8789 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8790 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00008791 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008792 << FnName
8793 << FixItHint::CreateInsertion(
8794 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00008795 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00008796 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00008797 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00008798 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8799 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00008800
8801 return true;
8802}
8803
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008804/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00008805/// (e.g., whether it has a vtable).
8806static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8807 bool &IsContained) {
8808 // Look through array types while ignoring qualifiers.
8809 const Type *Ty = T->getBaseElementTypeUnsafe();
8810 IsContained = false;
8811
8812 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8813 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00008814 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00008815 return nullptr;
8816
8817 if (RD->isDynamicClass())
8818 return RD;
8819
8820 // Check all the fields. If any bases were dynamic, the class is dynamic.
8821 // It's impossible for a class to transitively contain itself by value, so
8822 // infinite recursion is impossible.
8823 for (auto *FD : RD->fields()) {
8824 bool SubContained;
8825 if (const CXXRecordDecl *ContainedRD =
8826 getContainedDynamicClass(FD->getType(), SubContained)) {
8827 IsContained = true;
8828 return ContainedRD;
8829 }
8830 }
8831
8832 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00008833}
8834
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008835static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8836 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8837 if (Unary->getKind() == UETT_SizeOf)
8838 return Unary;
8839 return nullptr;
8840}
8841
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008842/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008843/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00008844static const Expr *getSizeOfExprArg(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008845 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8846 if (!SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008847 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Craig Topperc3ec1492014-05-26 06:22:03 +00008848 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008849}
8850
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008851/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00008852static QualType getSizeOfArgType(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008853 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8854 return SizeOf->getTypeOfArgument();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008855 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00008856}
8857
Akira Hatanaka2be04412018-04-17 19:13:41 +00008858namespace {
8859
8860struct SearchNonTrivialToInitializeField
8861 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8862 using Super =
8863 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8864
8865 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8866
8867 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8868 SourceLocation SL) {
8869 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8870 asDerived().visitArray(PDIK, AT, SL);
8871 return;
8872 }
8873
8874 Super::visitWithKind(PDIK, FT, SL);
8875 }
8876
8877 void visitARCStrong(QualType FT, SourceLocation SL) {
8878 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8879 }
8880 void visitARCWeak(QualType FT, SourceLocation SL) {
8881 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8882 }
8883 void visitStruct(QualType FT, SourceLocation SL) {
8884 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8885 visit(FD->getType(), FD->getLocation());
8886 }
8887 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8888 const ArrayType *AT, SourceLocation SL) {
8889 visit(getContext().getBaseElementType(AT), SL);
8890 }
8891 void visitTrivial(QualType FT, SourceLocation SL) {}
8892
8893 static void diag(QualType RT, const Expr *E, Sema &S) {
8894 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8895 }
8896
8897 ASTContext &getContext() { return S.getASTContext(); }
8898
8899 const Expr *E;
8900 Sema &S;
8901};
8902
8903struct SearchNonTrivialToCopyField
8904 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8905 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8906
8907 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8908
8909 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8910 SourceLocation SL) {
8911 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8912 asDerived().visitArray(PCK, AT, SL);
8913 return;
8914 }
8915
8916 Super::visitWithKind(PCK, FT, SL);
8917 }
8918
8919 void visitARCStrong(QualType FT, SourceLocation SL) {
8920 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8921 }
8922 void visitARCWeak(QualType FT, SourceLocation SL) {
8923 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8924 }
8925 void visitStruct(QualType FT, SourceLocation SL) {
8926 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8927 visit(FD->getType(), FD->getLocation());
8928 }
8929 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8930 SourceLocation SL) {
8931 visit(getContext().getBaseElementType(AT), SL);
8932 }
8933 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8934 SourceLocation SL) {}
8935 void visitTrivial(QualType FT, SourceLocation SL) {}
8936 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8937
8938 static void diag(QualType RT, const Expr *E, Sema &S) {
8939 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8940 }
8941
8942 ASTContext &getContext() { return S.getASTContext(); }
8943
8944 const Expr *E;
8945 Sema &S;
8946};
8947
8948}
8949
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008950/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8951static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8952 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8953
8954 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8955 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8956 return false;
8957
8958 return doesExprLikelyComputeSize(BO->getLHS()) ||
8959 doesExprLikelyComputeSize(BO->getRHS());
8960 }
8961
8962 return getAsSizeOfExpr(SizeofExpr) != nullptr;
8963}
8964
8965/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8966///
8967/// \code
8968/// #define MACRO 0
8969/// foo(MACRO);
8970/// foo(0);
8971/// \endcode
8972///
8973/// This should return true for the first call to foo, but not for the second
8974/// (regardless of whether foo is a macro or function).
8975static bool isArgumentExpandedFromMacro(SourceManager &SM,
8976 SourceLocation CallLoc,
8977 SourceLocation ArgLoc) {
8978 if (!CallLoc.isMacroID())
8979 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8980
8981 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8982 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8983}
8984
8985/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8986/// last two arguments transposed.
8987static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8988 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8989 return;
8990
8991 const Expr *SizeArg =
8992 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8993
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00008994 auto isLiteralZero = [](const Expr *E) {
8995 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
8996 };
8997
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008998 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
8999 SourceLocation CallLoc = Call->getRParenLoc();
9000 SourceManager &SM = S.getSourceManager();
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009001 if (isLiteralZero(SizeArg) &&
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009002 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9003
9004 SourceLocation DiagLoc = SizeArg->getExprLoc();
9005
9006 // Some platforms #define bzero to __builtin_memset. See if this is the
9007 // case, and if so, emit a better diagnostic.
9008 if (BId == Builtin::BIbzero ||
9009 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9010 CallLoc, SM, S.getLangOpts()) == "bzero")) {
9011 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9012 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00009013 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009014 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9015 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9016 }
9017 return;
9018 }
9019
9020 // If the second argument to a memset is a sizeof expression and the third
9021 // isn't, this is also likely an error. This should catch
9022 // 'memset(buf, sizeof(buf), 0xff)'.
9023 if (BId == Builtin::BImemset &&
9024 doesExprLikelyComputeSize(Call->getArg(1)) &&
9025 !doesExprLikelyComputeSize(Call->getArg(2))) {
9026 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9027 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9028 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9029 return;
9030 }
9031}
9032
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009033/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009034///
Chandler Carruthac687262011-06-03 06:23:57 +00009035/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009036/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9037/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009038///
9039/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009040void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00009041 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00009042 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00009043 assert(BId != 0);
9044
Ted Kremenekb5fabb22011-04-28 01:38:02 +00009045 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00009046 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009047 unsigned ExpectedNumArgs =
9048 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00009049 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00009050 return;
9051
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009052 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00009053 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00009054 unsigned LenArg =
9055 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00009056 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009057
Nico Weber0e6daef2013-12-26 23:38:39 +00009058 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009059 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00009060 return;
9061
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00009062 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9063 CheckMemaccessSize(*this, BId, Call);
9064
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009065 // We have special checking when the length is a sizeof expression.
9066 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9067 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9068 llvm::FoldingSetNodeID SizeOfArgID;
9069
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00009070 // Although widely used, 'bzero' is not a standard function. Be more strict
9071 // with the argument types before allowing diagnostics and only allow the
9072 // form bzero(ptr, sizeof(...)).
9073 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9074 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9075 return;
9076
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009077 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9078 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00009079 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009080
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009081 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00009082 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009083 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00009084 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00009085
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009086 // Never warn about void type pointers. This can be used to suppress
9087 // false positives.
9088 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00009089 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009090
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009091 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9092 // actually comparing the expressions for equality. Because computing the
9093 // expression IDs can be expensive, we only do this if the diagnostic is
9094 // enabled.
9095 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009096 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9097 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009098 // We only compute IDs for expressions if the warning is enabled, and
9099 // cache the sizeof arg's ID.
9100 if (SizeOfArgID == llvm::FoldingSetNodeID())
9101 SizeOfArg->Profile(SizeOfArgID, Context, true);
9102 llvm::FoldingSetNodeID DestID;
9103 Dest->Profile(DestID, Context, true);
9104 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00009105 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9106 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009107 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00009108 StringRef ReadableName = FnName->getName();
9109
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009110 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00009111 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009112 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00009113 if (!PointeeTy->isIncompleteType() &&
9114 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009115 ActionIdx = 2; // If the pointee's size is sizeof(char),
9116 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00009117
9118 // If the function is defined as a builtin macro, do not show macro
9119 // expansion.
9120 SourceLocation SL = SizeOfArg->getExprLoc();
9121 SourceRange DSR = Dest->getSourceRange();
9122 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009123 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00009124
9125 if (SM.isMacroArgExpansion(SL)) {
9126 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9127 SL = SM.getSpellingLoc(SL);
9128 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9129 SM.getSpellingLoc(DSR.getEnd()));
9130 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9131 SM.getSpellingLoc(SSR.getEnd()));
9132 }
9133
Anna Zaksd08d9152012-05-30 23:14:52 +00009134 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009135 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00009136 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00009137 << PointeeTy
9138 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00009139 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00009140 << SSR);
9141 DiagRuntimeBehavior(SL, SizeOfArg,
9142 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9143 << ActionIdx
9144 << SSR);
9145
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009146 break;
9147 }
9148 }
9149
9150 // Also check for cases where the sizeof argument is the exact same
9151 // type as the memory argument, and where it points to a user-defined
9152 // record type.
9153 if (SizeOfArgTy != QualType()) {
9154 if (PointeeTy->isRecordType() &&
9155 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9156 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9157 PDiag(diag::warn_sizeof_pointer_type_memaccess)
9158 << FnName << SizeOfArgTy << ArgIdx
9159 << PointeeTy << Dest->getSourceRange()
9160 << LenExpr->getSourceRange());
9161 break;
9162 }
Nico Weberc5e73862011-06-14 16:14:58 +00009163 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00009164 } else if (DestTy->isArrayType()) {
9165 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00009166 }
Nico Weberc5e73862011-06-14 16:14:58 +00009167
Nico Weberc44b35e2015-03-21 17:37:46 +00009168 if (PointeeTy == QualType())
9169 continue;
Anna Zaks22122702012-01-17 00:37:07 +00009170
Nico Weberc44b35e2015-03-21 17:37:46 +00009171 // Always complain about dynamic classes.
9172 bool IsContained;
9173 if (const CXXRecordDecl *ContainedRD =
9174 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00009175
Nico Weberc44b35e2015-03-21 17:37:46 +00009176 unsigned OperationType = 0;
9177 // "overwritten" if we're warning about the destination for any call
9178 // but memcmp; otherwise a verb appropriate to the call.
9179 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
9180 if (BId == Builtin::BImemcpy)
9181 OperationType = 1;
9182 else if(BId == Builtin::BImemmove)
9183 OperationType = 2;
9184 else if (BId == Builtin::BImemcmp)
9185 OperationType = 3;
9186 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009187
John McCall31168b02011-06-15 23:02:42 +00009188 DiagRuntimeBehavior(
9189 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00009190 PDiag(diag::warn_dyn_class_memaccess)
9191 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
9192 << FnName << IsContained << ContainedRD << OperationType
9193 << Call->getCallee()->getSourceRange());
9194 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9195 BId != Builtin::BImemset)
9196 DiagRuntimeBehavior(
9197 Dest->getExprLoc(), Dest,
9198 PDiag(diag::warn_arc_object_memaccess)
9199 << ArgIdx << FnName << PointeeTy
9200 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00009201 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9202 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9203 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9204 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9205 PDiag(diag::warn_cstruct_memaccess)
9206 << ArgIdx << FnName << PointeeTy << 0);
9207 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9208 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9209 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9210 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9211 PDiag(diag::warn_cstruct_memaccess)
9212 << ArgIdx << FnName << PointeeTy << 1);
9213 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9214 } else {
9215 continue;
9216 }
9217 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00009218 continue;
9219
9220 DiagRuntimeBehavior(
9221 Dest->getExprLoc(), Dest,
9222 PDiag(diag::note_bad_memaccess_silence)
9223 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9224 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009225 }
9226}
9227
Ted Kremenek6865f772011-08-18 20:55:45 +00009228// A little helper routine: ignore addition and subtraction of integer literals.
9229// This intentionally does not ignore all integer constant expressions because
9230// we don't want to remove sizeof().
9231static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9232 Ex = Ex->IgnoreParenCasts();
9233
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009234 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00009235 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9236 if (!BO || !BO->isAdditiveOp())
9237 break;
9238
9239 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9240 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00009241
Ted Kremenek6865f772011-08-18 20:55:45 +00009242 if (isa<IntegerLiteral>(RHS))
9243 Ex = LHS;
9244 else if (isa<IntegerLiteral>(LHS))
9245 Ex = RHS;
9246 else
9247 break;
9248 }
9249
9250 return Ex;
9251}
9252
Anna Zaks13b08572012-08-08 21:42:23 +00009253static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9254 ASTContext &Context) {
9255 // Only handle constant-sized or VLAs, but not flexible members.
9256 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9257 // Only issue the FIXIT for arrays of size > 1.
9258 if (CAT->getSize().getSExtValue() <= 1)
9259 return false;
9260 } else if (!Ty->isVariableArrayType()) {
9261 return false;
9262 }
9263 return true;
9264}
9265
Ted Kremenek6865f772011-08-18 20:55:45 +00009266// Warn if the user has made the 'size' argument to strlcpy or strlcat
9267// be the size of the source, instead of the destination.
9268void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9269 IdentifierInfo *FnName) {
9270
9271 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00009272 unsigned NumArgs = Call->getNumArgs();
9273 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00009274 return;
9275
9276 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9277 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00009278 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00009279
9280 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009281 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00009282 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009283
Ted Kremenek6865f772011-08-18 20:55:45 +00009284 // Look for 'strlcpy(dst, x, sizeof(x))'
9285 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9286 CompareWithSrc = Ex;
9287 else {
9288 // Look for 'strlcpy(dst, x, strlen(x))'
9289 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00009290 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9291 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00009292 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9293 }
9294 }
9295
9296 if (!CompareWithSrc)
9297 return;
9298
9299 // Determine if the argument to sizeof/strlen is equal to the source
9300 // argument. In principle there's all kinds of things you could do
9301 // here, for instance creating an == expression and evaluating it with
9302 // EvaluateAsBooleanCondition, but this uses a more direct technique:
9303 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9304 if (!SrcArgDRE)
9305 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009306
Ted Kremenek6865f772011-08-18 20:55:45 +00009307 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
Fangrui Song6907ce22018-07-30 19:24:48 +00009308 if (!CompareWithSrcDRE ||
Ted Kremenek6865f772011-08-18 20:55:45 +00009309 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9310 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009311
Ted Kremenek6865f772011-08-18 20:55:45 +00009312 const Expr *OriginalSizeArg = Call->getArg(2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009313 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9314 << OriginalSizeArg->getSourceRange() << FnName;
Fangrui Song6907ce22018-07-30 19:24:48 +00009315
Ted Kremenek6865f772011-08-18 20:55:45 +00009316 // Output a FIXIT hint if the destination is an array (rather than a
9317 // pointer to an array). This could be enhanced to handle some
9318 // pointers if we know the actual size, like if DstArg is 'array+2'
9319 // we could say 'sizeof(array)-2'.
9320 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00009321 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00009322 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009323
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009324 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009325 llvm::raw_svector_ostream OS(sizeString);
9326 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009327 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00009328 OS << ")";
Fangrui Song6907ce22018-07-30 19:24:48 +00009329
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009330 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9331 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9332 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00009333}
9334
Anna Zaks314cd092012-02-01 19:08:57 +00009335/// Check if two expressions refer to the same declaration.
9336static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9337 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9338 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9339 return D1->getDecl() == D2->getDecl();
9340 return false;
9341}
9342
9343static const Expr *getStrlenExprArg(const Expr *E) {
9344 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9345 const FunctionDecl *FD = CE->getDirectCallee();
9346 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00009347 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009348 return CE->getArg(0)->IgnoreParenCasts();
9349 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009350 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009351}
9352
9353// Warn on anti-patterns as the 'size' argument to strncat.
9354// The correct size argument should look like following:
9355// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9356void Sema::CheckStrncatArguments(const CallExpr *CE,
9357 IdentifierInfo *FnName) {
9358 // Don't crash if the user has the wrong number of arguments.
9359 if (CE->getNumArgs() < 3)
9360 return;
9361 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9362 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9363 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9364
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009365 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
Nico Weber0e6daef2013-12-26 23:38:39 +00009366 CE->getRParenLoc()))
9367 return;
9368
Anna Zaks314cd092012-02-01 19:08:57 +00009369 // Identify common expressions, which are wrongly used as the size argument
9370 // to strncat and may lead to buffer overflows.
9371 unsigned PatternType = 0;
9372 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9373 // - sizeof(dst)
9374 if (referToTheSameDecl(SizeOfArg, DstArg))
9375 PatternType = 1;
9376 // - sizeof(src)
9377 else if (referToTheSameDecl(SizeOfArg, SrcArg))
9378 PatternType = 2;
9379 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9380 if (BE->getOpcode() == BO_Sub) {
9381 const Expr *L = BE->getLHS()->IgnoreParenCasts();
9382 const Expr *R = BE->getRHS()->IgnoreParenCasts();
9383 // - sizeof(dst) - strlen(dst)
9384 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9385 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9386 PatternType = 1;
9387 // - sizeof(src) - (anything)
9388 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9389 PatternType = 2;
9390 }
9391 }
9392
9393 if (PatternType == 0)
9394 return;
9395
Anna Zaks5069aa32012-02-03 01:27:37 +00009396 // Generate the diagnostic.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009397 SourceLocation SL = LenArg->getBeginLoc();
Anna Zaks5069aa32012-02-03 01:27:37 +00009398 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009399 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00009400
9401 // If the function is defined as a builtin macro, do not show macro expansion.
9402 if (SM.isMacroArgExpansion(SL)) {
9403 SL = SM.getSpellingLoc(SL);
9404 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9405 SM.getSpellingLoc(SR.getEnd()));
9406 }
9407
Anna Zaks13b08572012-08-08 21:42:23 +00009408 // Check if the destination is an array (rather than a pointer to an array).
9409 QualType DstTy = DstArg->getType();
9410 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9411 Context);
9412 if (!isKnownSizeArray) {
9413 if (PatternType == 1)
9414 Diag(SL, diag::warn_strncat_wrong_size) << SR;
9415 else
9416 Diag(SL, diag::warn_strncat_src_size) << SR;
9417 return;
9418 }
9419
Anna Zaks314cd092012-02-01 19:08:57 +00009420 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00009421 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009422 else
Anna Zaks5069aa32012-02-03 01:27:37 +00009423 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009424
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009425 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00009426 llvm::raw_svector_ostream OS(sizeString);
9427 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009428 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009429 OS << ") - ";
9430 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009431 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009432 OS << ") - 1";
9433
Anna Zaks5069aa32012-02-03 01:27:37 +00009434 Diag(SL, diag::note_strncat_wrong_size)
9435 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00009436}
9437
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009438void
9439Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9440 SourceLocation ReturnLoc,
9441 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00009442 const AttrVec *Attrs,
9443 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009444 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00009445 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9446 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00009447 CheckNonNullExpr(*this, RetValExp))
9448 Diag(ReturnLoc, diag::warn_null_ret)
9449 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00009450
9451 // C++11 [basic.stc.dynamic.allocation]p4:
9452 // If an allocation function declared with a non-throwing
9453 // exception-specification fails to allocate storage, it shall return
9454 // a null pointer. Any other allocation function that fails to allocate
9455 // storage shall indicate failure only by throwing an exception [...]
9456 if (FD) {
9457 OverloadedOperatorKind Op = FD->getOverloadedOperator();
9458 if (Op == OO_New || Op == OO_Array_New) {
9459 const FunctionProtoType *Proto
9460 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00009461 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00009462 CheckNonNullExpr(*this, RetValExp))
9463 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9464 << FD << getLangOpts().CPlusPlus11;
9465 }
9466 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009467}
9468
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009469//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9470
9471/// Check for comparisons of floating point operands using != and ==.
9472/// Issue a warning if these are no self-comparisons, as they are not likely
9473/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00009474void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00009475 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9476 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009477
9478 // Special case: check for x == x (which is OK).
9479 // Do not emit warnings for such cases.
9480 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9481 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9482 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00009483 return;
Mike Stump11289f42009-09-09 15:08:12 +00009484
Ted Kremenekeda40e22007-11-29 00:59:04 +00009485 // Special case: check for comparisons against literals that can be exactly
9486 // represented by APFloat. In such cases, do not emit a warning. This
9487 // is a heuristic: often comparison against such literals are used to
9488 // detect if a value in a variable has not changed. This clearly can
9489 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00009490 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9491 if (FLL->isExact())
9492 return;
9493 } else
9494 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9495 if (FLR->isExact())
9496 return;
Mike Stump11289f42009-09-09 15:08:12 +00009497
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009498 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00009499 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00009500 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00009501 return;
Mike Stump11289f42009-09-09 15:08:12 +00009502
David Blaikie1f4ff152012-07-16 20:47:22 +00009503 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00009504 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00009505 return;
Mike Stump11289f42009-09-09 15:08:12 +00009506
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009507 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00009508 Diag(Loc, diag::warn_floatingpoint_eq)
9509 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009510}
John McCallca01b222010-01-04 23:21:16 +00009511
John McCall70aa5392010-01-06 05:24:50 +00009512//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9513//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00009514
John McCall70aa5392010-01-06 05:24:50 +00009515namespace {
John McCallca01b222010-01-04 23:21:16 +00009516
John McCall70aa5392010-01-06 05:24:50 +00009517/// Structure recording the 'active' range of an integer-valued
9518/// expression.
9519struct IntRange {
9520 /// The number of bits active in the int.
9521 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00009522
John McCall70aa5392010-01-06 05:24:50 +00009523 /// True if the int is known not to have negative values.
9524 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00009525
John McCall70aa5392010-01-06 05:24:50 +00009526 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009527 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00009528
John McCall817d4af2010-11-10 23:38:19 +00009529 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00009530 static IntRange forBoolType() {
9531 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00009532 }
9533
John McCall817d4af2010-11-10 23:38:19 +00009534 /// Returns the range of an opaque value of the given integral type.
9535 static IntRange forValueOfType(ASTContext &C, QualType T) {
9536 return forValueOfCanonicalType(C,
9537 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00009538 }
9539
John McCall817d4af2010-11-10 23:38:19 +00009540 /// Returns the range of an opaque value of a canonical integral type.
9541 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00009542 assert(T->isCanonicalUnqualified());
9543
9544 if (const VectorType *VT = dyn_cast<VectorType>(T))
9545 T = VT->getElementType().getTypePtr();
9546 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9547 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00009548 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9549 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00009550
Roman Lebedevca1aaac2017-10-21 16:44:03 +00009551 if (!C.getLangOpts().CPlusPlus) {
9552 // For enum types in C code, use the underlying datatype.
9553 if (const EnumType *ET = dyn_cast<EnumType>(T))
9554 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9555 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9556 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00009557 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00009558 // In C++11, enums can have a fixed underlying type. Use this type to
9559 // compute the range.
9560 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00009561 return IntRange(C.getIntWidth(QualType(T, 0)),
9562 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00009563 }
John McCall18a2c2c2010-11-09 22:22:12 +00009564
David Majnemer6a426652013-06-07 22:07:20 +00009565 unsigned NumPositive = Enum->getNumPositiveBits();
9566 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00009567
David Majnemer6a426652013-06-07 22:07:20 +00009568 if (NumNegative == 0)
9569 return IntRange(NumPositive, true/*NonNegative*/);
9570 else
9571 return IntRange(std::max(NumPositive + 1, NumNegative),
9572 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00009573 }
John McCall70aa5392010-01-06 05:24:50 +00009574
9575 const BuiltinType *BT = cast<BuiltinType>(T);
9576 assert(BT->isInteger());
9577
9578 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9579 }
9580
John McCall817d4af2010-11-10 23:38:19 +00009581 /// Returns the "target" range of a canonical integral type, i.e.
9582 /// the range of values expressible in the type.
9583 ///
9584 /// This matches forValueOfCanonicalType except that enums have the
9585 /// full range of their type, not the range of their enumerators.
9586 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9587 assert(T->isCanonicalUnqualified());
9588
9589 if (const VectorType *VT = dyn_cast<VectorType>(T))
9590 T = VT->getElementType().getTypePtr();
9591 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9592 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00009593 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9594 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00009595 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00009596 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00009597
9598 const BuiltinType *BT = cast<BuiltinType>(T);
9599 assert(BT->isInteger());
9600
9601 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9602 }
9603
9604 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00009605 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00009606 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00009607 L.NonNegative && R.NonNegative);
9608 }
9609
John McCall817d4af2010-11-10 23:38:19 +00009610 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00009611 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00009612 return IntRange(std::min(L.Width, R.Width),
9613 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00009614 }
9615};
9616
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009617} // namespace
9618
9619static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9620 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009621 if (value.isSigned() && value.isNegative())
9622 return IntRange(value.getMinSignedBits(), false);
9623
9624 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00009625 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00009626
9627 // isNonNegative() just checks the sign bit without considering
9628 // signedness.
9629 return IntRange(value.getActiveBits(), true);
9630}
9631
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009632static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9633 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009634 if (result.isInt())
9635 return GetValueRange(C, result.getInt(), MaxWidth);
9636
9637 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00009638 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9639 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9640 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9641 R = IntRange::join(R, El);
9642 }
John McCall70aa5392010-01-06 05:24:50 +00009643 return R;
9644 }
9645
9646 if (result.isComplexInt()) {
9647 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9648 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9649 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00009650 }
9651
9652 // This can happen with lossless casts to intptr_t of "based" lvalues.
9653 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00009654 // FIXME: The only reason we need to pass the type in here is to get
9655 // the sign right on this one case. It would be nice if APValue
9656 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009657 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00009658 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00009659}
John McCall70aa5392010-01-06 05:24:50 +00009660
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009661static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009662 QualType Ty = E->getType();
9663 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9664 Ty = AtomicRHS->getValueType();
9665 return Ty;
9666}
9667
John McCall70aa5392010-01-06 05:24:50 +00009668/// Pseudo-evaluate the given integer expression, estimating the
9669/// range of values it might take.
9670///
9671/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009672static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009673 E = E->IgnoreParens();
9674
9675 // Try a full evaluation first.
9676 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009677 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00009678 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00009679
9680 // I think we only want to look through implicit casts here; if the
9681 // user has an explicit widening cast, we should treat the value as
9682 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009683 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00009684 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00009685 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9686
Eli Friedmane6d33952013-07-08 20:20:06 +00009687 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00009688
George Burgess IVdf1ed002016-01-13 01:52:39 +00009689 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9690 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00009691
John McCall70aa5392010-01-06 05:24:50 +00009692 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00009693 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00009694 return OutputTypeRange;
9695
9696 IntRange SubRange
9697 = GetExprRange(C, CE->getSubExpr(),
9698 std::min(MaxWidth, OutputTypeRange.Width));
9699
9700 // Bail out if the subexpr's range is as wide as the cast type.
9701 if (SubRange.Width >= OutputTypeRange.Width)
9702 return OutputTypeRange;
9703
9704 // Otherwise, we take the smaller width, and we're non-negative if
9705 // either the output type or the subexpr is.
9706 return IntRange(SubRange.Width,
9707 SubRange.NonNegative || OutputTypeRange.NonNegative);
9708 }
9709
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009710 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009711 // If we can fold the condition, just take that operand.
9712 bool CondResult;
9713 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9714 return GetExprRange(C, CondResult ? CO->getTrueExpr()
9715 : CO->getFalseExpr(),
9716 MaxWidth);
9717
9718 // Otherwise, conservatively merge.
9719 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9720 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9721 return IntRange::join(L, R);
9722 }
9723
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009724 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009725 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00009726 case BO_Cmp:
9727 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00009728
9729 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00009730 case BO_LAnd:
9731 case BO_LOr:
9732 case BO_LT:
9733 case BO_GT:
9734 case BO_LE:
9735 case BO_GE:
9736 case BO_EQ:
9737 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00009738 return IntRange::forBoolType();
9739
John McCallc3688382011-07-13 06:35:24 +00009740 // The type of the assignments is the type of the LHS, so the RHS
9741 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00009742 case BO_MulAssign:
9743 case BO_DivAssign:
9744 case BO_RemAssign:
9745 case BO_AddAssign:
9746 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00009747 case BO_XorAssign:
9748 case BO_OrAssign:
9749 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00009750 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00009751
John McCallc3688382011-07-13 06:35:24 +00009752 // Simple assignments just pass through the RHS, which will have
9753 // been coerced to the LHS type.
9754 case BO_Assign:
9755 // TODO: bitfields?
9756 return GetExprRange(C, BO->getRHS(), MaxWidth);
9757
John McCall70aa5392010-01-06 05:24:50 +00009758 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009759 case BO_PtrMemD:
9760 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00009761 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009762
John McCall2ce81ad2010-01-06 22:07:33 +00009763 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00009764 case BO_And:
9765 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00009766 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9767 GetExprRange(C, BO->getRHS(), MaxWidth));
9768
John McCall70aa5392010-01-06 05:24:50 +00009769 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00009770 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00009771 // ...except that we want to treat '1 << (blah)' as logically
9772 // positive. It's an important idiom.
9773 if (IntegerLiteral *I
9774 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9775 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009776 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00009777 return IntRange(R.Width, /*NonNegative*/ true);
9778 }
9779 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009780 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00009781
John McCalle3027922010-08-25 11:45:40 +00009782 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00009783 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009784
John McCall2ce81ad2010-01-06 22:07:33 +00009785 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00009786 case BO_Shr:
9787 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00009788 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9789
9790 // If the shift amount is a positive constant, drop the width by
9791 // that much.
9792 llvm::APSInt shift;
9793 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9794 shift.isNonNegative()) {
9795 unsigned zext = shift.getZExtValue();
9796 if (zext >= L.Width)
9797 L.Width = (L.NonNegative ? 0 : 1);
9798 else
9799 L.Width -= zext;
9800 }
9801
9802 return L;
9803 }
9804
9805 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009806 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009807 return GetExprRange(C, BO->getRHS(), MaxWidth);
9808
John McCall2ce81ad2010-01-06 22:07:33 +00009809 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009810 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009811 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009812 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009813 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009814
John McCall51431812011-07-14 22:39:48 +00009815 // The width of a division result is mostly determined by the size
9816 // of the LHS.
9817 case BO_Div: {
9818 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009819 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009820 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9821
9822 // If the divisor is constant, use that.
9823 llvm::APSInt divisor;
9824 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9825 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9826 if (log2 >= L.Width)
9827 L.Width = (L.NonNegative ? 0 : 1);
9828 else
9829 L.Width = std::min(L.Width - log2, MaxWidth);
9830 return L;
9831 }
9832
9833 // Otherwise, just use the LHS's width.
9834 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9835 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9836 }
9837
9838 // The result of a remainder can't be larger than the result of
9839 // either side.
9840 case BO_Rem: {
9841 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009842 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009843 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9844 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9845
9846 IntRange meet = IntRange::meet(L, R);
9847 meet.Width = std::min(meet.Width, MaxWidth);
9848 return meet;
9849 }
9850
9851 // The default behavior is okay for these.
9852 case BO_Mul:
9853 case BO_Add:
9854 case BO_Xor:
9855 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009856 break;
9857 }
9858
John McCall51431812011-07-14 22:39:48 +00009859 // The default case is to treat the operation as if it were closed
9860 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009861 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9862 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9863 return IntRange::join(L, R);
9864 }
9865
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009866 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009867 switch (UO->getOpcode()) {
9868 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009869 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009870 return IntRange::forBoolType();
9871
9872 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009873 case UO_Deref:
9874 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009875 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009876
9877 default:
9878 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9879 }
9880 }
9881
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009882 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009883 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9884
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009885 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009886 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009887 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009888
Eli Friedmane6d33952013-07-08 20:20:06 +00009889 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009890}
John McCall263a48b2010-01-04 23:31:57 +00009891
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009892static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009893 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009894}
9895
John McCall263a48b2010-01-04 23:31:57 +00009896/// Checks whether the given value, which currently has the given
9897/// source semantics, has the same value when coerced through the
9898/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009899static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9900 const llvm::fltSemantics &Src,
9901 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009902 llvm::APFloat truncated = value;
9903
9904 bool ignored;
9905 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9906 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9907
9908 return truncated.bitwiseIsEqual(value);
9909}
9910
9911/// Checks whether the given value, which currently has the given
9912/// source semantics, has the same value when coerced through the
9913/// target semantics.
9914///
9915/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009916static bool IsSameFloatAfterCast(const APValue &value,
9917 const llvm::fltSemantics &Src,
9918 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009919 if (value.isFloat())
9920 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9921
9922 if (value.isVector()) {
9923 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9924 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9925 return false;
9926 return true;
9927 }
9928
9929 assert(value.isComplexFloat());
9930 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9931 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9932}
9933
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009934static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009935
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009936static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009937 // Suppress cases where we are comparing against an enum constant.
9938 if (const DeclRefExpr *DR =
9939 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9940 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009941 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009942
9943 // Suppress cases where the '0' value is expanded from a macro.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009944 if (E->getBeginLoc().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009945 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009946
Roman Lebedev6de129e2017-10-15 20:13:17 +00009947 return false;
9948}
9949
Richard Smith692f66ab2017-12-06 19:23:19 +00009950static bool isKnownToHaveUnsignedValue(Expr *E) {
9951 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009952 (!E->getType()->isSignedIntegerType() ||
9953 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9954}
9955
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009956namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009957/// The promoted range of values of a type. In general this has the
9958/// following structure:
9959///
9960/// |-----------| . . . |-----------|
9961/// ^ ^ ^ ^
9962/// Min HoleMin HoleMax Max
9963///
9964/// ... where there is only a hole if a signed type is promoted to unsigned
9965/// (in which case Min and Max are the smallest and largest representable
9966/// values).
9967struct PromotedRange {
9968 // Min, or HoleMax if there is a hole.
9969 llvm::APSInt PromotedMin;
9970 // Max, or HoleMin if there is a hole.
9971 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009972
Richard Smitha5370fb2017-12-08 22:57:11 +00009973 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9974 if (R.Width == 0)
9975 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9976 else if (R.Width >= BitWidth && !Unsigned) {
9977 // Promotion made the type *narrower*. This happens when promoting
9978 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9979 // Treat all values of 'signed int' as being in range for now.
9980 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9981 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9982 } else {
9983 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9984 .extOrTrunc(BitWidth);
9985 PromotedMin.setIsUnsigned(Unsigned);
9986
9987 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9988 .extOrTrunc(BitWidth);
9989 PromotedMax.setIsUnsigned(Unsigned);
9990 }
9991 }
9992
9993 // Determine whether this range is contiguous (has no hole).
9994 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9995
9996 // Where a constant value is within the range.
9997 enum ComparisonResult {
9998 LT = 0x1,
9999 LE = 0x2,
10000 GT = 0x4,
10001 GE = 0x8,
10002 EQ = 0x10,
10003 NE = 0x20,
10004 InRangeFlag = 0x40,
10005
10006 Less = LE | LT | NE,
10007 Min = LE | InRangeFlag,
10008 InRange = InRangeFlag,
10009 Max = GE | InRangeFlag,
10010 Greater = GE | GT | NE,
10011
10012 OnlyValue = LE | GE | EQ | InRangeFlag,
10013 InHole = NE
10014 };
10015
10016 ComparisonResult compare(const llvm::APSInt &Value) const {
10017 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10018 Value.isUnsigned() == PromotedMin.isUnsigned());
10019 if (!isContiguous()) {
10020 assert(Value.isUnsigned() && "discontiguous range for signed compare");
10021 if (Value.isMinValue()) return Min;
10022 if (Value.isMaxValue()) return Max;
10023 if (Value >= PromotedMin) return InRange;
10024 if (Value <= PromotedMax) return InRange;
10025 return InHole;
10026 }
10027
10028 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10029 case -1: return Less;
10030 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10031 case 1:
10032 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10033 case -1: return InRange;
10034 case 0: return Max;
10035 case 1: return Greater;
10036 }
10037 }
10038
10039 llvm_unreachable("impossible compare result");
10040 }
10041
Richard Smithc70f1d62017-12-14 15:16:18 +000010042 static llvm::Optional<StringRef>
10043 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10044 if (Op == BO_Cmp) {
10045 ComparisonResult LTFlag = LT, GTFlag = GT;
10046 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10047
10048 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10049 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10050 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10051 return llvm::None;
10052 }
10053
Richard Smitha5370fb2017-12-08 22:57:11 +000010054 ComparisonResult TrueFlag, FalseFlag;
10055 if (Op == BO_EQ) {
10056 TrueFlag = EQ;
10057 FalseFlag = NE;
10058 } else if (Op == BO_NE) {
10059 TrueFlag = NE;
10060 FalseFlag = EQ;
10061 } else {
10062 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10063 TrueFlag = LT;
10064 FalseFlag = GE;
10065 } else {
10066 TrueFlag = GT;
10067 FalseFlag = LE;
10068 }
10069 if (Op == BO_GE || Op == BO_LE)
10070 std::swap(TrueFlag, FalseFlag);
10071 }
10072 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +000010073 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +000010074 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +000010075 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +000010076 return llvm::None;
10077 }
Roman Lebedev6de129e2017-10-15 20:13:17 +000010078};
John McCallcc7e5bf2010-05-06 08:58:33 +000010079}
10080
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010081static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +000010082 // Strip off implicit integral promotions.
10083 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +000010084 if (ICE->getCastKind() != CK_IntegralCast &&
10085 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +000010086 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +000010087 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +000010088 }
10089
10090 return E->getType()->isEnumeralType();
10091}
10092
Richard Smith692f66ab2017-12-06 19:23:19 +000010093static int classifyConstantValue(Expr *Constant) {
10094 // The values of this enumeration are used in the diagnostics
10095 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10096 enum ConstantValueKind {
10097 Miscellaneous = 0,
10098 LiteralTrue,
10099 LiteralFalse
10100 };
10101 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10102 return BL->getValue() ? ConstantValueKind::LiteralTrue
10103 : ConstantValueKind::LiteralFalse;
10104 return ConstantValueKind::Miscellaneous;
10105}
10106
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010107static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10108 Expr *Constant, Expr *Other,
10109 const llvm::APSInt &Value,
10110 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010111 if (S.inTemplateInstantiation())
10112 return false;
10113
Richard Smitha5370fb2017-12-08 22:57:11 +000010114 Expr *OriginalOther = Other;
10115
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010116 Constant = Constant->IgnoreParenImpCasts();
10117 Other = Other->IgnoreParenImpCasts();
10118
Richard Smitha5370fb2017-12-08 22:57:11 +000010119 // Suppress warnings on tautological comparisons between values of the same
10120 // enumeration type. There are only two ways we could warn on this:
10121 // - If the constant is outside the range of representable values of
10122 // the enumeration. In such a case, we should warn about the cast
10123 // to enumeration type, not about the comparison.
10124 // - If the constant is the maximum / minimum in-range value. For an
10125 // enumeratin type, such comparisons can be meaningful and useful.
10126 if (Constant->getType()->isEnumeralType() &&
10127 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10128 return false;
10129
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010130 // TODO: Investigate using GetExprRange() to get tighter bounds
10131 // on the bit ranges.
10132 QualType OtherT = Other->getType();
10133 if (const auto *AT = OtherT->getAs<AtomicType>())
10134 OtherT = AT->getValueType();
10135 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10136
10137 // Whether we're treating Other as being a bool because of the form of
10138 // expression despite it having another type (typically 'int' in C).
10139 bool OtherIsBooleanDespiteType =
10140 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10141 if (OtherIsBooleanDespiteType)
10142 OtherRange = IntRange::forBoolType();
10143
Richard Smitha5370fb2017-12-08 22:57:11 +000010144 // Determine the promoted range of the other type and see if a comparison of
10145 // the constant against that range is tautological.
10146 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10147 Value.isUnsigned());
10148 auto Cmp = OtherPromotedRange.compare(Value);
10149 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10150 if (!Result)
10151 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +000010152
Richard Smitha5370fb2017-12-08 22:57:11 +000010153 // Suppress the diagnostic for an in-range comparison if the constant comes
10154 // from a macro or enumerator. We don't want to diagnose
10155 //
10156 // some_long_value <= INT_MAX
10157 //
10158 // when sizeof(int) == sizeof(long).
10159 bool InRange = Cmp & PromotedRange::InRangeFlag;
10160 if (InRange && IsEnumConstOrFromMacro(S, Constant))
10161 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010162
10163 // If this is a comparison to an enum constant, include that
10164 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +000010165 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010166 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10167 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10168
Richard Smitha5370fb2017-12-08 22:57:11 +000010169 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010170 SmallString<64> PrettySourceValue;
10171 llvm::raw_svector_ostream OS(PrettySourceValue);
10172 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +000010173 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010174 else
10175 OS << Value;
10176
Richard Smitha5370fb2017-12-08 22:57:11 +000010177 // FIXME: We use a somewhat different formatting for the in-range cases and
10178 // cases involving boolean values for historical reasons. We should pick a
10179 // consistent way of presenting these diagnostics.
10180 if (!InRange || Other->isKnownToHaveBooleanValue()) {
10181 S.DiagRuntimeBehavior(
10182 E->getOperatorLoc(), E,
10183 S.PDiag(!InRange ? diag::warn_out_of_range_compare
10184 : diag::warn_tautological_bool_compare)
10185 << OS.str() << classifyConstantValue(Constant)
10186 << OtherT << OtherIsBooleanDespiteType << *Result
10187 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10188 } else {
10189 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10190 ? (HasEnumType(OriginalOther)
10191 ? diag::warn_unsigned_enum_always_true_comparison
10192 : diag::warn_unsigned_always_true_comparison)
10193 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +000010194
Richard Smitha5370fb2017-12-08 22:57:11 +000010195 S.Diag(E->getOperatorLoc(), Diag)
10196 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10197 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10198 }
10199
10200 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010201}
10202
John McCallcc7e5bf2010-05-06 08:58:33 +000010203/// Analyze the operands of the given comparison. Implements the
10204/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010205static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +000010206 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10207 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010208}
John McCall263a48b2010-01-04 23:31:57 +000010209
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010210/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +000010211///
Richard Trieu82402a02011-09-15 21:56:47 +000010212/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010213static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010214 // The type the comparison is being performed in.
10215 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +000010216
10217 // Only analyze comparison operators where both sides have been converted to
10218 // the same type.
10219 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10220 return AnalyzeImpConvsInComparison(S, E);
10221
10222 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +000010223 if (E->isValueDependent())
10224 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010225
Roman Lebedev6de129e2017-10-15 20:13:17 +000010226 Expr *LHS = E->getLHS();
10227 Expr *RHS = E->getRHS();
10228
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010229 if (T->isIntegralType(S.Context)) {
10230 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010231 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010232
Roman Lebedev6de129e2017-10-15 20:13:17 +000010233 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10234 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +000010235
Roman Lebedev6de129e2017-10-15 20:13:17 +000010236 // We don't care about expressions whose result is a constant.
10237 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10238 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +000010239
Roman Lebedev6de129e2017-10-15 20:13:17 +000010240 // We only care about expressions where just one side is literal
10241 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10242 // Is the constant on the RHS or LHS?
10243 const bool RhsConstant = IsRHSIntegralLiteral;
10244 Expr *Const = RhsConstant ? RHS : LHS;
10245 Expr *Other = RhsConstant ? LHS : RHS;
10246 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10247
10248 // Check whether an integer constant comparison results in a value
10249 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +000010250 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10251 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010252 }
10253 }
10254
10255 if (!T->hasUnsignedIntegerRepresentation()) {
10256 // We don't do anything special if this isn't an unsigned integral
10257 // comparison: we're only interested in integral comparisons, and
10258 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +000010259 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010260 }
10261
10262 LHS = LHS->IgnoreParenImpCasts();
10263 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010264
Alex Lorenzb57409f2018-02-07 20:45:39 +000010265 if (!S.getLangOpts().CPlusPlus) {
10266 // Avoid warning about comparison of integers with different signs when
10267 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10268 // the type of `E`.
10269 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10270 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10271 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10272 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10273 }
10274
John McCallcc7e5bf2010-05-06 08:58:33 +000010275 // Check to see if one of the (unmodified) operands is of different
10276 // signedness.
10277 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +000010278 if (LHS->getType()->hasSignedIntegerRepresentation()) {
10279 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +000010280 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +000010281 signedOperand = LHS;
10282 unsignedOperand = RHS;
10283 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10284 signedOperand = RHS;
10285 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +000010286 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +000010287 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010288 }
10289
John McCallcc7e5bf2010-05-06 08:58:33 +000010290 // Otherwise, calculate the effective range of the signed operand.
10291 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +000010292
John McCallcc7e5bf2010-05-06 08:58:33 +000010293 // Go ahead and analyze implicit conversions in the operands. Note
10294 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +000010295 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10296 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +000010297
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010298 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +000010299 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010300 return;
John McCallca01b222010-01-04 23:21:16 +000010301
10302 // For (in)equality comparisons, if the unsigned operand is a
10303 // constant which cannot collide with a overflowed signed operand,
10304 // then reinterpreting the signed operand as unsigned will not
10305 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +000010306 if (E->isEqualityOp()) {
10307 unsigned comparisonWidth = S.Context.getIntWidth(T);
10308 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +000010309
John McCallcc7e5bf2010-05-06 08:58:33 +000010310 // We should never be unable to prove that the unsigned operand is
10311 // non-negative.
10312 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10313
10314 if (unsignedRange.Width < comparisonWidth)
10315 return;
10316 }
10317
Douglas Gregorbfb4a212012-05-01 01:53:49 +000010318 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10319 S.PDiag(diag::warn_mixed_sign_comparison)
10320 << LHS->getType() << RHS->getType()
10321 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +000010322}
10323
John McCall1f425642010-11-11 03:21:53 +000010324/// Analyzes an attempt to assign the given value to a bitfield.
10325///
10326/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010327static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10328 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +000010329 assert(Bitfield->isBitField());
10330 if (Bitfield->isInvalidDecl())
10331 return false;
10332
John McCalldeebbcf2010-11-11 05:33:51 +000010333 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +000010334 QualType BitfieldType = Bitfield->getType();
10335 if (BitfieldType->isBooleanType())
10336 return false;
10337
10338 if (BitfieldType->isEnumeralType()) {
10339 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10340 // If the underlying enum type was not explicitly specified as an unsigned
10341 // type and the enum contain only positive values, MSVC++ will cause an
10342 // inconsistency by storing this as a signed type.
10343 if (S.getLangOpts().CPlusPlus11 &&
10344 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10345 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10346 BitfieldEnumDecl->getNumNegativeBits() == 0) {
10347 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10348 << BitfieldEnumDecl->getNameAsString();
10349 }
10350 }
10351
John McCalldeebbcf2010-11-11 05:33:51 +000010352 if (Bitfield->getType()->isBooleanType())
10353 return false;
10354
Douglas Gregor789adec2011-02-04 13:09:01 +000010355 // Ignore value- or type-dependent expressions.
10356 if (Bitfield->getBitWidth()->isValueDependent() ||
10357 Bitfield->getBitWidth()->isTypeDependent() ||
10358 Init->isValueDependent() ||
10359 Init->isTypeDependent())
10360 return false;
10361
John McCall1f425642010-11-11 03:21:53 +000010362 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +000010363 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +000010364
Fangrui Song407659a2018-11-30 23:41:18 +000010365 Expr::EvalResult Result;
10366 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
Reid Kleckner329f24d2017-03-14 18:01:02 +000010367 Expr::SE_AllowSideEffects)) {
10368 // The RHS is not constant. If the RHS has an enum type, make sure the
10369 // bitfield is wide enough to hold all the values of the enum without
10370 // truncation.
10371 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10372 EnumDecl *ED = EnumTy->getDecl();
10373 bool SignedBitfield = BitfieldType->isSignedIntegerType();
10374
10375 // Enum types are implicitly signed on Windows, so check if there are any
10376 // negative enumerators to see if the enum was intended to be signed or
10377 // not.
10378 bool SignedEnum = ED->getNumNegativeBits() > 0;
10379
10380 // Check for surprising sign changes when assigning enum values to a
10381 // bitfield of different signedness. If the bitfield is signed and we
10382 // have exactly the right number of bits to store this unsigned enum,
10383 // suggest changing the enum to an unsigned type. This typically happens
10384 // on Windows where unfixed enums always use an underlying type of 'int'.
10385 unsigned DiagID = 0;
10386 if (SignedEnum && !SignedBitfield) {
10387 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10388 } else if (SignedBitfield && !SignedEnum &&
10389 ED->getNumPositiveBits() == FieldWidth) {
10390 DiagID = diag::warn_signed_bitfield_enum_conversion;
10391 }
10392
10393 if (DiagID) {
10394 S.Diag(InitLoc, DiagID) << Bitfield << ED;
10395 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10396 SourceRange TypeRange =
10397 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10398 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10399 << SignedEnum << TypeRange;
10400 }
10401
10402 // Compute the required bitwidth. If the enum has negative values, we need
10403 // one more bit than the normal number of positive bits to represent the
10404 // sign bit.
10405 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10406 ED->getNumNegativeBits())
10407 : ED->getNumPositiveBits();
10408
10409 // Check the bitwidth.
10410 if (BitsNeeded > FieldWidth) {
10411 Expr *WidthExpr = Bitfield->getBitWidth();
10412 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10413 << Bitfield << ED;
10414 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10415 << BitsNeeded << ED << WidthExpr->getSourceRange();
10416 }
10417 }
10418
John McCall1f425642010-11-11 03:21:53 +000010419 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +000010420 }
John McCall1f425642010-11-11 03:21:53 +000010421
Fangrui Song407659a2018-11-30 23:41:18 +000010422 llvm::APSInt Value = Result.Val.getInt();
10423
John McCall1f425642010-11-11 03:21:53 +000010424 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +000010425
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010426 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +000010427 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010428 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10429 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +000010430
John McCall1f425642010-11-11 03:21:53 +000010431 if (OriginalWidth <= FieldWidth)
10432 return false;
10433
Eli Friedmanc267a322012-01-26 23:11:39 +000010434 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +000010435 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +000010436 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +000010437
Eli Friedmanc267a322012-01-26 23:11:39 +000010438 // Check whether the stored value is equal to the original value.
10439 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +000010440 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +000010441 return false;
10442
Eli Friedmanc267a322012-01-26 23:11:39 +000010443 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +000010444 // therefore don't strictly fit into a signed bitfield of width 1.
10445 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +000010446 return false;
10447
John McCall1f425642010-11-11 03:21:53 +000010448 std::string PrettyValue = Value.toString(10);
10449 std::string PrettyTrunc = TruncatedValue.toString(10);
10450
10451 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10452 << PrettyValue << PrettyTrunc << OriginalInit->getType()
10453 << Init->getSourceRange();
10454
10455 return true;
10456}
10457
John McCalld2a53122010-11-09 23:24:47 +000010458/// Analyze the given simple or compound assignment for warning-worthy
10459/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010460static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +000010461 // Just recurse on the LHS.
10462 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10463
10464 // We want to recurse on the RHS as normal unless we're assigning to
10465 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +000010466 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010467 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +000010468 E->getOperatorLoc())) {
10469 // Recurse, ignoring any implicit conversions on the RHS.
10470 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10471 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +000010472 }
10473 }
10474
10475 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
Richard Smith6822bd72018-10-26 19:26:45 +000010476
JF Bastiene77b48b2018-09-10 20:42:56 +000010477 // Diagnose implicitly sequentially-consistent atomic assignment.
10478 if (E->getLHS()->getType()->isAtomicType())
10479 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
John McCalld2a53122010-11-09 23:24:47 +000010480}
10481
John McCall263a48b2010-01-04 23:31:57 +000010482/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Fangrui Song6907ce22018-07-30 19:24:48 +000010483static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010484 SourceLocation CContext, unsigned diag,
10485 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000010486 if (pruneControlFlow) {
10487 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10488 S.PDiag(diag)
10489 << SourceType << T << E->getSourceRange()
10490 << SourceRange(CContext));
10491 return;
10492 }
Douglas Gregor364f7db2011-03-12 00:14:31 +000010493 S.Diag(E->getExprLoc(), diag)
10494 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10495}
10496
Chandler Carruth7f3654f2011-04-05 06:47:57 +000010497/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010498static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10499 SourceLocation CContext,
10500 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000010501 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +000010502}
10503
Richard Trieube234c32016-04-21 21:04:55 +000010504/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010505static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10506 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +000010507 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +000010508 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +000010509
10510 Expr *InnerE = E->IgnoreParenImpCasts();
10511 // We also want to warn on, e.g., "int i = -1.234"
10512 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10513 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10514 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10515
10516 const bool IsLiteral =
10517 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10518
10519 llvm::APFloat Value(0.0);
10520 bool IsConstant =
10521 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10522 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +000010523 return DiagnoseImpCast(S, E, T, CContext,
10524 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +000010525 }
10526
Chandler Carruth016ef402011-04-10 08:36:24 +000010527 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +000010528
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +000010529 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10530 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +000010531 llvm::APFloat::opStatus Result = Value.convertToInteger(
10532 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10533
10534 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +000010535 if (IsLiteral) return;
10536 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10537 PruneWarnings);
10538 }
10539
Erich Keanea4c48c62018-05-08 21:26:21 +000010540 // Conversion of a floating-point value to a non-bool integer where the
10541 // integral part cannot be represented by the integer type is undefined.
10542 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10543 return DiagnoseImpCast(
10544 S, E, T, CContext,
10545 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +000010546 : diag::warn_impcast_float_to_integer_out_of_range,
10547 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +000010548
Richard Trieube234c32016-04-21 21:04:55 +000010549 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +000010550 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +000010551 // Warn on floating point literal to integer.
10552 DiagID = diag::warn_impcast_literal_float_to_integer;
10553 } else if (IntegerValue == 0) {
10554 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
10555 return DiagnoseImpCast(S, E, T, CContext,
10556 diag::warn_impcast_float_integer, PruneWarnings);
10557 }
10558 // Warn on non-zero to zero conversion.
10559 DiagID = diag::warn_impcast_float_to_integer_zero;
10560 } else {
10561 if (IntegerValue.isUnsigned()) {
10562 if (!IntegerValue.isMaxValue()) {
10563 return DiagnoseImpCast(S, E, T, CContext,
10564 diag::warn_impcast_float_integer, PruneWarnings);
10565 }
10566 } else { // IntegerValue.isSigned()
10567 if (!IntegerValue.isMaxSignedValue() &&
10568 !IntegerValue.isMinSignedValue()) {
10569 return DiagnoseImpCast(S, E, T, CContext,
10570 diag::warn_impcast_float_integer, PruneWarnings);
10571 }
10572 }
10573 // Warn on evaluatable floating point expression to integer conversion.
10574 DiagID = diag::warn_impcast_float_to_integer;
10575 }
Chandler Carruth016ef402011-04-10 08:36:24 +000010576
David Bolvansky3cc2ef82018-11-14 14:27:51 +000010577 // FIXME: Force the precision of the source value down so we don't print
10578 // digits which are usually useless (we don't really care here if we
10579 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
10580 // would automatically print the shortest representation, but it's a bit
10581 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +000010582 SmallString<16> PrettySourceValue;
David Bolvansky3cc2ef82018-11-14 14:27:51 +000010583 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10584 precision = (precision * 59 + 195) / 196;
10585 Value.toString(PrettySourceValue, precision);
Eli Friedman07185912013-08-29 23:44:43 +000010586
David Blaikie9b88cc02012-05-15 17:18:27 +000010587 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +000010588 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +000010589 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +000010590 else
David Blaikie9b88cc02012-05-15 17:18:27 +000010591 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +000010592
Richard Trieube234c32016-04-21 21:04:55 +000010593 if (PruneWarnings) {
10594 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10595 S.PDiag(DiagID)
10596 << E->getType() << T.getUnqualifiedType()
10597 << PrettySourceValue << PrettyTargetValue
10598 << E->getSourceRange() << SourceRange(CContext));
10599 } else {
10600 S.Diag(E->getExprLoc(), DiagID)
10601 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10602 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10603 }
Chandler Carruth016ef402011-04-10 08:36:24 +000010604}
10605
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010606/// Analyze the given compound assignment for the possible losing of
10607/// floating-point precision.
10608static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10609 assert(isa<CompoundAssignOperator>(E) &&
10610 "Must be compound assignment operation");
10611 // Recurse on the LHS and RHS in here
10612 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10613 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10614
JF Bastiene77b48b2018-09-10 20:42:56 +000010615 if (E->getLHS()->getType()->isAtomicType())
10616 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10617
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010618 // Now check the outermost expression
10619 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10620 const auto *RBT = cast<CompoundAssignOperator>(E)
10621 ->getComputationResultType()
10622 ->getAs<BuiltinType>();
10623
10624 // The below checks assume source is floating point.
10625 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10626
10627 // If source is floating point but target is not.
10628 if (!ResultBT->isFloatingPoint())
10629 return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(),
10630 E->getExprLoc());
10631
10632 // If both source and target are floating points.
10633 // Builtin FP kinds are ordered by increasing FP rank.
10634 if (ResultBT->getKind() < RBT->getKind() &&
10635 // We don't want to warn for system macro.
10636 !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10637 // warn about dropping FP rank.
10638 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10639 diag::warn_impcast_float_result_precision);
10640}
10641
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010642static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10643 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +000010644 if (!Range.Width) return "0";
10645
10646 llvm::APSInt ValueInRange = Value;
10647 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +000010648 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +000010649 return ValueInRange.toString(10);
10650}
10651
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010652static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010653 if (!isa<ImplicitCastExpr>(Ex))
10654 return false;
10655
10656 Expr *InnerE = Ex->IgnoreParenImpCasts();
10657 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10658 const Type *Source =
10659 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10660 if (Target->isDependentType())
10661 return false;
10662
10663 const BuiltinType *FloatCandidateBT =
10664 dyn_cast<BuiltinType>(ToBool ? Source : Target);
10665 const Type *BoolCandidateType = ToBool ? Target : Source;
10666
10667 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10668 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10669}
10670
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010671static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10672 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010673 unsigned NumArgs = TheCall->getNumArgs();
10674 for (unsigned i = 0; i < NumArgs; ++i) {
10675 Expr *CurrA = TheCall->getArg(i);
10676 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10677 continue;
10678
10679 bool IsSwapped = ((i > 0) &&
10680 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10681 IsSwapped |= ((i < (NumArgs - 1)) &&
10682 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10683 if (IsSwapped) {
10684 // Warn on this floating-point to bool conversion.
10685 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10686 CurrA->getType(), CC,
10687 diag::warn_impcast_floating_point_to_bool);
10688 }
10689 }
10690}
10691
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010692static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10693 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +000010694 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10695 E->getExprLoc()))
10696 return;
10697
Richard Trieu09d6b802016-01-08 23:35:06 +000010698 // Don't warn on functions which have return type nullptr_t.
10699 if (isa<CallExpr>(E))
10700 return;
10701
Richard Trieu5b993502014-10-15 03:42:06 +000010702 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10703 const Expr::NullPointerConstantKind NullKind =
10704 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10705 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10706 return;
10707
10708 // Return if target type is a safe conversion.
10709 if (T->isAnyPointerType() || T->isBlockPointerType() ||
10710 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10711 return;
10712
10713 SourceLocation Loc = E->getSourceRange().getBegin();
10714
Richard Trieu0a5e1662016-02-13 00:58:53 +000010715 // Venture through the macro stacks to get to the source of macro arguments.
10716 // The new location is a better location than the complete location that was
10717 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +000010718 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10719 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +000010720
Richard Trieu5b993502014-10-15 03:42:06 +000010721 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +000010722 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10723 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10724 Loc, S.SourceMgr, S.getLangOpts());
10725 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +000010726 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +000010727 }
10728
10729 // Only warn if the null and context location are in the same macro expansion.
10730 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10731 return;
10732
10733 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010734 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +000010735 << FixItHint::CreateReplacement(Loc,
10736 S.getFixItZeroLiteralForType(T, Loc));
10737}
10738
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010739static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10740 ObjCArrayLiteral *ArrayLiteral);
10741
10742static void
10743checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10744 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000010745
10746/// Check a single element within a collection literal against the
10747/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010748static void checkObjCCollectionLiteralElement(Sema &S,
10749 QualType TargetElementType,
10750 Expr *Element,
10751 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010752 // Skip a bitcast to 'id' or qualified 'id'.
10753 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10754 if (ICE->getCastKind() == CK_BitCast &&
10755 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10756 Element = ICE->getSubExpr();
10757 }
10758
10759 QualType ElementType = Element->getType();
10760 ExprResult ElementResult(Element);
10761 if (ElementType->getAs<ObjCObjectPointerType>() &&
10762 S.CheckSingleAssignmentConstraints(TargetElementType,
10763 ElementResult,
10764 false, false)
10765 != Sema::Compatible) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010766 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10767 << ElementType << ElementKind << TargetElementType
10768 << Element->getSourceRange();
Douglas Gregor5054cb02015-07-07 03:58:22 +000010769 }
10770
10771 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10772 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10773 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10774 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10775}
10776
10777/// Check an Objective-C array literal being converted to the given
10778/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010779static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10780 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010781 if (!S.NSArrayDecl)
10782 return;
10783
10784 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10785 if (!TargetObjCPtr)
10786 return;
10787
10788 if (TargetObjCPtr->isUnspecialized() ||
10789 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10790 != S.NSArrayDecl->getCanonicalDecl())
10791 return;
10792
10793 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10794 if (TypeArgs.size() != 1)
10795 return;
10796
10797 QualType TargetElementType = TypeArgs[0];
10798 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10799 checkObjCCollectionLiteralElement(S, TargetElementType,
10800 ArrayLiteral->getElement(I),
10801 0);
10802 }
10803}
10804
10805/// Check an Objective-C dictionary literal being converted to the given
10806/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010807static void
10808checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10809 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010810 if (!S.NSDictionaryDecl)
10811 return;
10812
10813 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10814 if (!TargetObjCPtr)
10815 return;
10816
10817 if (TargetObjCPtr->isUnspecialized() ||
10818 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10819 != S.NSDictionaryDecl->getCanonicalDecl())
10820 return;
10821
10822 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10823 if (TypeArgs.size() != 2)
10824 return;
10825
10826 QualType TargetKeyType = TypeArgs[0];
10827 QualType TargetObjectType = TypeArgs[1];
10828 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10829 auto Element = DictionaryLiteral->getKeyValueElement(I);
10830 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10831 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10832 }
10833}
10834
Richard Trieufc404c72016-02-05 23:02:38 +000010835// Helper function to filter out cases for constant width constant conversion.
10836// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010837static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10838 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010839 // If initializing from a constant, and the constant starts with '0',
10840 // then it is a binary, octal, or hexadecimal. Allow these constants
10841 // to fill all the bits, even if there is a sign change.
10842 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10843 const char FirstLiteralCharacter =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010844 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
Richard Trieufc404c72016-02-05 23:02:38 +000010845 if (FirstLiteralCharacter == '0')
10846 return false;
10847 }
10848
10849 // If the CC location points to a '{', and the type is char, then assume
10850 // assume it is an array initialization.
10851 if (CC.isValid() && T->isCharType()) {
10852 const char FirstContextCharacter =
10853 S.getSourceManager().getCharacterData(CC)[0];
10854 if (FirstContextCharacter == '{')
10855 return false;
10856 }
10857
10858 return true;
10859}
10860
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010861static void
10862CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10863 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010864 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010865
John McCallcc7e5bf2010-05-06 08:58:33 +000010866 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10867 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10868 if (Source == Target) return;
10869 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010870
Chandler Carruthc22845a2011-07-26 05:40:03 +000010871 // If the conversion context location is invalid don't complain. We also
10872 // don't want to emit a warning if the issue occurs from the expansion of
10873 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10874 // delay this check as long as possible. Once we detect we are in that
10875 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010876 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010877 return;
10878
JF Bastiene77b48b2018-09-10 20:42:56 +000010879 if (Source->isAtomicType())
10880 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10881
Richard Trieu021baa32011-09-23 20:10:00 +000010882 // Diagnose implicit casts to bool.
10883 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10884 if (isa<StringLiteral>(E))
10885 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010886 // and expressions, for instance, assert(0 && "error here"), are
10887 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010888 return DiagnoseImpCast(S, E, T, CC,
10889 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010890 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10891 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10892 // This covers the literal expressions that evaluate to Objective-C
10893 // objects.
10894 return DiagnoseImpCast(S, E, T, CC,
10895 diag::warn_impcast_objective_c_literal_to_bool);
10896 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010897 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10898 // Warn on pointer to bool conversion that is always true.
10899 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10900 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010901 }
Richard Trieu021baa32011-09-23 20:10:00 +000010902 }
John McCall263a48b2010-01-04 23:31:57 +000010903
Douglas Gregor5054cb02015-07-07 03:58:22 +000010904 // Check implicit casts from Objective-C collection literals to specialized
10905 // collection types, e.g., NSArray<NSString *> *.
10906 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10907 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10908 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10909 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10910
John McCall263a48b2010-01-04 23:31:57 +000010911 // Strip vector types.
10912 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010913 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010914 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010915 return;
John McCallacf0ee52010-10-08 02:01:28 +000010916 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010917 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010918
Chris Lattneree7286f2011-06-14 04:51:15 +000010919 // If the vector cast is cast between two vectors of the same size, it is
10920 // a bitcast, not a conversion.
10921 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10922 return;
John McCall263a48b2010-01-04 23:31:57 +000010923
10924 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10925 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10926 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010927 if (auto VecTy = dyn_cast<VectorType>(Target))
10928 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010929
10930 // Strip complex types.
10931 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010932 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010933 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010934 return;
10935
Tim Northover02416372017-08-08 23:18:05 +000010936 return DiagnoseImpCast(S, E, T, CC,
10937 S.getLangOpts().CPlusPlus
10938 ? diag::err_impcast_complex_scalar
10939 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010940 }
John McCall263a48b2010-01-04 23:31:57 +000010941
10942 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10943 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10944 }
10945
10946 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10947 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10948
10949 // If the source is floating point...
10950 if (SourceBT && SourceBT->isFloatingPoint()) {
10951 // ...and the target is floating point...
10952 if (TargetBT && TargetBT->isFloatingPoint()) {
10953 // ...then warn if we're dropping FP rank.
10954
10955 // Builtin FP kinds are ordered by increasing FP rank.
10956 if (SourceBT->getKind() > TargetBT->getKind()) {
10957 // Don't warn about float constants that are precisely
10958 // representable in the target type.
10959 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010960 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010961 // Value might be a float, a float vector, or a float complex.
10962 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010963 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10964 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010965 return;
10966 }
10967
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010968 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010969 return;
10970
John McCallacf0ee52010-10-08 02:01:28 +000010971 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010972 }
10973 // ... or possibly if we're increasing rank, too
10974 else if (TargetBT->getKind() > SourceBT->getKind()) {
10975 if (S.SourceMgr.isInSystemMacro(CC))
10976 return;
10977
10978 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010979 }
10980 return;
10981 }
10982
Richard Trieube234c32016-04-21 21:04:55 +000010983 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010984 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010985 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010986 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010987
Richard Trieube234c32016-04-21 21:04:55 +000010988 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010989 }
John McCall263a48b2010-01-04 23:31:57 +000010990
Richard Smith54894fd2015-12-30 01:06:52 +000010991 // Detect the case where a call result is converted from floating-point to
10992 // to bool, and the final argument to the call is converted from bool, to
10993 // discover this typo:
10994 //
10995 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10996 //
10997 // FIXME: This is an incredibly special case; is there some more general
10998 // way to detect this class of misplaced-parentheses bug?
10999 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011000 // Check last argument of function call to see if it is an
11001 // implicit cast from a type matching the type the result
11002 // is being cast to.
11003 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000011004 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011005 Expr *LastA = CEx->getArg(NumArgs - 1);
11006 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000011007 if (isa<ImplicitCastExpr>(LastA) &&
11008 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011009 // Warn on this floating-point to bool conversion
11010 DiagnoseImpCast(S, E, T, CC,
11011 diag::warn_impcast_floating_point_to_bool);
11012 }
11013 }
11014 }
John McCall263a48b2010-01-04 23:31:57 +000011015 return;
11016 }
11017
Leonard Chand3f3e162019-01-18 21:04:25 +000011018 if (Source->isFixedPointType()) {
11019 // TODO: Only CK_FixedPointCast is supported now. The other valid casts
11020 // should be accounted for here.
11021 if (Target->isFixedPointType()) {
11022 Expr::EvalResult Result;
11023 if (E->EvaluateAsFixedPoint(Result, S.Context,
11024 Expr::SE_AllowSideEffects)) {
11025 APFixedPoint Value = Result.Val.getFixedPoint();
11026 APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11027 APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11028 if (Value > MaxVal || Value < MinVal) {
11029 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11030 S.PDiag(diag::warn_impcast_fixed_point_range)
11031 << Value.toString() << T
11032 << E->getSourceRange()
11033 << clang::SourceRange(CC));
11034 return;
11035 }
11036 }
11037 }
11038 }
11039
Richard Trieu5b993502014-10-15 03:42:06 +000011040 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000011041
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011042 S.DiscardMisalignedMemberAddress(Target, E);
11043
David Blaikie9366d2b2012-06-19 21:19:06 +000011044 if (!Source->isIntegerType() || !Target->isIntegerType())
11045 return;
11046
David Blaikie7555b6a2012-05-15 16:56:36 +000011047 // TODO: remove this early return once the false positives for constant->bool
11048 // in templates, macros, etc, are reduced or removed.
11049 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11050 return;
11051
John McCallcc7e5bf2010-05-06 08:58:33 +000011052 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000011053 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000011054
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011055 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000011056 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011057 // TODO: this should happen for bitfield stores, too.
Fangrui Song407659a2018-11-30 23:41:18 +000011058 Expr::EvalResult Result;
11059 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11060 llvm::APSInt Value(32);
11061 Value = Result.Val.getInt();
11062
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011063 if (S.SourceMgr.isInSystemMacro(CC))
11064 return;
11065
John McCall18a2c2c2010-11-09 22:22:12 +000011066 std::string PrettySourceValue = Value.toString(10);
11067 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011068
Ted Kremenek33ba9952011-10-22 02:37:33 +000011069 S.DiagRuntimeBehavior(E->getExprLoc(), E,
11070 S.PDiag(diag::warn_impcast_integer_precision_constant)
11071 << PrettySourceValue << PrettyTargetValue
11072 << E->getType() << T << E->getSourceRange()
11073 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000011074 return;
11075 }
11076
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011077 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11078 if (S.SourceMgr.isInSystemMacro(CC))
11079 return;
11080
David Blaikie9455da02012-04-12 22:40:54 +000011081 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000011082 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11083 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000011084 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000011085 }
11086
David Bolvanskycf7d2252018-10-02 06:02:30 +000011087 if (TargetRange.Width > SourceRange.Width) {
11088 if (auto *UO = dyn_cast<UnaryOperator>(E))
11089 if (UO->getOpcode() == UO_Minus)
11090 if (Source->isUnsignedIntegerType()) {
11091 if (Target->isUnsignedIntegerType())
11092 return DiagnoseImpCast(S, E, T, CC,
11093 diag::warn_impcast_high_order_zero_bits);
11094 if (Target->isSignedIntegerType())
11095 return DiagnoseImpCast(S, E, T, CC,
11096 diag::warn_impcast_nonnegative_result);
11097 }
11098 }
11099
Richard Trieudcb55572016-01-29 23:51:16 +000011100 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11101 SourceRange.NonNegative && Source->isSignedIntegerType()) {
11102 // Warn when doing a signed to signed conversion, warn if the positive
11103 // source value is exactly the width of the target type, which will
11104 // cause a negative value to be stored.
11105
Fangrui Song407659a2018-11-30 23:41:18 +000011106 Expr::EvalResult Result;
11107 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
Richard Trieufc404c72016-02-05 23:02:38 +000011108 !S.SourceMgr.isInSystemMacro(CC)) {
Fangrui Song407659a2018-11-30 23:41:18 +000011109 llvm::APSInt Value = Result.Val.getInt();
Richard Trieufc404c72016-02-05 23:02:38 +000011110 if (isSameWidthConstantConversion(S, E, T, CC)) {
11111 std::string PrettySourceValue = Value.toString(10);
11112 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000011113
Richard Trieufc404c72016-02-05 23:02:38 +000011114 S.DiagRuntimeBehavior(
11115 E->getExprLoc(), E,
11116 S.PDiag(diag::warn_impcast_integer_precision_constant)
11117 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11118 << E->getSourceRange() << clang::SourceRange(CC));
11119 return;
Richard Trieudcb55572016-01-29 23:51:16 +000011120 }
11121 }
Richard Trieufc404c72016-02-05 23:02:38 +000011122
Richard Trieudcb55572016-01-29 23:51:16 +000011123 // Fall through for non-constants to give a sign conversion warning.
11124 }
11125
John McCallcc7e5bf2010-05-06 08:58:33 +000011126 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11127 (!TargetRange.NonNegative && SourceRange.NonNegative &&
11128 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011129 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011130 return;
11131
John McCallcc7e5bf2010-05-06 08:58:33 +000011132 unsigned DiagID = diag::warn_impcast_integer_sign;
11133
11134 // Traditionally, gcc has warned about this under -Wsign-compare.
11135 // We also want to warn about it in -Wconversion.
11136 // So if -Wconversion is off, use a completely identical diagnostic
11137 // in the sign-compare group.
Fangrui Song6907ce22018-07-30 19:24:48 +000011138 // The conditional-checking code will
John McCallcc7e5bf2010-05-06 08:58:33 +000011139 if (ICContext) {
11140 DiagID = diag::warn_impcast_integer_sign_conditional;
11141 *ICContext = true;
11142 }
11143
John McCallacf0ee52010-10-08 02:01:28 +000011144 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000011145 }
11146
Douglas Gregora78f1932011-02-22 02:45:07 +000011147 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000011148 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11149 // type, to give us better diagnostics.
11150 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011151 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000011152 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11153 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11154 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11155 SourceType = S.Context.getTypeDeclType(Enum);
11156 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11157 }
11158 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011159
Douglas Gregora78f1932011-02-22 02:45:07 +000011160 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11161 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000011162 if (SourceEnum->getDecl()->hasNameForLinkage() &&
11163 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011164 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011165 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011166 return;
11167
Fangrui Song6907ce22018-07-30 19:24:48 +000011168 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000011169 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011170 }
John McCall263a48b2010-01-04 23:31:57 +000011171}
11172
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011173static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11174 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011175
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011176static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11177 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011178 E = E->IgnoreParenImpCasts();
11179
11180 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000011181 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011182
John McCallacf0ee52010-10-08 02:01:28 +000011183 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011184 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000011185 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000011186}
11187
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011188static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11189 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000011190 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000011191
11192 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000011193 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11194 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000011195
11196 // If -Wconversion would have warned about either of the candidates
11197 // for a signedness conversion to the context type...
11198 if (!Suspicious) return;
11199
11200 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011201 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000011202 return;
11203
John McCallcc7e5bf2010-05-06 08:58:33 +000011204 // ...then check whether it would have warned about either of the
11205 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000011206 if (E->getType() == T) return;
Fangrui Song6907ce22018-07-30 19:24:48 +000011207
Richard Trieubb43dec2011-07-21 02:46:28 +000011208 Suspicious = false;
11209 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11210 E->getType(), CC, &Suspicious);
11211 if (!Suspicious)
11212 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000011213 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000011214}
11215
JF Bastiene77b48b2018-09-10 20:42:56 +000011216/// Check conversion of given expression to boolean.
Richard Trieu65724892014-11-15 06:37:39 +000011217/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011218static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000011219 if (S.getLangOpts().Bool)
11220 return;
JF Bastiene77b48b2018-09-10 20:42:56 +000011221 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11222 return;
Richard Trieu65724892014-11-15 06:37:39 +000011223 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11224}
11225
John McCallcc7e5bf2010-05-06 08:58:33 +000011226/// AnalyzeImplicitConversions - Find and report any interesting
11227/// implicit conversions in the given expression. There are a couple
11228/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011229static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11230 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000011231 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000011232 Expr *E = OrigE->IgnoreParenImpCasts();
11233
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000011234 if (E->isTypeDependent() || E->isValueDependent())
11235 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011236
John McCallcc7e5bf2010-05-06 08:58:33 +000011237 // For conditional operators, we analyze the arguments as if they
11238 // were being fed directly into the output.
11239 if (isa<ConditionalOperator>(E)) {
11240 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000011241 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011242 return;
11243 }
11244
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011245 // Check implicit argument conversions for function calls.
11246 if (CallExpr *Call = dyn_cast<CallExpr>(E))
11247 CheckImplicitArgumentConversions(S, Call, CC);
11248
John McCallcc7e5bf2010-05-06 08:58:33 +000011249 // Go ahead and check any implicit conversions we might have skipped.
11250 // The non-canonical typecheck is just an optimization;
11251 // CheckImplicitConversion will filter out dead implicit conversions.
11252 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000011253 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011254
11255 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000011256
11257 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11258 // The bound subexpressions in a PseudoObjectExpr are not reachable
11259 // as transitive children.
11260 // FIXME: Use a more uniform representation for this.
11261 for (auto *SE : POE->semantics())
11262 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11263 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000011264 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000011265
John McCallcc7e5bf2010-05-06 08:58:33 +000011266 // Skip past explicit casts.
JF Bastiene77b48b2018-09-10 20:42:56 +000011267 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11268 E = CE->getSubExpr()->IgnoreParenImpCasts();
11269 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11270 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
John McCallacf0ee52010-10-08 02:01:28 +000011271 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011272 }
11273
John McCalld2a53122010-11-09 23:24:47 +000011274 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11275 // Do a somewhat different check with comparison operators.
11276 if (BO->isComparisonOp())
11277 return AnalyzeComparison(S, BO);
11278
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011279 // And with simple assignments.
11280 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000011281 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011282 // And with compound assignments.
11283 if (BO->isAssignmentOp())
11284 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000011285 }
John McCallcc7e5bf2010-05-06 08:58:33 +000011286
11287 // These break the otherwise-useful invariant below. Fortunately,
11288 // we don't really need to recurse into them, because any internal
11289 // expressions should have been analyzed already when they were
11290 // built into statements.
11291 if (isa<StmtExpr>(E)) return;
11292
11293 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000011294 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000011295
11296 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000011297 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000011298 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000011299 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000011300 for (Stmt *SubStmt : E->children()) {
11301 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000011302 if (!ChildExpr)
11303 continue;
11304
Richard Trieu955231d2014-01-25 01:10:35 +000011305 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000011306 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000011307 // Ignore checking string literals that are in logical and operators.
11308 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000011309 continue;
11310 AnalyzeImplicitConversions(S, ChildExpr, CC);
11311 }
Richard Trieu791b86e2014-11-19 06:08:18 +000011312
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000011313 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000011314 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11315 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000011316 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000011317
11318 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11319 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000011320 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000011321 }
Richard Trieu791b86e2014-11-19 06:08:18 +000011322
JF Bastiene77b48b2018-09-10 20:42:56 +000011323 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11324 if (U->getOpcode() == UO_LNot) {
Richard Trieu65724892014-11-15 06:37:39 +000011325 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
JF Bastiene77b48b2018-09-10 20:42:56 +000011326 } else if (U->getOpcode() != UO_AddrOf) {
11327 if (U->getSubExpr()->getType()->isAtomicType())
11328 S.Diag(U->getSubExpr()->getBeginLoc(),
11329 diag::warn_atomic_implicit_seq_cst);
11330 }
11331 }
John McCallcc7e5bf2010-05-06 08:58:33 +000011332}
11333
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011334/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011335static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11336 // Taking into account implicit conversions,
11337 // allow any integer.
11338 if (!E->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011339 S.Diag(E->getBeginLoc(),
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011340 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11341 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011342 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011343 // Potentially emit standard warnings for implicit conversions if enabled
11344 // using -Wconversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011345 CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011346 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011347}
11348
Richard Trieuc1888e02014-06-28 23:25:37 +000011349// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11350// Returns true when emitting a warning about taking the address of a reference.
11351static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000011352 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000011353 E = E->IgnoreParenImpCasts();
11354
11355 const FunctionDecl *FD = nullptr;
11356
11357 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11358 if (!DRE->getDecl()->getType()->isReferenceType())
11359 return false;
11360 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11361 if (!M->getMemberDecl()->getType()->isReferenceType())
11362 return false;
11363 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000011364 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000011365 return false;
11366 FD = Call->getDirectCallee();
11367 } else {
11368 return false;
11369 }
11370
11371 SemaRef.Diag(E->getExprLoc(), PD);
11372
11373 // If possible, point to location of function.
11374 if (FD) {
11375 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11376 }
11377
11378 return true;
11379}
11380
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011381// Returns true if the SourceLocation is expanded from any macro body.
11382// Returns false if the SourceLocation is invalid, is from not in a macro
11383// expansion, or is from expanded from a top-level macro argument.
11384static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11385 if (Loc.isInvalid())
11386 return false;
11387
11388 while (Loc.isMacroID()) {
11389 if (SM.isMacroBodyExpansion(Loc))
11390 return true;
11391 Loc = SM.getImmediateMacroCallerLoc(Loc);
11392 }
11393
11394 return false;
11395}
11396
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011397/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000011398/// \param E the expression containing the pointer
11399/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11400/// compared to a null pointer
11401/// \param IsEqual True when the comparison is equal to a null pointer
11402/// \param Range Extra SourceRange to highlight in the diagnostic
11403void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11404 Expr::NullPointerConstantKind NullKind,
11405 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000011406 if (!E)
11407 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011408
11409 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011410 if (E->getExprLoc().isMacroID()) {
11411 const SourceManager &SM = getSourceManager();
11412 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11413 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000011414 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011415 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000011416 E = E->IgnoreImpCasts();
11417
11418 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11419
Richard Trieuf7432752014-06-06 21:39:26 +000011420 if (isa<CXXThisExpr>(E)) {
11421 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11422 : diag::warn_this_bool_conversion;
11423 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11424 return;
11425 }
11426
Richard Trieu3bb8b562014-02-26 02:36:06 +000011427 bool IsAddressOf = false;
11428
11429 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11430 if (UO->getOpcode() != UO_AddrOf)
11431 return;
11432 IsAddressOf = true;
11433 E = UO->getSubExpr();
11434 }
11435
Richard Trieuc1888e02014-06-28 23:25:37 +000011436 if (IsAddressOf) {
11437 unsigned DiagID = IsCompare
11438 ? diag::warn_address_of_reference_null_compare
11439 : diag::warn_address_of_reference_bool_conversion;
11440 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11441 << IsEqual;
11442 if (CheckForReference(*this, E, PD)) {
11443 return;
11444 }
11445 }
11446
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011447 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11448 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000011449 std::string Str;
11450 llvm::raw_string_ostream S(Str);
11451 E->printPretty(S, nullptr, getPrintingPolicy());
11452 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11453 : diag::warn_cast_nonnull_to_bool;
11454 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11455 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011456 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000011457 };
11458
11459 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11460 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11461 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011462 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11463 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000011464 return;
11465 }
11466 }
11467 }
11468
Richard Trieu3bb8b562014-02-26 02:36:06 +000011469 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000011470 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011471 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11472 D = R->getDecl();
11473 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11474 D = M->getMemberDecl();
11475 }
11476
11477 // Weak Decls can be null.
11478 if (!D || D->isWeak())
11479 return;
George Burgess IV850269a2015-12-08 22:02:00 +000011480
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011481 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000011482 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11483 if (getCurFunction() &&
11484 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011485 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11486 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000011487 return;
11488 }
11489
11490 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000011491 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000011492 assert(ParamIter != FD->param_end());
11493 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11494
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011495 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11496 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011497 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000011498 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011499 }
George Burgess IV850269a2015-12-08 22:02:00 +000011500
Joel E. Denny81508102018-03-13 14:51:22 +000011501 for (const ParamIdx &ArgNo : NonNull->args()) {
11502 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011503 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011504 return;
11505 }
George Burgess IV850269a2015-12-08 22:02:00 +000011506 }
11507 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011508 }
11509 }
George Burgess IV850269a2015-12-08 22:02:00 +000011510 }
11511
Richard Trieu3bb8b562014-02-26 02:36:06 +000011512 QualType T = D->getType();
11513 const bool IsArray = T->isArrayType();
11514 const bool IsFunction = T->isFunctionType();
11515
Richard Trieuc1888e02014-06-28 23:25:37 +000011516 // Address of function is used to silence the function warning.
11517 if (IsAddressOf && IsFunction) {
11518 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011519 }
11520
11521 // Found nothing.
11522 if (!IsAddressOf && !IsFunction && !IsArray)
11523 return;
11524
11525 // Pretty print the expression for the diagnostic.
11526 std::string Str;
11527 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000011528 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000011529
11530 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11531 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000011532 enum {
11533 AddressOf,
11534 FunctionPointer,
11535 ArrayPointer
11536 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011537 if (IsAddressOf)
11538 DiagType = AddressOf;
11539 else if (IsFunction)
11540 DiagType = FunctionPointer;
11541 else if (IsArray)
11542 DiagType = ArrayPointer;
11543 else
11544 llvm_unreachable("Could not determine diagnostic.");
11545 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11546 << Range << IsEqual;
11547
11548 if (!IsFunction)
11549 return;
11550
11551 // Suggest '&' to silence the function warning.
11552 Diag(E->getExprLoc(), diag::note_function_warning_silence)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011553 << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
Richard Trieu3bb8b562014-02-26 02:36:06 +000011554
11555 // Check to see if '()' fixit should be emitted.
11556 QualType ReturnType;
11557 UnresolvedSet<4> NonTemplateOverloads;
11558 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11559 if (ReturnType.isNull())
11560 return;
11561
11562 if (IsCompare) {
11563 // There are two cases here. If there is null constant, the only suggest
11564 // for a pointer return type. If the null is 0, then suggest if the return
11565 // type is a pointer or an integer type.
11566 if (!ReturnType->isPointerType()) {
11567 if (NullKind == Expr::NPCK_ZeroExpression ||
11568 NullKind == Expr::NPCK_ZeroLiteral) {
11569 if (!ReturnType->isIntegerType())
11570 return;
11571 } else {
11572 return;
11573 }
11574 }
11575 } else { // !IsCompare
11576 // For function to bool, only suggest if the function pointer has bool
11577 // return type.
11578 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11579 return;
11580 }
11581 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Kelly1c301dc2018-08-09 21:09:38 +000011582 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000011583}
11584
John McCallcc7e5bf2010-05-06 08:58:33 +000011585/// Diagnoses "dangerous" implicit conversions within the given
11586/// expression (which is a full expression). Implements -Wconversion
11587/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000011588///
11589/// \param CC the "context" location of the implicit conversion, i.e.
11590/// the most location of the syntactic entity requiring the implicit
11591/// conversion
11592void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011593 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000011594 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000011595 return;
11596
11597 // Don't diagnose for value- or type-dependent expressions.
11598 if (E->isTypeDependent() || E->isValueDependent())
11599 return;
11600
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011601 // Check for array bounds violations in cases where the check isn't triggered
11602 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11603 // ArraySubscriptExpr is on the RHS of a variable initialization.
11604 CheckArrayAccess(E);
11605
John McCallacf0ee52010-10-08 02:01:28 +000011606 // This is not the right CC for (e.g.) a variable initialization.
11607 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011608}
11609
Richard Trieu65724892014-11-15 06:37:39 +000011610/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11611/// Input argument E is a logical expression.
11612void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11613 ::CheckBoolLikeConversion(*this, E, CC);
11614}
11615
Richard Smith9f7df0c2017-06-26 23:19:32 +000011616/// Diagnose when expression is an integer constant expression and its evaluation
11617/// results in integer overflow
11618void Sema::CheckForIntOverflow (Expr *E) {
11619 // Use a work list to deal with nested struct initializers.
11620 SmallVector<Expr *, 2> Exprs(1, E);
11621
11622 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011623 Expr *OriginalE = Exprs.pop_back_val();
11624 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000011625
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011626 if (isa<BinaryOperator>(E)) {
11627 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000011628 continue;
11629 }
11630
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011631 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000011632 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011633 else if (isa<ObjCBoxedExpr>(OriginalE))
11634 E->EvaluateForOverflow(Context);
11635 else if (auto Call = dyn_cast<CallExpr>(E))
11636 Exprs.append(Call->arg_begin(), Call->arg_end());
11637 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11638 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000011639 } while (!Exprs.empty());
11640}
11641
Richard Smithc406cb72013-01-17 01:17:56 +000011642namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011643
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011644/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000011645/// same object.
11646class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011647 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000011648
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011649 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000011650 /// unsequenced if one is an ancestor or a descendent of the other. When we
11651 /// finish processing an expression with sequencing, such as a comma
11652 /// expression, we fold its tree nodes into its parent, since they are
11653 /// unsequenced with respect to nodes we will visit later.
11654 class SequenceTree {
11655 struct Value {
11656 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11657 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000011658 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000011659 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011660 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000011661
11662 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011663 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000011664 /// to some other region.
11665 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000011666 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011667
Serge Gueltonbe885392019-01-20 21:19:56 +000011668 unsigned Index;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011669
11670 explicit Seq(unsigned N) : Index(N) {}
11671
Richard Smithc406cb72013-01-17 01:17:56 +000011672 public:
Serge Gueltonbe885392019-01-20 21:19:56 +000011673 Seq() : Index(0) {}
Richard Smithc406cb72013-01-17 01:17:56 +000011674 };
11675
11676 SequenceTree() { Values.push_back(Value(0)); }
11677 Seq root() const { return Seq(0); }
11678
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011679 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000011680 /// subset of \p Parent. This sequence of operations is sequenced with
11681 /// respect to other children of \p Parent.
11682 Seq allocate(Seq Parent) {
11683 Values.push_back(Value(Parent.Index));
11684 return Seq(Values.size() - 1);
11685 }
11686
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011687 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000011688 void merge(Seq S) {
11689 Values[S.Index].Merged = true;
11690 }
11691
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011692 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000011693 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11694 /// should have been merged into its parent as appropriate.
11695 bool isUnsequenced(Seq Cur, Seq Old) {
11696 unsigned C = representative(Cur.Index);
11697 unsigned Target = representative(Old.Index);
11698 while (C >= Target) {
11699 if (C == Target)
11700 return true;
11701 C = Values[C].Parent;
11702 }
11703 return false;
11704 }
11705
11706 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011707 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000011708 unsigned representative(unsigned K) {
11709 if (Values[K].Merged)
11710 // Perform path compression as we go.
11711 return Values[K].Parent = representative(Values[K].Parent);
11712 return K;
11713 }
11714 };
11715
11716 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011717 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000011718
11719 /// Different flavors of object usage which we track. We only track the
11720 /// least-sequenced usage of each kind.
11721 enum UsageKind {
11722 /// A read of an object. Multiple unsequenced reads are OK.
11723 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011724
Richard Smithc406cb72013-01-17 01:17:56 +000011725 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000011726 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000011727 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011728
Richard Smithc406cb72013-01-17 01:17:56 +000011729 /// A modification of an object which is not sequenced before the value
11730 /// computation of the expression, such as n++.
11731 UK_ModAsSideEffect,
11732
11733 UK_Count = UK_ModAsSideEffect + 1
11734 };
11735
11736 struct Usage {
Serge Gueltonc1904042019-01-20 23:43:37 +000011737 Expr *Use;
Richard Smithc406cb72013-01-17 01:17:56 +000011738 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011739
Serge Gueltonc1904042019-01-20 23:43:37 +000011740 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +000011741 };
11742
11743 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000011744 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011745
Richard Smithc406cb72013-01-17 01:17:56 +000011746 /// Have we issued a diagnostic for this variable already?
Serge Gueltonc1904042019-01-20 23:43:37 +000011747 bool Diagnosed;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011748
Serge Gueltonc1904042019-01-20 23:43:37 +000011749 UsageInfo() : Uses(), Diagnosed(false) {}
Richard Smithc406cb72013-01-17 01:17:56 +000011750 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011751 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000011752
11753 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011754
Richard Smithc406cb72013-01-17 01:17:56 +000011755 /// Sequenced regions within the expression.
11756 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011757
Richard Smithc406cb72013-01-17 01:17:56 +000011758 /// Declaration modifications and references which we have seen.
11759 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011760
Richard Smithc406cb72013-01-17 01:17:56 +000011761 /// The region we are currently within.
11762 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011763
Richard Smithc406cb72013-01-17 01:17:56 +000011764 /// Filled in with declarations which were modified as a side-effect
11765 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011766 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11767
Richard Smithd33f5202013-01-17 23:18:09 +000011768 /// Expressions to check later. We defer checking these to reduce
11769 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011770 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000011771
11772 /// RAII object wrapping the visitation of a sequenced subexpression of an
11773 /// expression. At the end of this process, the side-effects of the evaluation
11774 /// become sequenced with respect to the value computation of the result, so
11775 /// we downgrade any UK_ModAsSideEffect within the evaluation to
11776 /// UK_ModAsValue.
11777 struct SequencedSubexpression {
11778 SequencedSubexpression(SequenceChecker &Self)
11779 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11780 Self.ModAsSideEffect = &ModAsSideEffect;
11781 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011782
Richard Smithc406cb72013-01-17 01:17:56 +000011783 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000011784 for (auto &M : llvm::reverse(ModAsSideEffect)) {
11785 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000011786 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000011787 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11788 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000011789 }
11790 Self.ModAsSideEffect = OldModAsSideEffect;
11791 }
11792
11793 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011794 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011795 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000011796 };
11797
Richard Smith40238f02013-06-20 22:21:56 +000011798 /// RAII object wrapping the visitation of a subexpression which we might
11799 /// choose to evaluate as a constant. If any subexpression is evaluated and
11800 /// found to be non-constant, this allows us to suppress the evaluation of
11801 /// the outer expression.
11802 class EvaluationTracker {
11803 public:
11804 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011805 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000011806 Self.EvalTracker = this;
11807 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011808
Richard Smith40238f02013-06-20 22:21:56 +000011809 ~EvaluationTracker() {
11810 Self.EvalTracker = Prev;
11811 if (Prev)
11812 Prev->EvalOK &= EvalOK;
11813 }
11814
11815 bool evaluate(const Expr *E, bool &Result) {
11816 if (!EvalOK || E->isValueDependent())
11817 return false;
11818 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11819 return EvalOK;
11820 }
11821
11822 private:
11823 SequenceChecker &Self;
11824 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011825 bool EvalOK = true;
11826 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000011827
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011828 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000011829 /// if any.
11830 Object getObject(Expr *E, bool Mod) const {
11831 E = E->IgnoreParenCasts();
11832 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11833 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11834 return getObject(UO->getSubExpr(), Mod);
11835 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11836 if (BO->getOpcode() == BO_Comma)
11837 return getObject(BO->getRHS(), Mod);
11838 if (Mod && BO->isAssignmentOp())
11839 return getObject(BO->getLHS(), Mod);
11840 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11841 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11842 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11843 return ME->getMemberDecl();
11844 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11845 // FIXME: If this is a reference, map through to its value.
11846 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000011847 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011848 }
11849
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011850 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000011851 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11852 Usage &U = UI.Uses[UK];
11853 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11854 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11855 ModAsSideEffect->push_back(std::make_pair(O, U));
11856 U.Use = Ref;
11857 U.Seq = Region;
11858 }
11859 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011860
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011861 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000011862 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11863 bool IsModMod) {
11864 if (UI.Diagnosed)
11865 return;
11866
11867 const Usage &U = UI.Uses[OtherKind];
11868 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11869 return;
11870
11871 Expr *Mod = U.Use;
11872 Expr *ModOrUse = Ref;
11873 if (OtherKind == UK_Use)
11874 std::swap(Mod, ModOrUse);
11875
11876 SemaRef.Diag(Mod->getExprLoc(),
11877 IsModMod ? diag::warn_unsequenced_mod_mod
11878 : diag::warn_unsequenced_mod_use)
11879 << O << SourceRange(ModOrUse->getExprLoc());
11880 UI.Diagnosed = true;
11881 }
11882
11883 void notePreUse(Object O, Expr *Use) {
11884 UsageInfo &U = UsageMap[O];
11885 // Uses conflict with other modifications.
11886 checkUsage(O, U, Use, UK_ModAsValue, false);
11887 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011888
Richard Smithc406cb72013-01-17 01:17:56 +000011889 void notePostUse(Object O, Expr *Use) {
11890 UsageInfo &U = UsageMap[O];
11891 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11892 addUsage(U, O, Use, UK_Use);
11893 }
11894
11895 void notePreMod(Object O, Expr *Mod) {
11896 UsageInfo &U = UsageMap[O];
11897 // Modifications conflict with other modifications and with uses.
11898 checkUsage(O, U, Mod, UK_ModAsValue, true);
11899 checkUsage(O, U, Mod, UK_Use, false);
11900 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011901
Richard Smithc406cb72013-01-17 01:17:56 +000011902 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11903 UsageInfo &U = UsageMap[O];
11904 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11905 addUsage(U, O, Use, UK);
11906 }
11907
11908public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011909 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011910 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011911 Visit(E);
11912 }
11913
11914 void VisitStmt(Stmt *S) {
11915 // Skip all statements which aren't expressions for now.
11916 }
11917
11918 void VisitExpr(Expr *E) {
11919 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011920 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011921 }
11922
11923 void VisitCastExpr(CastExpr *E) {
11924 Object O = Object();
11925 if (E->getCastKind() == CK_LValueToRValue)
11926 O = getObject(E->getSubExpr(), false);
11927
11928 if (O)
11929 notePreUse(O, E);
11930 VisitExpr(E);
11931 if (O)
11932 notePostUse(O, E);
11933 }
11934
Nicolas Lesser5610cd82019-01-10 19:03:33 +000011935 void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
11936 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
11937 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
11938 SequenceTree::Seq OldRegion = Region;
11939
11940 {
11941 SequencedSubexpression SeqBefore(*this);
11942 Region = BeforeRegion;
11943 Visit(SequencedBefore);
11944 }
11945
11946 Region = AfterRegion;
11947 Visit(SequencedAfter);
11948
11949 Region = OldRegion;
11950
11951 Tree.merge(BeforeRegion);
11952 Tree.merge(AfterRegion);
11953 }
11954
11955 void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
11956 // C++17 [expr.sub]p1:
11957 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
11958 // expression E1 is sequenced before the expression E2.
11959 if (SemaRef.getLangOpts().CPlusPlus17)
11960 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
11961 else
11962 Base::VisitStmt(ASE);
11963 }
11964
Richard Smithc406cb72013-01-17 01:17:56 +000011965 void VisitBinComma(BinaryOperator *BO) {
11966 // C++11 [expr.comma]p1:
11967 // Every value computation and side effect associated with the left
11968 // expression is sequenced before every value computation and side
11969 // effect associated with the right expression.
Nicolas Lesser5610cd82019-01-10 19:03:33 +000011970 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
Richard Smithc406cb72013-01-17 01:17:56 +000011971 }
11972
11973 void VisitBinAssign(BinaryOperator *BO) {
11974 // The modification is sequenced after the value computation of the LHS
11975 // and RHS, so check it before inspecting the operands and update the
11976 // map afterwards.
11977 Object O = getObject(BO->getLHS(), true);
11978 if (!O)
11979 return VisitExpr(BO);
11980
11981 notePreMod(O, BO);
11982
11983 // C++11 [expr.ass]p7:
11984 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11985 // only once.
11986 //
11987 // Therefore, for a compound assignment operator, O is considered used
11988 // everywhere except within the evaluation of E1 itself.
11989 if (isa<CompoundAssignOperator>(BO))
11990 notePreUse(O, BO);
11991
11992 Visit(BO->getLHS());
11993
11994 if (isa<CompoundAssignOperator>(BO))
11995 notePostUse(O, BO);
11996
11997 Visit(BO->getRHS());
11998
Richard Smith83e37bee2013-06-26 23:16:51 +000011999 // C++11 [expr.ass]p1:
12000 // the assignment is sequenced [...] before the value computation of the
12001 // assignment expression.
12002 // C11 6.5.16/3 has no such rule.
12003 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12004 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000012005 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000012006
Richard Smithc406cb72013-01-17 01:17:56 +000012007 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12008 VisitBinAssign(CAO);
12009 }
12010
12011 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12012 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12013 void VisitUnaryPreIncDec(UnaryOperator *UO) {
12014 Object O = getObject(UO->getSubExpr(), true);
12015 if (!O)
12016 return VisitExpr(UO);
12017
12018 notePreMod(O, UO);
12019 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000012020 // C++11 [expr.pre.incr]p1:
12021 // the expression ++x is equivalent to x+=1
12022 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12023 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000012024 }
12025
12026 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12027 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12028 void VisitUnaryPostIncDec(UnaryOperator *UO) {
12029 Object O = getObject(UO->getSubExpr(), true);
12030 if (!O)
12031 return VisitExpr(UO);
12032
12033 notePreMod(O, UO);
12034 Visit(UO->getSubExpr());
12035 notePostMod(O, UO, UK_ModAsSideEffect);
12036 }
12037
12038 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12039 void VisitBinLOr(BinaryOperator *BO) {
12040 // The side-effects of the LHS of an '&&' are sequenced before the
12041 // value computation of the RHS, and hence before the value computation
12042 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12043 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000012044 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000012045 {
12046 SequencedSubexpression Sequenced(*this);
12047 Visit(BO->getLHS());
12048 }
12049
12050 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012051 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000012052 if (!Result)
12053 Visit(BO->getRHS());
12054 } else {
12055 // Check for unsequenced operations in the RHS, treating it as an
12056 // entirely separate evaluation.
12057 //
12058 // FIXME: If there are operations in the RHS which are unsequenced
12059 // with respect to operations outside the RHS, and those operations
12060 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000012061 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000012062 }
Richard Smithc406cb72013-01-17 01:17:56 +000012063 }
12064 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000012065 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000012066 {
12067 SequencedSubexpression Sequenced(*this);
12068 Visit(BO->getLHS());
12069 }
12070
12071 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012072 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000012073 if (Result)
12074 Visit(BO->getRHS());
12075 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000012076 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000012077 }
Richard Smithc406cb72013-01-17 01:17:56 +000012078 }
12079
12080 // Only visit the condition, unless we can be sure which subexpression will
12081 // be chosen.
12082 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000012083 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000012084 {
12085 SequencedSubexpression Sequenced(*this);
12086 Visit(CO->getCond());
12087 }
Richard Smithc406cb72013-01-17 01:17:56 +000012088
12089 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000012090 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000012091 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000012092 else {
Richard Smithd33f5202013-01-17 23:18:09 +000012093 WorkList.push_back(CO->getTrueExpr());
12094 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000012095 }
Richard Smithc406cb72013-01-17 01:17:56 +000012096 }
12097
Richard Smithe3dbfe02013-06-30 10:40:20 +000012098 void VisitCallExpr(CallExpr *CE) {
12099 // C++11 [intro.execution]p15:
12100 // When calling a function [...], every value computation and side effect
12101 // associated with any argument expression, or with the postfix expression
12102 // designating the called function, is sequenced before execution of every
12103 // expression or statement in the body of the function [and thus before
12104 // the value computation of its result].
12105 SequencedSubexpression Sequenced(*this);
12106 Base::VisitCallExpr(CE);
12107
12108 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12109 }
12110
Richard Smithc406cb72013-01-17 01:17:56 +000012111 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000012112 // This is a call, so all subexpressions are sequenced before the result.
12113 SequencedSubexpression Sequenced(*this);
12114
Richard Smithc406cb72013-01-17 01:17:56 +000012115 if (!CCE->isListInitialization())
12116 return VisitExpr(CCE);
12117
12118 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012119 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000012120 SequenceTree::Seq Parent = Region;
12121 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12122 E = CCE->arg_end();
12123 I != E; ++I) {
12124 Region = Tree.allocate(Parent);
12125 Elts.push_back(Region);
12126 Visit(*I);
12127 }
12128
12129 // Forget that the initializers are sequenced.
12130 Region = Parent;
12131 for (unsigned I = 0; I < Elts.size(); ++I)
12132 Tree.merge(Elts[I]);
12133 }
12134
12135 void VisitInitListExpr(InitListExpr *ILE) {
12136 if (!SemaRef.getLangOpts().CPlusPlus11)
12137 return VisitExpr(ILE);
12138
12139 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012140 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000012141 SequenceTree::Seq Parent = Region;
12142 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12143 Expr *E = ILE->getInit(I);
12144 if (!E) continue;
12145 Region = Tree.allocate(Parent);
12146 Elts.push_back(Region);
12147 Visit(E);
12148 }
12149
12150 // Forget that the initializers are sequenced.
12151 Region = Parent;
12152 for (unsigned I = 0; I < Elts.size(); ++I)
12153 Tree.merge(Elts[I]);
12154 }
12155};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012156
12157} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000012158
12159void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012160 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000012161 WorkList.push_back(E);
12162 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000012163 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000012164 SequenceChecker(*this, Item, WorkList);
12165 }
Richard Smithc406cb72013-01-17 01:17:56 +000012166}
12167
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012168void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12169 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000012170 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000012171 if (!E->isInstantiationDependent())
12172 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012173 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000012174 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012175 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000012176}
12177
John McCall1f425642010-11-11 03:21:53 +000012178void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12179 FieldDecl *BitField,
12180 Expr *Init) {
12181 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12182}
12183
David Majnemer61a5bbf2015-04-07 22:08:51 +000012184static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12185 SourceLocation Loc) {
12186 if (!PType->isVariablyModifiedType())
12187 return;
12188 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12189 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12190 return;
12191 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000012192 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12193 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12194 return;
12195 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000012196 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12197 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12198 return;
12199 }
12200
12201 const ArrayType *AT = S.Context.getAsArrayType(PType);
12202 if (!AT)
12203 return;
12204
12205 if (AT->getSizeModifier() != ArrayType::Star) {
12206 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12207 return;
12208 }
12209
12210 S.Diag(Loc, diag::err_array_star_in_function_definition);
12211}
12212
Mike Stump0c2ec772010-01-21 03:59:47 +000012213/// CheckParmsForFunctionDef - Check that the parameters of the given
12214/// function are appropriate for the definition of a function. This
12215/// takes care of any checks that cannot be performed on the
12216/// declaration itself, e.g., that the types of each of the function
12217/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000012218bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000012219 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012220 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000012221 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012222 // C99 6.7.5.3p4: the parameters in a parameter type list in a
12223 // function declarator that is part of a function definition of
12224 // that function shall not have incomplete type.
12225 //
12226 // This is also C++ [dcl.fct]p6.
12227 if (!Param->isInvalidDecl() &&
12228 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012229 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012230 Param->setInvalidDecl();
12231 HasInvalidParm = true;
12232 }
12233
12234 // C99 6.9.1p5: If the declarator includes a parameter type list, the
12235 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000012236 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000012237 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000012238 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012239 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000012240 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000012241
12242 // C99 6.7.5.3p12:
12243 // If the function declarator is not part of a definition of that
12244 // function, parameters may have incomplete type and may use the [*]
12245 // notation in their sequences of declarator specifiers to specify
12246 // variable length array types.
12247 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000012248 // FIXME: This diagnostic should point the '[*]' if source-location
12249 // information is added for it.
12250 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000012251
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012252 // If the parameter is a c++ class type and it has to be destructed in the
12253 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012254 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012255 if (!Param->isInvalidDecl()) {
12256 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12257 if (!ClassDecl->isInvalidDecl() &&
12258 !ClassDecl->hasIrrelevantDestructor() &&
12259 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000012260 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012261 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12262 MarkFunctionReferenced(Param->getLocation(), Destructor);
12263 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000012264 }
12265 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000012266 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012267
12268 // Parameters with the pass_object_size attribute only need to be marked
12269 // constant at function definitions. Because we lack information about
12270 // whether we're on a declaration or definition when we're instantiating the
12271 // attribute, we need to check for constness here.
12272 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12273 if (!Param->getType().isConstQualified())
12274 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12275 << Attr->getSpelling() << 1;
Aaron Ballmanc3463f62018-12-05 18:56:57 +000012276
12277 // Check for parameter names shadowing fields from the class.
12278 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12279 // The owning context for the parameter should be the function, but we
12280 // want to see if this function's declaration context is a record.
12281 DeclContext *DC = Param->getDeclContext();
12282 if (DC && DC->isFunctionOrMethod()) {
12283 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12284 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12285 RD, /*DeclIsField*/ false);
12286 }
12287 }
Mike Stump0c2ec772010-01-21 03:59:47 +000012288 }
12289
12290 return HasInvalidParm;
12291}
John McCall2b5c1b22010-08-12 21:44:57 +000012292
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000012293/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12294/// or MemberExpr.
12295static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12296 ASTContext &Context) {
12297 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12298 return Context.getDeclAlign(DRE->getDecl());
12299
12300 if (const auto *ME = dyn_cast<MemberExpr>(E))
12301 return Context.getDeclAlign(ME->getMemberDecl());
12302
12303 return TypeAlign;
12304}
12305
John McCall2b5c1b22010-08-12 21:44:57 +000012306/// CheckCastAlign - Implements -Wcast-align, which warns when a
12307/// pointer cast increases the alignment requirements.
12308void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12309 // This is actually a lot of work to potentially be doing on every
12310 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012311 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000012312 return;
12313
12314 // Ignore dependent types.
12315 if (T->isDependentType() || Op->getType()->isDependentType())
12316 return;
12317
12318 // Require that the destination be a pointer type.
12319 const PointerType *DestPtr = T->getAs<PointerType>();
12320 if (!DestPtr) return;
12321
12322 // If the destination has alignment 1, we're done.
12323 QualType DestPointee = DestPtr->getPointeeType();
12324 if (DestPointee->isIncompleteType()) return;
12325 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12326 if (DestAlign.isOne()) return;
12327
12328 // Require that the source be a pointer type.
12329 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12330 if (!SrcPtr) return;
12331 QualType SrcPointee = SrcPtr->getPointeeType();
12332
12333 // Whitelist casts from cv void*. We already implicitly
12334 // whitelisted casts to cv void*, since they have alignment 1.
12335 // Also whitelist casts involving incomplete types, which implicitly
12336 // includes 'void'.
12337 if (SrcPointee->isIncompleteType()) return;
12338
12339 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000012340
12341 if (auto *CE = dyn_cast<CastExpr>(Op)) {
12342 if (CE->getCastKind() == CK_ArrayToPointerDecay)
12343 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12344 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12345 if (UO->getOpcode() == UO_AddrOf)
12346 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12347 }
12348
John McCall2b5c1b22010-08-12 21:44:57 +000012349 if (SrcAlign >= DestAlign) return;
12350
12351 Diag(TRange.getBegin(), diag::warn_cast_align)
12352 << Op->getType() << T
12353 << static_cast<unsigned>(SrcAlign.getQuantity())
12354 << static_cast<unsigned>(DestAlign.getQuantity())
12355 << TRange << Op->getSourceRange();
12356}
12357
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012358/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000012359/// array member of a struct.
12360///
12361/// We avoid emitting out-of-bounds access warnings for such arrays as they are
12362/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000012363static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000012364 const NamedDecl *ND) {
12365 if (Size != 1 || !ND) return false;
12366
12367 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12368 if (!FD) return false;
12369
12370 // Don't consider sizes resulting from macro expansions or template argument
12371 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000012372
12373 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012374 while (TInfo) {
12375 TypeLoc TL = TInfo->getTypeLoc();
12376 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000012377 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12378 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012379 TInfo = TDL->getTypeSourceInfo();
12380 continue;
12381 }
David Blaikie6adc78e2013-02-18 22:06:02 +000012382 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12383 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000012384 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12385 return false;
12386 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012387 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000012388 }
Chandler Carruth28389f02011-08-05 09:10:50 +000012389
12390 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000012391 if (!RD) return false;
12392 if (RD->isUnion()) return false;
12393 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12394 if (!CRD->isStandardLayout()) return false;
12395 }
Chandler Carruth28389f02011-08-05 09:10:50 +000012396
Benjamin Kramer8c543672011-08-06 03:04:42 +000012397 // See if this is the last field decl in the record.
12398 const Decl *D = FD;
12399 while ((D = D->getNextDeclInContext()))
12400 if (isa<FieldDecl>(D))
12401 return false;
12402 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000012403}
12404
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012405void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012406 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000012407 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012408 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012409 if (IndexExpr->isValueDependent())
12410 return;
12411
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000012412 const Type *EffectiveType =
12413 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012414 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012415 const ConstantArrayType *ArrayTy =
Bruno Riccied414842018-12-20 20:05:11 +000012416 Context.getAsConstantArrayType(BaseExpr->getType());
12417
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012418 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000012419 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000012420
Bruno Riccied414842018-12-20 20:05:11 +000012421 const Type *BaseType = ArrayTy->getElementType().getTypePtr();
Bruno Riccied414842018-12-20 20:05:11 +000012422
Fangrui Song407659a2018-11-30 23:41:18 +000012423 Expr::EvalResult Result;
12424 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000012425 return;
Fangrui Song407659a2018-11-30 23:41:18 +000012426
12427 llvm::APSInt index = Result.Val.getInt();
Richard Smith13f67182011-12-16 19:31:14 +000012428 if (IndexNegated)
12429 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000012430
Craig Topperc3ec1492014-05-26 06:22:03 +000012431 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000012432 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012433 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000012434 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012435 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000012436
Ted Kremeneke4b316c2011-02-23 23:06:04 +000012437 if (index.isUnsigned() || !index.isNegative()) {
Bruno Riccif605e822019-01-08 13:52:54 +000012438 // It is possible that the type of the base expression after
12439 // IgnoreParenCasts is incomplete, even though the type of the base
12440 // expression before IgnoreParenCasts is complete (see PR39746 for an
12441 // example). In this case we have no information about whether the array
12442 // access exceeds the array bounds. However we can still diagnose an array
12443 // access which precedes the array bounds.
12444 if (BaseType->isIncompleteType())
12445 return;
12446
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012447 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000012448 if (!size.isStrictlyPositive())
12449 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012450
Nico Weber7c299802011-09-17 22:59:41 +000012451 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012452 // Make sure we're comparing apples to apples when comparing index to size
12453 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12454 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000012455 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000012456 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012457 if (ptrarith_typesize != array_typesize) {
12458 // There's a cast to a different size type involved
12459 uint64_t ratio = array_typesize / ptrarith_typesize;
12460 // TODO: Be smarter about handling cases where array_typesize is not a
12461 // multiple of ptrarith_typesize
12462 if (ptrarith_typesize * ratio == array_typesize)
12463 size *= llvm::APInt(size.getBitWidth(), ratio);
12464 }
12465 }
12466
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012467 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012468 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012469 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012470 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012471
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012472 // For array subscripting the index must be less than size, but for pointer
12473 // arithmetic also allow the index (offset) to be equal to size since
12474 // computing the next address after the end of the array is legal and
12475 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012476 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000012477 return;
12478
12479 // Also don't warn for arrays of size 1 which are members of some
12480 // structure. These are often used to approximate flexible arrays in C89
12481 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012482 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000012483 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012484
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012485 // Suppress the warning if the subscript expression (as identified by the
12486 // ']' location) and the index expression are both from macro expansions
12487 // within a system header.
12488 if (ASE) {
12489 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12490 ASE->getRBracketLoc());
12491 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012492 SourceLocation IndexLoc =
12493 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
Eli Friedman5ba37d52013-08-22 00:27:10 +000012494 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012495 return;
12496 }
12497 }
12498
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012499 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012500 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012501 DiagID = diag::warn_array_index_exceeds_bounds;
12502
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012503 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012504 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012505 << size.toString(10, true)
12506 << (unsigned)size.getLimitedValue(~0U)
12507 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012508 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012509 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012510 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012511 DiagID = diag::warn_ptr_arith_precedes_bounds;
12512 if (index.isNegative()) index = -index;
12513 }
12514
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012515 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012516 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012517 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000012518 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000012519
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012520 if (!ND) {
12521 // Try harder to find a NamedDecl to point at in the note.
12522 while (const ArraySubscriptExpr *ASE =
12523 dyn_cast<ArraySubscriptExpr>(BaseExpr))
12524 BaseExpr = ASE->getBase()->IgnoreParenCasts();
12525 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012526 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012527 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012528 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012529 }
12530
Chandler Carruth1af88f12011-02-17 21:10:52 +000012531 if (ND)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012532 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012533 PDiag(diag::note_array_index_out_of_bounds)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012534 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000012535}
12536
Ted Kremenekdf26df72011-03-01 18:41:00 +000012537void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012538 int AllowOnePastEnd = 0;
12539 while (expr) {
12540 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000012541 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012542 case Stmt::ArraySubscriptExprClass: {
12543 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012544 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012545 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000012546 expr = ASE->getBase();
12547 break;
12548 }
12549 case Stmt::MemberExprClass: {
12550 expr = cast<MemberExpr>(expr)->getBase();
12551 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012552 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012553 case Stmt::OMPArraySectionExprClass: {
12554 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12555 if (ASE->getLowerBound())
12556 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12557 /*ASE=*/nullptr, AllowOnePastEnd > 0);
12558 return;
12559 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012560 case Stmt::UnaryOperatorClass: {
12561 // Only unwrap the * and & unary operators
12562 const UnaryOperator *UO = cast<UnaryOperator>(expr);
12563 expr = UO->getSubExpr();
12564 switch (UO->getOpcode()) {
12565 case UO_AddrOf:
12566 AllowOnePastEnd++;
12567 break;
12568 case UO_Deref:
12569 AllowOnePastEnd--;
12570 break;
12571 default:
12572 return;
12573 }
12574 break;
12575 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012576 case Stmt::ConditionalOperatorClass: {
12577 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12578 if (const Expr *lhs = cond->getLHS())
12579 CheckArrayAccess(lhs);
12580 if (const Expr *rhs = cond->getRHS())
12581 CheckArrayAccess(rhs);
12582 return;
12583 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000012584 case Stmt::CXXOperatorCallExprClass: {
12585 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12586 for (const auto *Arg : OCE->arguments())
12587 CheckArrayAccess(Arg);
12588 return;
12589 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012590 default:
12591 return;
12592 }
Peter Collingbourne91147592011-04-15 00:35:48 +000012593 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012594}
John McCall31168b02011-06-15 23:02:42 +000012595
12596//===--- CHECK: Objective-C retain cycles ----------------------------------//
12597
12598namespace {
John McCall31168b02011-06-15 23:02:42 +000012599
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012600struct RetainCycleOwner {
12601 VarDecl *Variable = nullptr;
12602 SourceRange Range;
12603 SourceLocation Loc;
12604 bool Indirect = false;
12605
12606 RetainCycleOwner() = default;
12607
12608 void setLocsFrom(Expr *e) {
12609 Loc = e->getExprLoc();
12610 Range = e->getSourceRange();
12611 }
12612};
12613
12614} // namespace
John McCall31168b02011-06-15 23:02:42 +000012615
12616/// Consider whether capturing the given variable can possibly lead to
12617/// a retain cycle.
12618static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000012619 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000012620 // lifetime. In MRR, it's captured strongly if the variable is
12621 // __block and has an appropriate type.
12622 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12623 return false;
12624
12625 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012626 if (ref)
12627 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000012628 return true;
12629}
12630
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012631static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000012632 while (true) {
12633 e = e->IgnoreParens();
12634 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12635 switch (cast->getCastKind()) {
12636 case CK_BitCast:
12637 case CK_LValueBitCast:
12638 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000012639 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000012640 e = cast->getSubExpr();
12641 continue;
12642
John McCall31168b02011-06-15 23:02:42 +000012643 default:
12644 return false;
12645 }
12646 }
12647
12648 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12649 ObjCIvarDecl *ivar = ref->getDecl();
12650 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12651 return false;
12652
12653 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012654 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000012655 return false;
12656
12657 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12658 owner.Indirect = true;
12659 return true;
12660 }
12661
12662 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12663 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12664 if (!var) return false;
12665 return considerVariable(var, ref, owner);
12666 }
12667
John McCall31168b02011-06-15 23:02:42 +000012668 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12669 if (member->isArrow()) return false;
12670
12671 // Don't count this as an indirect ownership.
12672 e = member->getBase();
12673 continue;
12674 }
12675
John McCallfe96e0b2011-11-06 09:01:30 +000012676 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12677 // Only pay attention to pseudo-objects on property references.
12678 ObjCPropertyRefExpr *pre
12679 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12680 ->IgnoreParens());
12681 if (!pre) return false;
12682 if (pre->isImplicitProperty()) return false;
12683 ObjCPropertyDecl *property = pre->getExplicitProperty();
12684 if (!property->isRetaining() &&
12685 !(property->getPropertyIvarDecl() &&
12686 property->getPropertyIvarDecl()->getType()
12687 .getObjCLifetime() == Qualifiers::OCL_Strong))
12688 return false;
12689
12690 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012691 if (pre->isSuperReceiver()) {
12692 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12693 if (!owner.Variable)
12694 return false;
12695 owner.Loc = pre->getLocation();
12696 owner.Range = pre->getSourceRange();
12697 return true;
12698 }
John McCallfe96e0b2011-11-06 09:01:30 +000012699 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12700 ->getSourceExpr());
12701 continue;
12702 }
12703
John McCall31168b02011-06-15 23:02:42 +000012704 // Array ivars?
12705
12706 return false;
12707 }
12708}
12709
12710namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012711
John McCall31168b02011-06-15 23:02:42 +000012712 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012713 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000012714 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012715 Expr *Capturer = nullptr;
12716 bool VarWillBeReased = false;
12717
12718 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12719 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12720 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000012721
12722 void VisitDeclRefExpr(DeclRefExpr *ref) {
12723 if (ref->getDecl() == Variable && !Capturer)
12724 Capturer = ref;
12725 }
12726
John McCall31168b02011-06-15 23:02:42 +000012727 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12728 if (Capturer) return;
12729 Visit(ref->getBase());
12730 if (Capturer && ref->isFreeIvar())
12731 Capturer = ref;
12732 }
12733
12734 void VisitBlockExpr(BlockExpr *block) {
Fangrui Song6907ce22018-07-30 19:24:48 +000012735 // Look inside nested blocks
John McCall31168b02011-06-15 23:02:42 +000012736 if (block->getBlockDecl()->capturesVariable(Variable))
12737 Visit(block->getBlockDecl()->getBody());
12738 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012739
Fariborz Jahanian0e337542012-08-31 20:04:47 +000012740 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12741 if (Capturer) return;
12742 if (OVE->getSourceExpr())
12743 Visit(OVE->getSourceExpr());
12744 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012745
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012746 void VisitBinaryOperator(BinaryOperator *BinOp) {
12747 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12748 return;
12749 Expr *LHS = BinOp->getLHS();
12750 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12751 if (DRE->getDecl() != Variable)
12752 return;
12753 if (Expr *RHS = BinOp->getRHS()) {
12754 RHS = RHS->IgnoreParenCasts();
12755 llvm::APSInt Value;
12756 VarWillBeReased =
12757 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12758 }
12759 }
12760 }
John McCall31168b02011-06-15 23:02:42 +000012761 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012762
12763} // namespace
John McCall31168b02011-06-15 23:02:42 +000012764
12765/// Check whether the given argument is a block which captures a
12766/// variable.
12767static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12768 assert(owner.Variable && owner.Loc.isValid());
12769
12770 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000012771
12772 // Look through [^{...} copy] and Block_copy(^{...}).
12773 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12774 Selector Cmd = ME->getSelector();
12775 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12776 e = ME->getInstanceReceiver();
12777 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000012778 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000012779 e = e->IgnoreParenCasts();
12780 }
12781 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12782 if (CE->getNumArgs() == 1) {
12783 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000012784 if (Fn) {
12785 const IdentifierInfo *FnI = Fn->getIdentifier();
12786 if (FnI && FnI->isStr("_Block_copy")) {
12787 e = CE->getArg(0)->IgnoreParenCasts();
12788 }
12789 }
Jordan Rose67e887c2012-09-17 17:54:30 +000012790 }
12791 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012792
John McCall31168b02011-06-15 23:02:42 +000012793 BlockExpr *block = dyn_cast<BlockExpr>(e);
12794 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000012795 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000012796
12797 FindCaptureVisitor visitor(S.Context, owner.Variable);
12798 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012799 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000012800}
12801
12802static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12803 RetainCycleOwner &owner) {
12804 assert(capturer);
12805 assert(owner.Variable && owner.Loc.isValid());
12806
12807 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12808 << owner.Variable << capturer->getSourceRange();
12809 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12810 << owner.Indirect << owner.Range;
12811}
12812
12813/// Check for a keyword selector that starts with the word 'add' or
12814/// 'set'.
12815static bool isSetterLikeSelector(Selector sel) {
12816 if (sel.isUnarySelector()) return false;
12817
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012818 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000012819 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012820 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000012821 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012822 else if (str.startswith("add")) {
12823 // Specially whitelist 'addOperationWithBlock:'.
12824 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12825 return false;
12826 str = str.substr(3);
12827 }
John McCall31168b02011-06-15 23:02:42 +000012828 else
12829 return false;
12830
12831 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000012832 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000012833}
12834
Benjamin Kramer3a743452015-03-09 15:03:32 +000012835static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12836 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012837 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12838 Message->getReceiverInterface(),
12839 NSAPI::ClassId_NSMutableArray);
12840 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012841 return None;
12842 }
12843
12844 Selector Sel = Message->getSelector();
12845
12846 Optional<NSAPI::NSArrayMethodKind> MKOpt =
12847 S.NSAPIObj->getNSArrayMethodKind(Sel);
12848 if (!MKOpt) {
12849 return None;
12850 }
12851
12852 NSAPI::NSArrayMethodKind MK = *MKOpt;
12853
12854 switch (MK) {
12855 case NSAPI::NSMutableArr_addObject:
12856 case NSAPI::NSMutableArr_insertObjectAtIndex:
12857 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12858 return 0;
12859 case NSAPI::NSMutableArr_replaceObjectAtIndex:
12860 return 1;
12861
12862 default:
12863 return None;
12864 }
12865
12866 return None;
12867}
12868
12869static
12870Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12871 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012872 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12873 Message->getReceiverInterface(),
12874 NSAPI::ClassId_NSMutableDictionary);
12875 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012876 return None;
12877 }
12878
12879 Selector Sel = Message->getSelector();
12880
12881 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12882 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12883 if (!MKOpt) {
12884 return None;
12885 }
12886
12887 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12888
12889 switch (MK) {
12890 case NSAPI::NSMutableDict_setObjectForKey:
12891 case NSAPI::NSMutableDict_setValueForKey:
12892 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12893 return 0;
12894
12895 default:
12896 return None;
12897 }
12898
12899 return None;
12900}
12901
12902static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012903 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12904 Message->getReceiverInterface(),
12905 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012906
Alex Denisov5dfac812015-08-06 04:51:14 +000012907 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12908 Message->getReceiverInterface(),
12909 NSAPI::ClassId_NSMutableOrderedSet);
12910 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012911 return None;
12912 }
12913
12914 Selector Sel = Message->getSelector();
12915
12916 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12917 if (!MKOpt) {
12918 return None;
12919 }
12920
12921 NSAPI::NSSetMethodKind MK = *MKOpt;
12922
12923 switch (MK) {
12924 case NSAPI::NSMutableSet_addObject:
12925 case NSAPI::NSOrderedSet_setObjectAtIndex:
12926 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12927 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12928 return 0;
12929 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12930 return 1;
12931 }
12932
12933 return None;
12934}
12935
12936void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12937 if (!Message->isInstanceMessage()) {
12938 return;
12939 }
12940
12941 Optional<int> ArgOpt;
12942
12943 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12944 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12945 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12946 return;
12947 }
12948
12949 int ArgIndex = *ArgOpt;
12950
Alex Denisove1d882c2015-03-04 17:55:52 +000012951 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12952 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12953 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12954 }
12955
Alex Denisov5dfac812015-08-06 04:51:14 +000012956 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012957 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012958 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012959 Diag(Message->getSourceRange().getBegin(),
12960 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012961 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012962 }
12963 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012964 } else {
12965 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12966
12967 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12968 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12969 }
12970
12971 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12972 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12973 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12974 ValueDecl *Decl = ReceiverRE->getDecl();
12975 Diag(Message->getSourceRange().getBegin(),
12976 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012977 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012978 if (!ArgRE->isObjCSelfExpr()) {
12979 Diag(Decl->getLocation(),
12980 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012981 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012982 }
12983 }
12984 }
12985 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12986 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12987 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12988 ObjCIvarDecl *Decl = IvarRE->getDecl();
12989 Diag(Message->getSourceRange().getBegin(),
12990 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012991 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012992 Diag(Decl->getLocation(),
12993 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012994 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012995 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012996 }
12997 }
12998 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012999}
13000
John McCall31168b02011-06-15 23:02:42 +000013001/// Check a message send to see if it's likely to cause a retain cycle.
13002void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13003 // Only check instance methods whose selector looks like a setter.
13004 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13005 return;
13006
13007 // Try to find a variable that the receiver is strongly owned by.
13008 RetainCycleOwner owner;
13009 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013010 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000013011 return;
13012 } else {
13013 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13014 owner.Variable = getCurMethodDecl()->getSelfDecl();
13015 owner.Loc = msg->getSuperLoc();
13016 owner.Range = msg->getSuperLoc();
13017 }
13018
13019 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000013020 const ObjCMethodDecl *MD = msg->getMethodDecl();
13021 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13022 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13023 // noescape blocks should not be retained by the method.
13024 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13025 continue;
John McCall31168b02011-06-15 23:02:42 +000013026 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000013027 }
13028 }
John McCall31168b02011-06-15 23:02:42 +000013029}
13030
13031/// Check a property assign to see if it's likely to cause a retain cycle.
13032void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13033 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000013034 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000013035 return;
13036
13037 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13038 diagnoseRetainCycle(*this, capturer, owner);
13039}
13040
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013041void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13042 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000013043 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013044 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013045
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013046 // Because we don't have an expression for the variable, we have to set the
13047 // location explicitly here.
13048 Owner.Loc = Var->getLocation();
13049 Owner.Range = Var->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +000013050
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000013051 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13052 diagnoseRetainCycle(*this, Capturer, Owner);
13053}
13054
Ted Kremenek9304da92012-12-21 08:04:28 +000013055static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13056 Expr *RHS, bool isProperty) {
13057 // Check if RHS is an Objective-C object literal, which also can get
13058 // immediately zapped in a weak reference. Note that we explicitly
13059 // allow ObjCStringLiterals, since those are designed to never really die.
13060 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013061
Ted Kremenek64873352012-12-21 22:46:35 +000013062 // This enum needs to match with the 'select' in
13063 // warn_objc_arc_literal_assign (off-by-1).
13064 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13065 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13066 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013067
13068 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000013069 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000013070 << (isProperty ? 0 : 1)
13071 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000013072
13073 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000013074}
13075
Ted Kremenekc1f014a2012-12-21 19:45:30 +000013076static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13077 Qualifiers::ObjCLifetime LT,
13078 Expr *RHS, bool isProperty) {
13079 // Strip off any implicit cast added to get to the one ARC-specific.
13080 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13081 if (cast->getCastKind() == CK_ARCConsumeObject) {
13082 S.Diag(Loc, diag::warn_arc_retained_assign)
13083 << (LT == Qualifiers::OCL_ExplicitNone)
13084 << (isProperty ? 0 : 1)
13085 << RHS->getSourceRange();
13086 return true;
13087 }
13088 RHS = cast->getSubExpr();
13089 }
13090
13091 if (LT == Qualifiers::OCL_Weak &&
13092 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13093 return true;
13094
13095 return false;
13096}
13097
Ted Kremenekb36234d2012-12-21 08:04:20 +000013098bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13099 QualType LHS, Expr *RHS) {
13100 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13101
13102 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13103 return false;
13104
13105 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13106 return true;
13107
13108 return false;
13109}
13110
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013111void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13112 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013113 QualType LHSType;
13114 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000013115 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013116 ObjCPropertyRefExpr *PRE
13117 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13118 if (PRE && !PRE->isImplicitProperty()) {
13119 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13120 if (PD)
13121 LHSType = PD->getType();
13122 }
Fangrui Song6907ce22018-07-30 19:24:48 +000013123
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013124 if (LHSType.isNull())
13125 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000013126
13127 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13128
13129 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013130 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000013131 getCurFunction()->markSafeWeakUse(LHS);
13132 }
13133
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013134 if (checkUnsafeAssigns(Loc, LHSType, RHS))
13135 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000013136
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013137 // FIXME. Check for other life times.
13138 if (LT != Qualifiers::OCL_None)
13139 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013140
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013141 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013142 if (PRE->isImplicitProperty())
13143 return;
13144 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13145 if (!PD)
13146 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013147
Bill Wendling44426052012-12-20 19:22:21 +000013148 unsigned Attributes = PD->getPropertyAttributes();
13149 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013150 // when 'assign' attribute was not explicitly specified
13151 // by user, ignore it and rely on property type itself
13152 // for lifetime info.
13153 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13154 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13155 LHSType->isObjCRetainableType())
13156 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000013157
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013158 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000013159 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013160 Diag(Loc, diag::warn_arc_retained_property_assign)
13161 << RHS->getSourceRange();
13162 return;
13163 }
13164 RHS = cast->getSubExpr();
13165 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000013166 }
Bill Wendling44426052012-12-20 19:22:21 +000013167 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000013168 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13169 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000013170 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013171 }
13172}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013173
13174//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13175
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013176static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13177 SourceLocation StmtLoc,
13178 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013179 // Do not warn if the body is a macro that expands to nothing, e.g:
13180 //
13181 // #define CALL(x)
13182 // if (condition)
13183 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013184 if (Body->hasLeadingEmptyMacro())
13185 return false;
13186
13187 // Get line numbers of statement and body.
13188 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000013189 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013190 &StmtLineInvalid);
13191 if (StmtLineInvalid)
13192 return false;
13193
13194 bool BodyLineInvalid;
13195 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13196 &BodyLineInvalid);
13197 if (BodyLineInvalid)
13198 return false;
13199
13200 // Warn if null statement and body are on the same line.
13201 if (StmtLine != BodyLine)
13202 return false;
13203
13204 return true;
13205}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013206
13207void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13208 const Stmt *Body,
13209 unsigned DiagID) {
13210 // Since this is a syntactic check, don't emit diagnostic for template
13211 // instantiations, this just adds noise.
13212 if (CurrentInstantiationScope)
13213 return;
13214
13215 // The body should be a null statement.
13216 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13217 if (!NBody)
13218 return;
13219
13220 // Do the usual checks.
13221 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13222 return;
13223
13224 Diag(NBody->getSemiLoc(), DiagID);
13225 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13226}
13227
13228void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13229 const Stmt *PossibleBody) {
13230 assert(!CurrentInstantiationScope); // Ensured by caller
13231
13232 SourceLocation StmtLoc;
13233 const Stmt *Body;
13234 unsigned DiagID;
13235 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13236 StmtLoc = FS->getRParenLoc();
13237 Body = FS->getBody();
13238 DiagID = diag::warn_empty_for_body;
13239 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13240 StmtLoc = WS->getCond()->getSourceRange().getEnd();
13241 Body = WS->getBody();
13242 DiagID = diag::warn_empty_while_body;
13243 } else
13244 return; // Neither `for' nor `while'.
13245
13246 // The body should be a null statement.
13247 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13248 if (!NBody)
13249 return;
13250
13251 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013252 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013253 return;
13254
13255 // Do the usual checks.
13256 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13257 return;
13258
13259 // `for(...);' and `while(...);' are popular idioms, so in order to keep
13260 // noise level low, emit diagnostics only if for/while is followed by a
13261 // CompoundStmt, e.g.:
13262 // for (int i = 0; i < n; i++);
13263 // {
13264 // a(i);
13265 // }
13266 // or if for/while is followed by a statement with more indentation
13267 // than for/while itself:
13268 // for (int i = 0; i < n; i++);
13269 // a(i);
13270 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13271 if (!ProbableTypo) {
13272 bool BodyColInvalid;
13273 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013274 PossibleBody->getBeginLoc(), &BodyColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013275 if (BodyColInvalid)
13276 return;
13277
13278 bool StmtColInvalid;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013279 unsigned StmtCol =
13280 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013281 if (StmtColInvalid)
13282 return;
13283
13284 if (BodyCol > StmtCol)
13285 ProbableTypo = true;
13286 }
13287
13288 if (ProbableTypo) {
13289 Diag(NBody->getSemiLoc(), DiagID);
13290 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13291 }
13292}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013293
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013294//===--- CHECK: Warn on self move with std::move. -------------------------===//
13295
13296/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13297void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13298 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013299 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13300 return;
13301
Richard Smith51ec0cf2017-02-21 01:17:38 +000013302 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013303 return;
13304
13305 // Strip parens and casts away.
13306 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13307 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13308
13309 // Check for a call expression
13310 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13311 if (!CE || CE->getNumArgs() != 1)
13312 return;
13313
13314 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000013315 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013316 return;
13317
13318 // Get argument from std::move
13319 RHSExpr = CE->getArg(0);
13320
13321 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13322 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13323
13324 // Two DeclRefExpr's, check that the decls are the same.
13325 if (LHSDeclRef && RHSDeclRef) {
13326 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13327 return;
13328 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13329 RHSDeclRef->getDecl()->getCanonicalDecl())
13330 return;
13331
13332 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13333 << LHSExpr->getSourceRange()
13334 << RHSExpr->getSourceRange();
13335 return;
13336 }
13337
13338 // Member variables require a different approach to check for self moves.
13339 // MemberExpr's are the same if every nested MemberExpr refers to the same
13340 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13341 // the base Expr's are CXXThisExpr's.
13342 const Expr *LHSBase = LHSExpr;
13343 const Expr *RHSBase = RHSExpr;
13344 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13345 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13346 if (!LHSME || !RHSME)
13347 return;
13348
13349 while (LHSME && RHSME) {
13350 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13351 RHSME->getMemberDecl()->getCanonicalDecl())
13352 return;
13353
13354 LHSBase = LHSME->getBase();
13355 RHSBase = RHSME->getBase();
13356 LHSME = dyn_cast<MemberExpr>(LHSBase);
13357 RHSME = dyn_cast<MemberExpr>(RHSBase);
13358 }
13359
13360 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13361 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13362 if (LHSDeclRef && RHSDeclRef) {
13363 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13364 return;
13365 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13366 RHSDeclRef->getDecl()->getCanonicalDecl())
13367 return;
13368
13369 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13370 << LHSExpr->getSourceRange()
13371 << RHSExpr->getSourceRange();
13372 return;
13373 }
13374
13375 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13376 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13377 << LHSExpr->getSourceRange()
13378 << RHSExpr->getSourceRange();
13379}
13380
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013381//===--- Layout compatibility ----------------------------------------------//
13382
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013383static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013384
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013385/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013386static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013387 // C++11 [dcl.enum] p8:
13388 // Two enumeration types are layout-compatible if they have the same
13389 // underlying type.
13390 return ED1->isComplete() && ED2->isComplete() &&
13391 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13392}
13393
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013394/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013395static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13396 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013397 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13398 return false;
13399
13400 if (Field1->isBitField() != Field2->isBitField())
13401 return false;
13402
13403 if (Field1->isBitField()) {
13404 // Make sure that the bit-fields are the same length.
13405 unsigned Bits1 = Field1->getBitWidthValue(C);
13406 unsigned Bits2 = Field2->getBitWidthValue(C);
13407
13408 if (Bits1 != Bits2)
13409 return false;
13410 }
13411
13412 return true;
13413}
13414
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013415/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013416/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013417static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13418 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013419 // If both records are C++ classes, check that base classes match.
13420 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13421 // If one of records is a CXXRecordDecl we are in C++ mode,
13422 // thus the other one is a CXXRecordDecl, too.
13423 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13424 // Check number of base classes.
13425 if (D1CXX->getNumBases() != D2CXX->getNumBases())
13426 return false;
13427
13428 // Check the base classes.
13429 for (CXXRecordDecl::base_class_const_iterator
13430 Base1 = D1CXX->bases_begin(),
13431 BaseEnd1 = D1CXX->bases_end(),
13432 Base2 = D2CXX->bases_begin();
13433 Base1 != BaseEnd1;
13434 ++Base1, ++Base2) {
13435 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13436 return false;
13437 }
13438 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13439 // If only RD2 is a C++ class, it should have zero base classes.
13440 if (D2CXX->getNumBases() > 0)
13441 return false;
13442 }
13443
13444 // Check the fields.
13445 RecordDecl::field_iterator Field2 = RD2->field_begin(),
13446 Field2End = RD2->field_end(),
13447 Field1 = RD1->field_begin(),
13448 Field1End = RD1->field_end();
13449 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13450 if (!isLayoutCompatible(C, *Field1, *Field2))
13451 return false;
13452 }
13453 if (Field1 != Field1End || Field2 != Field2End)
13454 return false;
13455
13456 return true;
13457}
13458
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013459/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013460/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013461static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13462 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013463 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013464 for (auto *Field2 : RD2->fields())
13465 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013466
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013467 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013468 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13469 I = UnmatchedFields.begin(),
13470 E = UnmatchedFields.end();
13471
13472 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013473 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013474 bool Result = UnmatchedFields.erase(*I);
13475 (void) Result;
13476 assert(Result);
13477 break;
13478 }
13479 }
13480 if (I == E)
13481 return false;
13482 }
13483
13484 return UnmatchedFields.empty();
13485}
13486
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013487static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13488 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013489 if (RD1->isUnion() != RD2->isUnion())
13490 return false;
13491
13492 if (RD1->isUnion())
13493 return isLayoutCompatibleUnion(C, RD1, RD2);
13494 else
13495 return isLayoutCompatibleStruct(C, RD1, RD2);
13496}
13497
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013498/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013499static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013500 if (T1.isNull() || T2.isNull())
13501 return false;
13502
13503 // C++11 [basic.types] p11:
13504 // If two types T1 and T2 are the same type, then T1 and T2 are
13505 // layout-compatible types.
13506 if (C.hasSameType(T1, T2))
13507 return true;
13508
13509 T1 = T1.getCanonicalType().getUnqualifiedType();
13510 T2 = T2.getCanonicalType().getUnqualifiedType();
13511
13512 const Type::TypeClass TC1 = T1->getTypeClass();
13513 const Type::TypeClass TC2 = T2->getTypeClass();
13514
13515 if (TC1 != TC2)
13516 return false;
13517
13518 if (TC1 == Type::Enum) {
13519 return isLayoutCompatible(C,
13520 cast<EnumType>(T1)->getDecl(),
13521 cast<EnumType>(T2)->getDecl());
13522 } else if (TC1 == Type::Record) {
13523 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13524 return false;
13525
13526 return isLayoutCompatible(C,
13527 cast<RecordType>(T1)->getDecl(),
13528 cast<RecordType>(T2)->getDecl());
13529 }
13530
13531 return false;
13532}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013533
13534//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13535
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013536/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013537///
13538/// \param TypeExpr Type tag expression, as it appears in user's code.
13539///
13540/// \param VD Declaration of an identifier that appears in a type tag.
13541///
13542/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013543static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13544 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013545 while(true) {
13546 if (!TypeExpr)
13547 return false;
13548
13549 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13550
13551 switch (TypeExpr->getStmtClass()) {
13552 case Stmt::UnaryOperatorClass: {
13553 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13554 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13555 TypeExpr = UO->getSubExpr();
13556 continue;
13557 }
13558 return false;
13559 }
13560
13561 case Stmt::DeclRefExprClass: {
13562 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13563 *VD = DRE->getDecl();
13564 return true;
13565 }
13566
13567 case Stmt::IntegerLiteralClass: {
13568 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13569 llvm::APInt MagicValueAPInt = IL->getValue();
13570 if (MagicValueAPInt.getActiveBits() <= 64) {
13571 *MagicValue = MagicValueAPInt.getZExtValue();
13572 return true;
13573 } else
13574 return false;
13575 }
13576
13577 case Stmt::BinaryConditionalOperatorClass:
13578 case Stmt::ConditionalOperatorClass: {
13579 const AbstractConditionalOperator *ACO =
13580 cast<AbstractConditionalOperator>(TypeExpr);
13581 bool Result;
13582 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13583 if (Result)
13584 TypeExpr = ACO->getTrueExpr();
13585 else
13586 TypeExpr = ACO->getFalseExpr();
13587 continue;
13588 }
13589 return false;
13590 }
13591
13592 case Stmt::BinaryOperatorClass: {
13593 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13594 if (BO->getOpcode() == BO_Comma) {
13595 TypeExpr = BO->getRHS();
13596 continue;
13597 }
13598 return false;
13599 }
13600
13601 default:
13602 return false;
13603 }
13604 }
13605}
13606
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013607/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013608///
13609/// \param TypeExpr Expression that specifies a type tag.
13610///
13611/// \param MagicValues Registered magic values.
13612///
13613/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13614/// kind.
13615///
13616/// \param TypeInfo Information about the corresponding C type.
13617///
13618/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013619static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013620 const IdentifierInfo *ArgumentKind,
13621 const Expr *TypeExpr, const ASTContext &Ctx,
13622 const llvm::DenseMap<Sema::TypeTagMagicValue,
13623 Sema::TypeTagData> *MagicValues,
13624 bool &FoundWrongKind,
13625 Sema::TypeTagData &TypeInfo) {
13626 FoundWrongKind = false;
13627
13628 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000013629 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013630
13631 uint64_t MagicValue;
13632
13633 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13634 return false;
13635
13636 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000013637 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013638 if (I->getArgumentKind() != ArgumentKind) {
13639 FoundWrongKind = true;
13640 return false;
13641 }
13642 TypeInfo.Type = I->getMatchingCType();
13643 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13644 TypeInfo.MustBeNull = I->getMustBeNull();
13645 return true;
13646 }
13647 return false;
13648 }
13649
13650 if (!MagicValues)
13651 return false;
13652
13653 llvm::DenseMap<Sema::TypeTagMagicValue,
13654 Sema::TypeTagData>::const_iterator I =
13655 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13656 if (I == MagicValues->end())
13657 return false;
13658
13659 TypeInfo = I->second;
13660 return true;
13661}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013662
13663void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13664 uint64_t MagicValue, QualType Type,
13665 bool LayoutCompatible,
13666 bool MustBeNull) {
13667 if (!TypeTagForDatatypeMagicValues)
13668 TypeTagForDatatypeMagicValues.reset(
13669 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13670
13671 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13672 (*TypeTagForDatatypeMagicValues)[Magic] =
13673 TypeTagData(Type, LayoutCompatible, MustBeNull);
13674}
13675
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013676static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013677 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13678 if (!BT1)
13679 return false;
13680
13681 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13682 if (!BT2)
13683 return false;
13684
13685 BuiltinType::Kind T1Kind = BT1->getKind();
13686 BuiltinType::Kind T2Kind = BT2->getKind();
13687
13688 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
13689 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
13690 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13691 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13692}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013693
13694void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013695 const ArrayRef<const Expr *> ExprArgs,
13696 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013697 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13698 bool IsPointerAttr = Attr->getIsPointer();
13699
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013700 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000013701 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13702 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013703 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000013704 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013705 return;
13706 }
Joel E. Denny81508102018-03-13 14:51:22 +000013707 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013708 bool FoundWrongKind;
13709 TypeTagData TypeInfo;
13710 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13711 TypeTagForDatatypeMagicValues.get(),
13712 FoundWrongKind, TypeInfo)) {
13713 if (FoundWrongKind)
13714 Diag(TypeTagExpr->getExprLoc(),
13715 diag::warn_type_tag_for_datatype_wrong_kind)
13716 << TypeTagExpr->getSourceRange();
13717 return;
13718 }
13719
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013720 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000013721 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13722 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013723 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000013724 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013725 return;
13726 }
Joel E. Denny81508102018-03-13 14:51:22 +000013727 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013728 if (IsPointerAttr) {
13729 // Skip implicit cast of pointer to `void *' (as a function argument).
13730 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000013731 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000013732 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013733 ArgumentExpr = ICE->getSubExpr();
13734 }
13735 QualType ArgumentType = ArgumentExpr->getType();
13736
13737 // Passing a `void*' pointer shouldn't trigger a warning.
13738 if (IsPointerAttr && ArgumentType->isVoidPointerType())
13739 return;
13740
13741 if (TypeInfo.MustBeNull) {
13742 // Type tag with matching void type requires a null pointer.
13743 if (!ArgumentExpr->isNullPointerConstant(Context,
13744 Expr::NPC_ValueDependentIsNotNull)) {
13745 Diag(ArgumentExpr->getExprLoc(),
13746 diag::warn_type_safety_null_pointer_required)
13747 << ArgumentKind->getName()
13748 << ArgumentExpr->getSourceRange()
13749 << TypeTagExpr->getSourceRange();
13750 }
13751 return;
13752 }
13753
13754 QualType RequiredType = TypeInfo.Type;
13755 if (IsPointerAttr)
13756 RequiredType = Context.getPointerType(RequiredType);
13757
13758 bool mismatch = false;
13759 if (!TypeInfo.LayoutCompatible) {
13760 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13761
13762 // C++11 [basic.fundamental] p1:
13763 // Plain char, signed char, and unsigned char are three distinct types.
13764 //
13765 // But we treat plain `char' as equivalent to `signed char' or `unsigned
13766 // char' depending on the current char signedness mode.
13767 if (mismatch)
13768 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13769 RequiredType->getPointeeType())) ||
13770 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13771 mismatch = false;
13772 } else
13773 if (IsPointerAttr)
13774 mismatch = !isLayoutCompatible(Context,
13775 ArgumentType->getPointeeType(),
13776 RequiredType->getPointeeType());
13777 else
13778 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13779
13780 if (mismatch)
13781 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000013782 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013783 << TypeInfo.LayoutCompatible << RequiredType
13784 << ArgumentExpr->getSourceRange()
13785 << TypeTagExpr->getSourceRange();
13786}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013787
13788void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13789 CharUnits Alignment) {
13790 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13791}
13792
13793void Sema::DiagnoseMisalignedMembers() {
13794 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000013795 const NamedDecl *ND = m.RD;
13796 if (ND->getName().empty()) {
13797 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13798 ND = TD;
13799 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013800 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000013801 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013802 }
13803 MisalignedMembers.clear();
13804}
13805
13806void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013807 E = E->IgnoreParens();
13808 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013809 return;
13810 if (isa<UnaryOperator>(E) &&
13811 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13812 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13813 if (isa<MemberExpr>(Op)) {
13814 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13815 MisalignedMember(Op));
13816 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013817 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000013818 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13819 Context.getTypeAlignInChars(
13820 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013821 MisalignedMembers.erase(MA);
13822 }
13823 }
13824}
13825
13826void Sema::RefersToMemberWithReducedAlignment(
13827 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000013828 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13829 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013830 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013831 if (!ME)
13832 return;
13833
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000013834 // No need to check expressions with an __unaligned-qualified type.
13835 if (E->getType().getQualifiers().hasUnaligned())
13836 return;
13837
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013838 // For a chain of MemberExpr like "a.b.c.d" this list
13839 // will keep FieldDecl's like [d, c, b].
13840 SmallVector<FieldDecl *, 4> ReverseMemberChain;
13841 const MemberExpr *TopME = nullptr;
13842 bool AnyIsPacked = false;
13843 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013844 QualType BaseType = ME->getBase()->getType();
13845 if (ME->isArrow())
13846 BaseType = BaseType->getPointeeType();
13847 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000013848 if (RD->isInvalidDecl())
13849 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013850
13851 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013852 auto *FD = dyn_cast<FieldDecl>(MD);
13853 // We do not care about non-data members.
13854 if (!FD || FD->isInvalidDecl())
13855 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013856
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013857 AnyIsPacked =
13858 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13859 ReverseMemberChain.push_back(FD);
13860
13861 TopME = ME;
13862 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13863 } while (ME);
13864 assert(TopME && "We did not compute a topmost MemberExpr!");
13865
13866 // Not the scope of this diagnostic.
13867 if (!AnyIsPacked)
13868 return;
13869
13870 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13871 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13872 // TODO: The innermost base of the member expression may be too complicated.
13873 // For now, just disregard these cases. This is left for future
13874 // improvement.
13875 if (!DRE && !isa<CXXThisExpr>(TopBase))
13876 return;
13877
13878 // Alignment expected by the whole expression.
13879 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13880
13881 // No need to do anything else with this case.
13882 if (ExpectedAlignment.isOne())
13883 return;
13884
13885 // Synthesize offset of the whole access.
13886 CharUnits Offset;
13887 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13888 I++) {
13889 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13890 }
13891
13892 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13893 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13894 ReverseMemberChain.back()->getParent()->getTypeForDecl());
13895
13896 // The base expression of the innermost MemberExpr may give
13897 // stronger guarantees than the class containing the member.
13898 if (DRE && !TopME->isArrow()) {
13899 const ValueDecl *VD = DRE->getDecl();
13900 if (!VD->getType()->isReferenceType())
13901 CompleteObjectAlignment =
13902 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13903 }
13904
13905 // Check if the synthesized offset fulfills the alignment.
13906 if (Offset % ExpectedAlignment != 0 ||
13907 // It may fulfill the offset it but the effective alignment may still be
13908 // lower than the expected expression alignment.
13909 CompleteObjectAlignment < ExpectedAlignment) {
13910 // If this happens, we want to determine a sensible culprit of this.
13911 // Intuitively, watching the chain of member expressions from right to
13912 // left, we start with the required alignment (as required by the field
13913 // type) but some packed attribute in that chain has reduced the alignment.
13914 // It may happen that another packed structure increases it again. But if
13915 // we are here such increase has not been enough. So pointing the first
13916 // FieldDecl that either is packed or else its RecordDecl is,
13917 // seems reasonable.
13918 FieldDecl *FD = nullptr;
13919 CharUnits Alignment;
13920 for (FieldDecl *FDI : ReverseMemberChain) {
13921 if (FDI->hasAttr<PackedAttr>() ||
13922 FDI->getParent()->hasAttr<PackedAttr>()) {
13923 FD = FDI;
13924 Alignment = std::min(
13925 Context.getTypeAlignInChars(FD->getType()),
13926 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13927 break;
13928 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013929 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013930 assert(FD && "We did not find a packed FieldDecl!");
13931 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013932 }
13933}
13934
13935void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13936 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013937
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013938 RefersToMemberWithReducedAlignment(
13939 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13940 _2, _3, _4));
13941}