blob: 4660ed55aeea9edd24d8bcb38e45837c285f948e [file] [log] [blame]
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000015#include "clang/AST/APValue.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000017#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
Ken Dyck40775002010-01-11 17:06:35 +000019#include "clang/AST/CharUnits.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000020#include "clang/AST/Decl.h"
21#include "clang/AST/DeclBase.h"
John McCall28a0cf72010-08-25 07:42:41 +000022#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000024#include "clang/AST/DeclarationName.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000026#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000027#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000028#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000029#include "clang/AST/ExprOpenMP.h"
Tim Northover314fbfa2018-11-02 13:14:11 +000030#include "clang/AST/FormatString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000031#include "clang/AST/NSAPI.h"
Akira Hatanaka2be04412018-04-17 19:13:41 +000032#include "clang/AST/NonTrivialTypeVisitor.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000033#include "clang/AST/OperationKinds.h"
34#include "clang/AST/Stmt.h"
35#include "clang/AST/TemplateBase.h"
36#include "clang/AST/Type.h"
37#include "clang/AST/TypeLoc.h"
38#include "clang/AST/UnresolvedSet.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000039#include "clang/Basic/AddressSpaces.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000040#include "clang/Basic/CharInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000041#include "clang/Basic/Diagnostic.h"
42#include "clang/Basic/IdentifierTable.h"
43#include "clang/Basic/LLVM.h"
44#include "clang/Basic/LangOptions.h"
45#include "clang/Basic/OpenCLOptions.h"
46#include "clang/Basic/OperatorKinds.h"
47#include "clang/Basic/PartialDiagnostic.h"
48#include "clang/Basic/SourceLocation.h"
49#include "clang/Basic/SourceManager.h"
50#include "clang/Basic/Specifiers.h"
Yaxun Liu39195062017-08-04 18:16:31 +000051#include "clang/Basic/SyncScope.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000052#include "clang/Basic/TargetBuiltins.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000053#include "clang/Basic/TargetCXXABI.h"
Nate Begeman4904e322010-06-08 02:47:44 +000054#include "clang/Basic/TargetInfo.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000055#include "clang/Basic/TypeTraits.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000056#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000058#include "clang/Sema/Lookup.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000059#include "clang/Sema/Ownership.h"
60#include "clang/Sema/Scope.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000061#include "clang/Sema/ScopeInfo.h"
62#include "clang/Sema/Sema.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000063#include "clang/Sema/SemaInternal.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000064#include "llvm/ADT/APFloat.h"
65#include "llvm/ADT/APInt.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/ArrayRef.h"
68#include "llvm/ADT/DenseMap.h"
69#include "llvm/ADT/FoldingSet.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000072#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000073#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000074#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000075#include "llvm/ADT/SmallString.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000076#include "llvm/ADT/SmallVector.h"
77#include "llvm/ADT/StringRef.h"
78#include "llvm/ADT/StringSwitch.h"
79#include "llvm/ADT/Triple.h"
80#include "llvm/Support/AtomicOrdering.h"
81#include "llvm/Support/Casting.h"
82#include "llvm/Support/Compiler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000083#include "llvm/Support/ConvertUTF.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000084#include "llvm/Support/ErrorHandling.h"
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +000085#include "llvm/Support/Format.h"
86#include "llvm/Support/Locale.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000087#include "llvm/Support/MathExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000088#include "llvm/Support/raw_ostream.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000089#include <algorithm>
90#include <cassert>
91#include <cstddef>
92#include <cstdint>
93#include <functional>
94#include <limits>
95#include <string>
96#include <tuple>
97#include <utility>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000098
Chris Lattnerb87b1b32007-08-10 20:18:51 +000099using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +0000100using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000101
Chris Lattnera26fb342009-02-18 17:49:48 +0000102SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
103 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +0000104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
105 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +0000106}
107
John McCallbebede42011-02-26 05:39:39 +0000108/// Checks that a call expression's argument count is the desired number.
109/// This is useful when doing custom type-checking. Returns true on error.
110static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
111 unsigned argCount = call->getNumArgs();
112 if (argCount == desiredArgCount) return false;
113
114 if (argCount < desiredArgCount)
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
116 << 0 /*function call*/ << desiredArgCount << argCount
117 << call->getSourceRange();
John McCallbebede42011-02-26 05:39:39 +0000118
119 // Highlight all the excess arguments.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000121 call->getArg(argCount - 1)->getEndLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +0000122
John McCallbebede42011-02-26 05:39:39 +0000123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
124 << 0 /*function call*/ << desiredArgCount << argCount
125 << call->getArg(1)->getSourceRange();
126}
127
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000128/// Check that the first argument to __builtin_annotation is an integer
129/// and the second argument is a non-wide string literal.
130static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
131 if (checkArgCount(S, TheCall, 2))
132 return true;
133
134 // First argument should be an integer.
135 Expr *ValArg = TheCall->getArg(0);
136 QualType Ty = ValArg->getType();
137 if (!Ty->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000138 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
139 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000140 return true;
141 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000142
143 // Second argument should be a constant string.
144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
146 if (!Literal || !Literal->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
148 << StrArg->getSourceRange();
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000149 return true;
150 }
151
152 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000153 return false;
154}
155
Reid Kleckner30701ed2017-09-05 20:27:35 +0000156static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
157 // We need at least one argument.
158 if (TheCall->getNumArgs() < 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
Reid Kleckner30701ed2017-09-05 20:27:35 +0000160 << 0 << 1 << TheCall->getNumArgs()
161 << TheCall->getCallee()->getSourceRange();
162 return true;
163 }
164
165 // All arguments should be wide string literals.
166 for (Expr *Arg : TheCall->arguments()) {
167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168 if (!Literal || !Literal->isWide()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
Reid Kleckner30701ed2017-09-05 20:27:35 +0000170 << Arg->getSourceRange();
171 return true;
172 }
173 }
174
175 return false;
176}
177
Richard Smith6cbd65d2013-07-11 02:27:57 +0000178/// Check that the argument to __builtin_addressof is a glvalue, and set the
179/// result type to the corresponding pointer type.
180static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
181 if (checkArgCount(S, TheCall, 1))
182 return true;
183
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000184 ExprResult Arg(TheCall->getArg(0));
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000186 if (ResultType.isNull())
187 return true;
188
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000189 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000190 TheCall->setType(ResultType);
191 return false;
192}
193
John McCall03107a42015-10-29 20:48:01 +0000194static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
195 if (checkArgCount(S, TheCall, 3))
196 return true;
197
198 // First two arguments should be integers.
199 for (unsigned I = 0; I < 2; ++I) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000200 ExprResult Arg = TheCall->getArg(I);
201 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000202 if (!Ty->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000203 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
Erich Keane1d73d1a2018-06-13 13:25:11 +0000204 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000205 return true;
206 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000207 InitializedEntity Entity = InitializedEntity::InitializeParameter(
208 S.getASTContext(), Ty, /*consume*/ false);
209 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
210 if (Arg.isInvalid())
211 return true;
212 TheCall->setArg(I, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000213 }
214
215 // Third argument should be a pointer to a non-const integer.
216 // IRGen correctly handles volatile, restrict, and address spaces, and
217 // the other qualifiers aren't possible.
218 {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000219 ExprResult Arg = TheCall->getArg(2);
220 QualType Ty = Arg.get()->getType();
John McCall03107a42015-10-29 20:48:01 +0000221 const auto *PtrTy = Ty->getAs<PointerType>();
222 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
223 !PtrTy->getPointeeType().isConstQualified())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000224 S.Diag(Arg.get()->getBeginLoc(),
Erich Keane1d73d1a2018-06-13 13:25:11 +0000225 diag::err_overflow_builtin_must_be_ptr_int)
226 << Ty << Arg.get()->getSourceRange();
John McCall03107a42015-10-29 20:48:01 +0000227 return true;
228 }
Erich Keane1d73d1a2018-06-13 13:25:11 +0000229 InitializedEntity Entity = InitializedEntity::InitializeParameter(
230 S.getASTContext(), Ty, /*consume*/ false);
231 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
232 if (Arg.isInvalid())
233 return true;
234 TheCall->setArg(2, Arg.get());
John McCall03107a42015-10-29 20:48:01 +0000235 }
John McCall03107a42015-10-29 20:48:01 +0000236 return false;
237}
238
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000239static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
Fangrui Song99337e22018-07-20 08:19:20 +0000240 CallExpr *TheCall, unsigned SizeIdx,
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000241 unsigned DstSizeIdx,
242 StringRef LikelyMacroName) {
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000243 if (TheCall->getNumArgs() <= SizeIdx ||
244 TheCall->getNumArgs() <= DstSizeIdx)
245 return;
246
247 const Expr *SizeArg = TheCall->getArg(SizeIdx);
248 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
249
250 llvm::APSInt Size, DstSize;
251
252 // find out if both sizes are known at compile time
253 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
254 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
255 return;
256
257 if (Size.ule(DstSize))
258 return;
259
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000260 // Confirmed overflow, so generate the diagnostic.
261 StringRef FunctionName = FDecl->getName();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000262 SourceLocation SL = TheCall->getBeginLoc();
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000263 SourceManager &SM = S.getSourceManager();
264 // If we're in an expansion of a macro whose name corresponds to this builtin,
265 // use the simple macro name and location.
266 if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) ==
267 LikelyMacroName) {
268 FunctionName = LikelyMacroName;
269 SL = SM.getImmediateMacroCallerLoc(SL);
270 }
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000271
Erik Pilkingtonf85e3912018-09-06 17:19:33 +0000272 S.Diag(SL, diag::warn_memcpy_chk_overflow)
273 << FunctionName << DstSize.toString(/*Radix=*/10)
274 << Size.toString(/*Radix=*/10);
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000275}
276
Peter Collingbournef7706832014-12-12 23:41:25 +0000277static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
278 if (checkArgCount(S, BuiltinCall, 2))
279 return true;
280
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000281 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
Peter Collingbournef7706832014-12-12 23:41:25 +0000282 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
283 Expr *Call = BuiltinCall->getArg(0);
284 Expr *Chain = BuiltinCall->getArg(1);
285
286 if (Call->getStmtClass() != Stmt::CallExprClass) {
287 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
288 << Call->getSourceRange();
289 return true;
290 }
291
292 auto CE = cast<CallExpr>(Call);
293 if (CE->getCallee()->getType()->isBlockPointerType()) {
294 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
295 << Call->getSourceRange();
296 return true;
297 }
298
299 const Decl *TargetDecl = CE->getCalleeDecl();
300 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
301 if (FD->getBuiltinID()) {
302 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
303 << Call->getSourceRange();
304 return true;
305 }
306
307 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
308 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
309 << Call->getSourceRange();
310 return true;
311 }
312
313 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
314 if (ChainResult.isInvalid())
315 return true;
316 if (!ChainResult.get()->getType()->isPointerType()) {
317 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
318 << Chain->getSourceRange();
319 return true;
320 }
321
David Majnemerced8bdf2015-02-25 17:36:15 +0000322 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000323 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
324 QualType BuiltinTy = S.Context.getFunctionType(
325 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
326 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
327
328 Builtin =
329 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
330
331 BuiltinCall->setType(CE->getType());
332 BuiltinCall->setValueKind(CE->getValueKind());
333 BuiltinCall->setObjectKind(CE->getObjectKind());
334 BuiltinCall->setCallee(Builtin);
335 BuiltinCall->setArg(1, ChainResult.get());
336
337 return false;
338}
339
Reid Kleckner1d59f992015-01-22 01:36:17 +0000340static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
341 Scope::ScopeFlags NeededScopeFlags,
342 unsigned DiagID) {
343 // Scopes aren't available during instantiation. Fortunately, builtin
344 // functions cannot be template args so they cannot be formed through template
345 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000346 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000347 return false;
348
349 Scope *S = SemaRef.getCurScope();
350 while (S && !S->isSEHExceptScope())
351 S = S->getParent();
352 if (!S || !(S->getFlags() & NeededScopeFlags)) {
353 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
354 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
355 << DRE->getDecl()->getIdentifier();
356 return true;
357 }
358
359 return false;
360}
361
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000362static inline bool isBlockPointer(Expr *Arg) {
363 return Arg->getType()->isBlockPointerType();
364}
365
366/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
367/// void*, which is a requirement of device side enqueue.
368static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
369 const BlockPointerType *BPT =
370 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
371 ArrayRef<QualType> Params =
372 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
373 unsigned ArgCounter = 0;
374 bool IllegalParams = false;
375 // Iterate through the block parameters until either one is found that is not
376 // a local void*, or the block is valid.
377 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
378 I != E; ++I, ++ArgCounter) {
379 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
380 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
381 LangAS::opencl_local) {
382 // Get the location of the error. If a block literal has been passed
383 // (BlockExpr) then we can point straight to the offending argument,
384 // else we just point to the variable reference.
385 SourceLocation ErrorLoc;
386 if (isa<BlockExpr>(BlockArg)) {
387 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000388 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000389 } else if (isa<DeclRefExpr>(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000390 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000391 }
392 S.Diag(ErrorLoc,
393 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
394 IllegalParams = true;
395 }
396 }
397
398 return IllegalParams;
399}
400
Joey Gouly84ae3362017-07-31 15:15:59 +0000401static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
402 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000403 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
404 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
Joey Gouly84ae3362017-07-31 15:15:59 +0000405 return true;
406 }
407 return false;
408}
409
Joey Goulyfa76b492017-08-01 13:27:09 +0000410static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
411 if (checkArgCount(S, TheCall, 2))
412 return true;
413
414 if (checkOpenCLSubgroupExt(S, TheCall))
415 return true;
416
417 // First argument is an ndrange_t type.
418 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000419 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000420 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000421 << TheCall->getDirectCallee() << "'ndrange_t'";
422 return true;
423 }
424
425 Expr *BlockArg = TheCall->getArg(1);
426 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000427 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Goulyfa76b492017-08-01 13:27:09 +0000428 << TheCall->getDirectCallee() << "block";
429 return true;
430 }
431 return checkOpenCLBlockArgs(S, BlockArg);
432}
433
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000434/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
435/// get_kernel_work_group_size
436/// and get_kernel_preferred_work_group_size_multiple builtin functions.
437static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
438 if (checkArgCount(S, TheCall, 1))
439 return true;
440
441 Expr *BlockArg = TheCall->getArg(0);
442 if (!isBlockPointer(BlockArg)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000443 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000444 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000445 return true;
446 }
447 return checkOpenCLBlockArgs(S, BlockArg);
448}
449
Simon Pilgrim2c518802017-03-30 14:13:19 +0000450/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000451static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
452 const QualType &IntType);
453
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000454static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000455 unsigned Start, unsigned End) {
456 bool IllegalParams = false;
457 for (unsigned I = Start; I <= End; ++I)
458 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
459 S.Context.getSizeType());
460 return IllegalParams;
461}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000462
463/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
464/// 'local void*' parameter of passed block.
465static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
466 Expr *BlockArg,
467 unsigned NumNonVarArgs) {
468 const BlockPointerType *BPT =
469 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
470 unsigned NumBlockParams =
471 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
472 unsigned TotalNumArgs = TheCall->getNumArgs();
473
474 // For each argument passed to the block, a corresponding uint needs to
475 // be passed to describe the size of the local memory.
476 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000477 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000478 diag::err_opencl_enqueue_kernel_local_size_args);
479 return true;
480 }
481
482 // Check that the sizes of the local memory are specified by integers.
483 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
484 TotalNumArgs - 1);
485}
486
487/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
488/// overload formats specified in Table 6.13.17.1.
489/// int enqueue_kernel(queue_t queue,
490/// kernel_enqueue_flags_t flags,
491/// const ndrange_t ndrange,
492/// void (^block)(void))
493/// int enqueue_kernel(queue_t queue,
494/// kernel_enqueue_flags_t flags,
495/// const ndrange_t ndrange,
496/// uint num_events_in_wait_list,
497/// clk_event_t *event_wait_list,
498/// clk_event_t *event_ret,
499/// void (^block)(void))
500/// int enqueue_kernel(queue_t queue,
501/// kernel_enqueue_flags_t flags,
502/// const ndrange_t ndrange,
503/// void (^block)(local void*, ...),
504/// uint size0, ...)
505/// int enqueue_kernel(queue_t queue,
506/// kernel_enqueue_flags_t flags,
507/// const ndrange_t ndrange,
508/// uint num_events_in_wait_list,
509/// clk_event_t *event_wait_list,
510/// clk_event_t *event_ret,
511/// void (^block)(local void*, ...),
512/// uint size0, ...)
513static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
514 unsigned NumArgs = TheCall->getNumArgs();
515
516 if (NumArgs < 4) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000517 S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000518 return true;
519 }
520
521 Expr *Arg0 = TheCall->getArg(0);
522 Expr *Arg1 = TheCall->getArg(1);
523 Expr *Arg2 = TheCall->getArg(2);
524 Expr *Arg3 = TheCall->getArg(3);
525
526 // First argument always needs to be a queue_t type.
527 if (!Arg0->getType()->isQueueT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000528 S.Diag(TheCall->getArg(0)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000529 diag::err_opencl_builtin_expected_type)
530 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000531 return true;
532 }
533
534 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
535 if (!Arg1->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000536 S.Diag(TheCall->getArg(1)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000537 diag::err_opencl_builtin_expected_type)
538 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000539 return true;
540 }
541
542 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000543 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000544 S.Diag(TheCall->getArg(2)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000545 diag::err_opencl_builtin_expected_type)
546 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000547 return true;
548 }
549
550 // With four arguments, there is only one form that the function could be
551 // called in: no events and no variable arguments.
552 if (NumArgs == 4) {
553 // check that the last argument is the right block type.
554 if (!isBlockPointer(Arg3)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000555 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000556 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000557 return true;
558 }
559 // we have a block type, check the prototype
560 const BlockPointerType *BPT =
561 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
562 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000563 S.Diag(Arg3->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000564 diag::err_opencl_enqueue_kernel_blocks_no_args);
565 return true;
566 }
567 return false;
568 }
569 // we can have block + varargs.
570 if (isBlockPointer(Arg3))
571 return (checkOpenCLBlockArgs(S, Arg3) ||
572 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
573 // last two cases with either exactly 7 args or 7 args and varargs.
574 if (NumArgs >= 7) {
575 // check common block argument.
576 Expr *Arg6 = TheCall->getArg(6);
577 if (!isBlockPointer(Arg6)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000578 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
Joey Gouly6b03d952017-07-04 11:50:23 +0000579 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000580 return true;
581 }
582 if (checkOpenCLBlockArgs(S, Arg6))
583 return true;
584
585 // Forth argument has to be any integer type.
586 if (!Arg3->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000587 S.Diag(TheCall->getArg(3)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000588 diag::err_opencl_builtin_expected_type)
589 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000590 return true;
591 }
592 // check remaining common arguments.
593 Expr *Arg4 = TheCall->getArg(4);
594 Expr *Arg5 = TheCall->getArg(5);
595
Anastasia Stulova2b461202016-11-14 15:34:01 +0000596 // Fifth argument is always passed as a pointer to clk_event_t.
597 if (!Arg4->isNullPointerConstant(S.Context,
598 Expr::NPC_ValueDependentIsNotNull) &&
599 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000600 S.Diag(TheCall->getArg(4)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000601 diag::err_opencl_builtin_expected_type)
602 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000603 << S.Context.getPointerType(S.Context.OCLClkEventTy);
604 return true;
605 }
606
Anastasia Stulova2b461202016-11-14 15:34:01 +0000607 // Sixth argument is always passed as a pointer to clk_event_t.
608 if (!Arg5->isNullPointerConstant(S.Context,
609 Expr::NPC_ValueDependentIsNotNull) &&
610 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000611 Arg5->getType()->getPointeeType()->isClkEventT())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000612 S.Diag(TheCall->getArg(5)->getBeginLoc(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000613 diag::err_opencl_builtin_expected_type)
614 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000615 << S.Context.getPointerType(S.Context.OCLClkEventTy);
616 return true;
617 }
618
619 if (NumArgs == 7)
620 return false;
621
622 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
623 }
624
625 // None of the specific case has been detected, give generic error
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000626 S.Diag(TheCall->getBeginLoc(),
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000627 diag::err_opencl_enqueue_kernel_incorrect_args);
628 return true;
629}
630
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000631/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000632static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000633 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000634}
635
636/// Returns true if pipe element type is different from the pointer.
637static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
638 const Expr *Arg0 = Call->getArg(0);
639 // First argument type should always be pipe.
640 if (!Arg0->getType()->isPipeType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000641 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000642 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000643 return true;
644 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000645 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000646 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
647 // Validates the access qualifier is compatible with the call.
648 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
649 // read_only and write_only, and assumed to be read_only if no qualifier is
650 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000651 switch (Call->getDirectCallee()->getBuiltinID()) {
652 case Builtin::BIread_pipe:
653 case Builtin::BIreserve_read_pipe:
654 case Builtin::BIcommit_read_pipe:
655 case Builtin::BIwork_group_reserve_read_pipe:
656 case Builtin::BIsub_group_reserve_read_pipe:
657 case Builtin::BIwork_group_commit_read_pipe:
658 case Builtin::BIsub_group_commit_read_pipe:
659 if (!(!AccessQual || AccessQual->isReadOnly())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000660 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000661 diag::err_opencl_builtin_pipe_invalid_access_modifier)
662 << "read_only" << Arg0->getSourceRange();
663 return true;
664 }
665 break;
666 case Builtin::BIwrite_pipe:
667 case Builtin::BIreserve_write_pipe:
668 case Builtin::BIcommit_write_pipe:
669 case Builtin::BIwork_group_reserve_write_pipe:
670 case Builtin::BIsub_group_reserve_write_pipe:
671 case Builtin::BIwork_group_commit_write_pipe:
672 case Builtin::BIsub_group_commit_write_pipe:
673 if (!(AccessQual && AccessQual->isWriteOnly())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000674 S.Diag(Arg0->getBeginLoc(),
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000675 diag::err_opencl_builtin_pipe_invalid_access_modifier)
676 << "write_only" << Arg0->getSourceRange();
677 return true;
678 }
679 break;
680 default:
681 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000682 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000683 return false;
684}
685
686/// Returns true if pipe element type is different from the pointer.
687static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
688 const Expr *Arg0 = Call->getArg(0);
689 const Expr *ArgIdx = Call->getArg(Idx);
690 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000691 const QualType EltTy = PipeTy->getElementType();
692 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000693 // The Idx argument should be a pointer and the type of the pointer and
694 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000695 if (!ArgTy ||
696 !S.Context.hasSameType(
697 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000698 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000699 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000700 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000701 return true;
702 }
703 return false;
704}
705
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000706// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000707// \param S Reference to the semantic analyzer.
708// \param Call A pointer to the builtin call.
709// \return True if a semantic error has been found, false otherwise.
710static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000711 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
712 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000713 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000714 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000715 if (checkOpenCLPipeArg(S, Call))
716 return true;
717 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000718 // read/write_pipe(pipe T, T*).
719 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000720 if (checkOpenCLPipePacketType(S, Call, 1))
721 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000722 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000723
724 case 4: {
725 if (checkOpenCLPipeArg(S, Call))
726 return true;
727 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000728 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
729 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000730 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000731 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000732 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000733 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000734 return true;
735 }
736
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000737 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000738 const Expr *Arg2 = Call->getArg(2);
739 if (!Arg2->getType()->isIntegerType() &&
740 !Arg2->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000741 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000742 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000743 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000744 return true;
745 }
746
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000747 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000748 if (checkOpenCLPipePacketType(S, Call, 3))
749 return true;
750 } break;
751 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000752 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000753 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000754 return true;
755 }
756
757 return false;
758}
759
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000760// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000761// /_}reserve_{read/write}_pipe
762// \param S Reference to the semantic analyzer.
763// \param Call The call to the builtin function to be analyzed.
764// \return True if a semantic error was found, false otherwise.
765static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
766 if (checkArgCount(S, Call, 2))
767 return true;
768
769 if (checkOpenCLPipeArg(S, Call))
770 return true;
771
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000772 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000773 if (!Call->getArg(1)->getType()->isIntegerType() &&
774 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000775 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000776 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000777 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000778 return true;
779 }
780
Joey Gouly922ca232017-08-09 14:52:47 +0000781 // Since return type of reserve_read/write_pipe built-in function is
Aaron Ballman68d50642018-06-19 14:53:20 +0000782 // reserve_id_t, which is not defined in the builtin def file , we used int
783 // as return type and need to override the return type of these functions.
784 Call->setType(S.Context.OCLReserveIDTy);
785
786 return false;
787}
788
789// Performs a semantic analysis on {work_group_/sub_group_
790// /_}commit_{read/write}_pipe
791// \param S Reference to the semantic analyzer.
792// \param Call The call to the builtin function to be analyzed.
793// \return True if a semantic error was found, false otherwise.
794static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
795 if (checkArgCount(S, Call, 2))
796 return true;
797
798 if (checkOpenCLPipeArg(S, Call))
799 return true;
800
801 // Check reserve_id_t.
802 if (!Call->getArg(1)->getType()->isReserveIDT()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000803 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000804 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
805 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
806 return true;
807 }
808
809 return false;
810}
811
812// Performs a semantic analysis on the call to built-in Pipe
813// Query Functions.
814// \param S Reference to the semantic analyzer.
815// \param Call The call to the builtin function to be analyzed.
816// \return True if a semantic error was found, false otherwise.
817static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
818 if (checkArgCount(S, Call, 1))
819 return true;
820
821 if (!Call->getArg(0)->getType()->isPipeType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000822 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000823 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
824 return true;
825 }
826
827 return false;
828}
829
830// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
831// Performs semantic analysis for the to_global/local/private call.
832// \param S Reference to the semantic analyzer.
833// \param BuiltinID ID of the builtin function.
834// \param Call A pointer to the builtin call.
835// \return True if a semantic error has been found, false otherwise.
836static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
837 CallExpr *Call) {
838 if (Call->getNumArgs() != 1) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000839 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
Aaron Ballman68d50642018-06-19 14:53:20 +0000840 << Call->getDirectCallee() << Call->getSourceRange();
841 return true;
842 }
843
844 auto RT = Call->getArg(0)->getType();
845 if (!RT->isPointerType() || RT->getPointeeType()
846 .getAddressSpace() == LangAS::opencl_constant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000847 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
Aaron Ballman68d50642018-06-19 14:53:20 +0000848 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
849 return true;
850 }
851
Sven van Haastregt1076cc22018-09-20 10:07:27 +0000852 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
853 S.Diag(Call->getArg(0)->getBeginLoc(),
854 diag::warn_opencl_generic_address_space_arg)
855 << Call->getDirectCallee()->getNameInfo().getAsString()
856 << Call->getArg(0)->getSourceRange();
857 }
858
Aaron Ballman68d50642018-06-19 14:53:20 +0000859 RT = RT->getPointeeType();
860 auto Qual = RT.getQualifiers();
861 switch (BuiltinID) {
862 case Builtin::BIto_global:
863 Qual.setAddressSpace(LangAS::opencl_global);
864 break;
865 case Builtin::BIto_local:
866 Qual.setAddressSpace(LangAS::opencl_local);
867 break;
868 case Builtin::BIto_private:
869 Qual.setAddressSpace(LangAS::opencl_private);
870 break;
871 default:
872 llvm_unreachable("Invalid builtin function");
873 }
874 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
875 RT.getUnqualifiedType(), Qual)));
876
877 return false;
878}
879
880// Emit an error and return true if the current architecture is not in the list
881// of supported architectures.
882static bool
883CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
884 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
885 llvm::Triple::ArchType CurArch =
886 S.getASTContext().getTargetInfo().getTriple().getArch();
887 if (llvm::is_contained(SupportedArchs, CurArch))
888 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000889 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
Aaron Ballman68d50642018-06-19 14:53:20 +0000890 << TheCall->getSourceRange();
891 return true;
892}
893
894ExprResult
895Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
896 CallExpr *TheCall) {
897 ExprResult TheCallResult(TheCall);
898
899 // Find out if any arguments are required to be integer constant expressions.
900 unsigned ICEArguments = 0;
901 ASTContext::GetBuiltinTypeError Error;
902 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
903 if (Error != ASTContext::GE_None)
904 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
Fangrui Song6907ce22018-07-30 19:24:48 +0000905
Aaron Ballman68d50642018-06-19 14:53:20 +0000906 // If any arguments are required to be ICE's, check and diagnose.
907 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
908 // Skip arguments not required to be ICE's.
909 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000910
Aaron Ballman68d50642018-06-19 14:53:20 +0000911 llvm::APSInt Result;
912 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
913 return true;
914 ICEArguments &= ~(1 << ArgNo);
915 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000916
Aaron Ballman68d50642018-06-19 14:53:20 +0000917 switch (BuiltinID) {
918 case Builtin::BI__builtin___CFStringMakeConstantString:
919 assert(TheCall->getNumArgs() == 1 &&
920 "Wrong # arguments to builtin CFStringMakeConstantString");
921 if (CheckObjCString(TheCall->getArg(0)))
922 return ExprError();
923 break;
924 case Builtin::BI__builtin_ms_va_start:
925 case Builtin::BI__builtin_stdarg_start:
926 case Builtin::BI__builtin_va_start:
927 if (SemaBuiltinVAStart(BuiltinID, TheCall))
928 return ExprError();
929 break;
930 case Builtin::BI__va_start: {
931 switch (Context.getTargetInfo().getTriple().getArch()) {
Martin Storsjo0b339e42018-09-27 08:24:15 +0000932 case llvm::Triple::aarch64:
Aaron Ballman68d50642018-06-19 14:53:20 +0000933 case llvm::Triple::arm:
934 case llvm::Triple::thumb:
935 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
936 return ExprError();
937 break;
938 default:
939 if (SemaBuiltinVAStart(BuiltinID, TheCall))
940 return ExprError();
941 break;
942 }
943 break;
944 }
945
946 // The acquire, release, and no fence variants are ARM and AArch64 only.
947 case Builtin::BI_interlockedbittestandset_acq:
948 case Builtin::BI_interlockedbittestandset_rel:
949 case Builtin::BI_interlockedbittestandset_nf:
950 case Builtin::BI_interlockedbittestandreset_acq:
951 case Builtin::BI_interlockedbittestandreset_rel:
952 case Builtin::BI_interlockedbittestandreset_nf:
953 if (CheckBuiltinTargetSupport(
954 *this, BuiltinID, TheCall,
955 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
956 return ExprError();
957 break;
958
959 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
960 case Builtin::BI_bittest64:
961 case Builtin::BI_bittestandcomplement64:
962 case Builtin::BI_bittestandreset64:
963 case Builtin::BI_bittestandset64:
964 case Builtin::BI_interlockedbittestandreset64:
965 case Builtin::BI_interlockedbittestandset64:
966 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
967 {llvm::Triple::x86_64, llvm::Triple::arm,
968 llvm::Triple::thumb, llvm::Triple::aarch64}))
969 return ExprError();
970 break;
971
972 case Builtin::BI__builtin_isgreater:
973 case Builtin::BI__builtin_isgreaterequal:
974 case Builtin::BI__builtin_isless:
975 case Builtin::BI__builtin_islessequal:
976 case Builtin::BI__builtin_islessgreater:
977 case Builtin::BI__builtin_isunordered:
978 if (SemaBuiltinUnorderedCompare(TheCall))
979 return ExprError();
980 break;
981 case Builtin::BI__builtin_fpclassify:
982 if (SemaBuiltinFPClassification(TheCall, 6))
983 return ExprError();
984 break;
985 case Builtin::BI__builtin_isfinite:
986 case Builtin::BI__builtin_isinf:
987 case Builtin::BI__builtin_isinf_sign:
988 case Builtin::BI__builtin_isnan:
989 case Builtin::BI__builtin_isnormal:
Aaron Ballmandd0e2b02018-06-19 14:59:11 +0000990 case Builtin::BI__builtin_signbit:
991 case Builtin::BI__builtin_signbitf:
992 case Builtin::BI__builtin_signbitl:
Aaron Ballman68d50642018-06-19 14:53:20 +0000993 if (SemaBuiltinFPClassification(TheCall, 1))
994 return ExprError();
995 break;
996 case Builtin::BI__builtin_shufflevector:
997 return SemaBuiltinShuffleVector(TheCall);
998 // TheCall will be freed by the smart pointer here, but that's fine, since
999 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1000 case Builtin::BI__builtin_prefetch:
1001 if (SemaBuiltinPrefetch(TheCall))
1002 return ExprError();
1003 break;
1004 case Builtin::BI__builtin_alloca_with_align:
1005 if (SemaBuiltinAllocaWithAlign(TheCall))
1006 return ExprError();
1007 break;
1008 case Builtin::BI__assume:
1009 case Builtin::BI__builtin_assume:
1010 if (SemaBuiltinAssume(TheCall))
1011 return ExprError();
1012 break;
1013 case Builtin::BI__builtin_assume_aligned:
1014 if (SemaBuiltinAssumeAligned(TheCall))
1015 return ExprError();
1016 break;
1017 case Builtin::BI__builtin_object_size:
1018 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1019 return ExprError();
1020 break;
1021 case Builtin::BI__builtin_longjmp:
1022 if (SemaBuiltinLongjmp(TheCall))
1023 return ExprError();
1024 break;
1025 case Builtin::BI__builtin_setjmp:
1026 if (SemaBuiltinSetjmp(TheCall))
1027 return ExprError();
1028 break;
1029 case Builtin::BI_setjmp:
1030 case Builtin::BI_setjmpex:
1031 if (checkArgCount(*this, TheCall, 1))
1032 return true;
1033 break;
1034 case Builtin::BI__builtin_classify_type:
1035 if (checkArgCount(*this, TheCall, 1)) return true;
1036 TheCall->setType(Context.IntTy);
1037 break;
1038 case Builtin::BI__builtin_constant_p:
1039 if (checkArgCount(*this, TheCall, 1)) return true;
1040 TheCall->setType(Context.IntTy);
1041 break;
1042 case Builtin::BI__sync_fetch_and_add:
1043 case Builtin::BI__sync_fetch_and_add_1:
1044 case Builtin::BI__sync_fetch_and_add_2:
1045 case Builtin::BI__sync_fetch_and_add_4:
1046 case Builtin::BI__sync_fetch_and_add_8:
1047 case Builtin::BI__sync_fetch_and_add_16:
1048 case Builtin::BI__sync_fetch_and_sub:
1049 case Builtin::BI__sync_fetch_and_sub_1:
1050 case Builtin::BI__sync_fetch_and_sub_2:
1051 case Builtin::BI__sync_fetch_and_sub_4:
1052 case Builtin::BI__sync_fetch_and_sub_8:
1053 case Builtin::BI__sync_fetch_and_sub_16:
1054 case Builtin::BI__sync_fetch_and_or:
1055 case Builtin::BI__sync_fetch_and_or_1:
1056 case Builtin::BI__sync_fetch_and_or_2:
1057 case Builtin::BI__sync_fetch_and_or_4:
1058 case Builtin::BI__sync_fetch_and_or_8:
1059 case Builtin::BI__sync_fetch_and_or_16:
1060 case Builtin::BI__sync_fetch_and_and:
1061 case Builtin::BI__sync_fetch_and_and_1:
1062 case Builtin::BI__sync_fetch_and_and_2:
1063 case Builtin::BI__sync_fetch_and_and_4:
1064 case Builtin::BI__sync_fetch_and_and_8:
1065 case Builtin::BI__sync_fetch_and_and_16:
1066 case Builtin::BI__sync_fetch_and_xor:
1067 case Builtin::BI__sync_fetch_and_xor_1:
1068 case Builtin::BI__sync_fetch_and_xor_2:
1069 case Builtin::BI__sync_fetch_and_xor_4:
1070 case Builtin::BI__sync_fetch_and_xor_8:
1071 case Builtin::BI__sync_fetch_and_xor_16:
1072 case Builtin::BI__sync_fetch_and_nand:
1073 case Builtin::BI__sync_fetch_and_nand_1:
1074 case Builtin::BI__sync_fetch_and_nand_2:
1075 case Builtin::BI__sync_fetch_and_nand_4:
1076 case Builtin::BI__sync_fetch_and_nand_8:
1077 case Builtin::BI__sync_fetch_and_nand_16:
1078 case Builtin::BI__sync_add_and_fetch:
1079 case Builtin::BI__sync_add_and_fetch_1:
1080 case Builtin::BI__sync_add_and_fetch_2:
1081 case Builtin::BI__sync_add_and_fetch_4:
1082 case Builtin::BI__sync_add_and_fetch_8:
1083 case Builtin::BI__sync_add_and_fetch_16:
1084 case Builtin::BI__sync_sub_and_fetch:
1085 case Builtin::BI__sync_sub_and_fetch_1:
1086 case Builtin::BI__sync_sub_and_fetch_2:
1087 case Builtin::BI__sync_sub_and_fetch_4:
1088 case Builtin::BI__sync_sub_and_fetch_8:
1089 case Builtin::BI__sync_sub_and_fetch_16:
1090 case Builtin::BI__sync_and_and_fetch:
1091 case Builtin::BI__sync_and_and_fetch_1:
1092 case Builtin::BI__sync_and_and_fetch_2:
1093 case Builtin::BI__sync_and_and_fetch_4:
1094 case Builtin::BI__sync_and_and_fetch_8:
1095 case Builtin::BI__sync_and_and_fetch_16:
1096 case Builtin::BI__sync_or_and_fetch:
1097 case Builtin::BI__sync_or_and_fetch_1:
1098 case Builtin::BI__sync_or_and_fetch_2:
1099 case Builtin::BI__sync_or_and_fetch_4:
1100 case Builtin::BI__sync_or_and_fetch_8:
1101 case Builtin::BI__sync_or_and_fetch_16:
1102 case Builtin::BI__sync_xor_and_fetch:
1103 case Builtin::BI__sync_xor_and_fetch_1:
1104 case Builtin::BI__sync_xor_and_fetch_2:
1105 case Builtin::BI__sync_xor_and_fetch_4:
1106 case Builtin::BI__sync_xor_and_fetch_8:
1107 case Builtin::BI__sync_xor_and_fetch_16:
1108 case Builtin::BI__sync_nand_and_fetch:
1109 case Builtin::BI__sync_nand_and_fetch_1:
1110 case Builtin::BI__sync_nand_and_fetch_2:
1111 case Builtin::BI__sync_nand_and_fetch_4:
1112 case Builtin::BI__sync_nand_and_fetch_8:
1113 case Builtin::BI__sync_nand_and_fetch_16:
1114 case Builtin::BI__sync_val_compare_and_swap:
1115 case Builtin::BI__sync_val_compare_and_swap_1:
1116 case Builtin::BI__sync_val_compare_and_swap_2:
1117 case Builtin::BI__sync_val_compare_and_swap_4:
1118 case Builtin::BI__sync_val_compare_and_swap_8:
1119 case Builtin::BI__sync_val_compare_and_swap_16:
1120 case Builtin::BI__sync_bool_compare_and_swap:
1121 case Builtin::BI__sync_bool_compare_and_swap_1:
1122 case Builtin::BI__sync_bool_compare_and_swap_2:
1123 case Builtin::BI__sync_bool_compare_and_swap_4:
1124 case Builtin::BI__sync_bool_compare_and_swap_8:
1125 case Builtin::BI__sync_bool_compare_and_swap_16:
1126 case Builtin::BI__sync_lock_test_and_set:
1127 case Builtin::BI__sync_lock_test_and_set_1:
1128 case Builtin::BI__sync_lock_test_and_set_2:
1129 case Builtin::BI__sync_lock_test_and_set_4:
1130 case Builtin::BI__sync_lock_test_and_set_8:
1131 case Builtin::BI__sync_lock_test_and_set_16:
1132 case Builtin::BI__sync_lock_release:
1133 case Builtin::BI__sync_lock_release_1:
1134 case Builtin::BI__sync_lock_release_2:
1135 case Builtin::BI__sync_lock_release_4:
1136 case Builtin::BI__sync_lock_release_8:
1137 case Builtin::BI__sync_lock_release_16:
1138 case Builtin::BI__sync_swap:
1139 case Builtin::BI__sync_swap_1:
1140 case Builtin::BI__sync_swap_2:
1141 case Builtin::BI__sync_swap_4:
1142 case Builtin::BI__sync_swap_8:
1143 case Builtin::BI__sync_swap_16:
1144 return SemaBuiltinAtomicOverloaded(TheCallResult);
JF Bastiene77b48b2018-09-10 20:42:56 +00001145 case Builtin::BI__sync_synchronize:
1146 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1147 << TheCall->getCallee()->getSourceRange();
1148 break;
Aaron Ballman68d50642018-06-19 14:53:20 +00001149 case Builtin::BI__builtin_nontemporal_load:
1150 case Builtin::BI__builtin_nontemporal_store:
1151 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1152#define BUILTIN(ID, TYPE, ATTRS)
1153#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1154 case Builtin::BI##ID: \
1155 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1156#include "clang/Basic/Builtins.def"
1157 case Builtin::BI__annotation:
1158 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1159 return ExprError();
1160 break;
1161 case Builtin::BI__builtin_annotation:
1162 if (SemaBuiltinAnnotation(*this, TheCall))
1163 return ExprError();
1164 break;
1165 case Builtin::BI__builtin_addressof:
1166 if (SemaBuiltinAddressof(*this, TheCall))
1167 return ExprError();
1168 break;
1169 case Builtin::BI__builtin_add_overflow:
1170 case Builtin::BI__builtin_sub_overflow:
1171 case Builtin::BI__builtin_mul_overflow:
1172 if (SemaBuiltinOverflow(*this, TheCall))
1173 return ExprError();
1174 break;
1175 case Builtin::BI__builtin_operator_new:
1176 case Builtin::BI__builtin_operator_delete: {
1177 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1178 ExprResult Res =
1179 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1180 if (Res.isInvalid())
1181 CorrectDelayedTyposInExpr(TheCallResult.get());
1182 return Res;
1183 }
1184 case Builtin::BI__builtin_dump_struct: {
1185 // We first want to ensure we are called with 2 arguments
1186 if (checkArgCount(*this, TheCall, 2))
1187 return ExprError();
1188 // Ensure that the first argument is of type 'struct XX *'
1189 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1190 const QualType PtrArgType = PtrArg->getType();
1191 if (!PtrArgType->isPointerType() ||
1192 !PtrArgType->getPointeeType()->isRecordType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001193 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman68d50642018-06-19 14:53:20 +00001194 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1195 << "structure pointer";
1196 return ExprError();
Aaron Ballman06525342018-04-10 21:58:13 +00001197 }
1198
1199 // Ensure that the second argument is of type 'FunctionType'
1200 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1201 const QualType FnPtrArgType = FnPtrArg->getType();
1202 if (!FnPtrArgType->isPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001203 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1204 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1205 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001206 return ExprError();
1207 }
1208
1209 const auto *FuncType =
1210 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1211
1212 if (!FuncType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001213 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1214 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1215 << FnPtrArgType << "'int (*)(const char *, ...)'";
Aaron Ballman06525342018-04-10 21:58:13 +00001216 return ExprError();
1217 }
1218
1219 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1220 if (!FT->getNumParams()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001221 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001222 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1223 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1224 return ExprError();
1225 }
1226 QualType PT = FT->getParamType(0);
1227 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1228 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1229 !PT->getPointeeType().isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001230 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
Aaron Ballman06525342018-04-10 21:58:13 +00001231 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1232 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1233 return ExprError();
1234 }
1235 }
1236
1237 TheCall->setType(Context.IntTy);
1238 break;
1239 }
1240
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001241 // check secure string manipulation functions where overflows
1242 // are detectable at compile time
1243 case Builtin::BI__builtin___memcpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001244 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy");
1245 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001246 case Builtin::BI__builtin___memmove_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001247 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove");
1248 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001249 case Builtin::BI__builtin___memset_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001250 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset");
1251 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001252 case Builtin::BI__builtin___strlcat_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001253 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat");
1254 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001255 case Builtin::BI__builtin___strlcpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001256 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy");
1257 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001258 case Builtin::BI__builtin___strncat_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001259 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat");
1260 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001261 case Builtin::BI__builtin___strncpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001262 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy");
1263 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001264 case Builtin::BI__builtin___stpncpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001265 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy");
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001266 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001267 case Builtin::BI__builtin___memccpy_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001268 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy");
Steven Wu566c14e2014-09-24 04:37:33 +00001269 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001270 case Builtin::BI__builtin___snprintf_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001271 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf");
1272 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001273 case Builtin::BI__builtin___vsnprintf_chk:
Erik Pilkingtonf85e3912018-09-06 17:19:33 +00001274 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf");
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001275 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001276 case Builtin::BI__builtin_call_with_static_chain:
1277 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1278 return ExprError();
1279 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001280 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001281 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001282 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1283 diag::err_seh___except_block))
1284 return ExprError();
1285 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001286 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001287 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001288 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1289 diag::err_seh___except_filter))
1290 return ExprError();
1291 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001292 case Builtin::BI__GetExceptionInfo:
1293 if (checkArgCount(*this, TheCall, 1))
1294 return ExprError();
1295
1296 if (CheckCXXThrowOperand(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001297 TheCall->getBeginLoc(),
David Majnemerba3e5ec2015-03-13 18:26:17 +00001298 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1299 TheCall))
1300 return ExprError();
1301
1302 TheCall->setType(Context.VoidPtrTy);
1303 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001304 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001305 case Builtin::BIread_pipe:
1306 case Builtin::BIwrite_pipe:
1307 // Since those two functions are declared with var args, we need a semantic
1308 // check for the argument.
1309 if (SemaBuiltinRWPipe(*this, TheCall))
1310 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001311 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001312 break;
1313 case Builtin::BIreserve_read_pipe:
1314 case Builtin::BIreserve_write_pipe:
1315 case Builtin::BIwork_group_reserve_read_pipe:
1316 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001317 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1318 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001319 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001320 case Builtin::BIsub_group_reserve_read_pipe:
1321 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001322 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1323 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001324 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001325 break;
1326 case Builtin::BIcommit_read_pipe:
1327 case Builtin::BIcommit_write_pipe:
1328 case Builtin::BIwork_group_commit_read_pipe:
1329 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001330 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1331 return ExprError();
1332 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001333 case Builtin::BIsub_group_commit_read_pipe:
1334 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001335 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1336 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001337 return ExprError();
1338 break;
1339 case Builtin::BIget_pipe_num_packets:
1340 case Builtin::BIget_pipe_max_packets:
1341 if (SemaBuiltinPipePackets(*this, TheCall))
1342 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001343 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001344 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001345 case Builtin::BIto_global:
1346 case Builtin::BIto_local:
1347 case Builtin::BIto_private:
1348 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1349 return ExprError();
1350 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001351 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1352 case Builtin::BIenqueue_kernel:
1353 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1354 return ExprError();
1355 break;
1356 case Builtin::BIget_kernel_work_group_size:
1357 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1358 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1359 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001360 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001361 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1362 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1363 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1364 return ExprError();
1365 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001366 case Builtin::BI__builtin_os_log_format:
1367 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001368 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001369 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001370 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001371 }
Richard Smith760520b2014-06-03 23:27:44 +00001372
Nate Begeman4904e322010-06-08 02:47:44 +00001373 // Since the target specific builtins for each arch overlap, only check those
1374 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001375 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001376 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001377 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001378 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001379 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001380 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001381 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1382 return ExprError();
1383 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001384 case llvm::Triple::aarch64:
1385 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001386 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001387 return ExprError();
1388 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001389 case llvm::Triple::hexagon:
1390 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1391 return ExprError();
1392 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001393 case llvm::Triple::mips:
1394 case llvm::Triple::mipsel:
1395 case llvm::Triple::mips64:
1396 case llvm::Triple::mips64el:
1397 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1398 return ExprError();
1399 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001400 case llvm::Triple::systemz:
1401 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1402 return ExprError();
1403 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001404 case llvm::Triple::x86:
1405 case llvm::Triple::x86_64:
1406 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1407 return ExprError();
1408 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001409 case llvm::Triple::ppc:
1410 case llvm::Triple::ppc64:
1411 case llvm::Triple::ppc64le:
1412 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1413 return ExprError();
1414 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001415 default:
1416 break;
1417 }
1418 }
1419
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001420 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001421}
1422
Nate Begeman91e1fea2010-06-14 05:21:25 +00001423// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001424static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001425 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001426 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001427 switch (Type.getEltType()) {
1428 case NeonTypeFlags::Int8:
1429 case NeonTypeFlags::Poly8:
1430 return shift ? 7 : (8 << IsQuad) - 1;
1431 case NeonTypeFlags::Int16:
1432 case NeonTypeFlags::Poly16:
1433 return shift ? 15 : (4 << IsQuad) - 1;
1434 case NeonTypeFlags::Int32:
1435 return shift ? 31 : (2 << IsQuad) - 1;
1436 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001437 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001438 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001439 case NeonTypeFlags::Poly128:
1440 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001441 case NeonTypeFlags::Float16:
1442 assert(!shift && "cannot shift float types!");
1443 return (4 << IsQuad) - 1;
1444 case NeonTypeFlags::Float32:
1445 assert(!shift && "cannot shift float types!");
1446 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001447 case NeonTypeFlags::Float64:
1448 assert(!shift && "cannot shift float types!");
1449 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001450 }
David Blaikie8a40f702012-01-17 06:56:22 +00001451 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001452}
1453
Bob Wilsone4d77232011-11-08 05:04:11 +00001454/// getNeonEltType - Return the QualType corresponding to the elements of
1455/// the vector type specified by the NeonTypeFlags. This is used to check
1456/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001457static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001458 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001459 switch (Flags.getEltType()) {
1460 case NeonTypeFlags::Int8:
1461 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1462 case NeonTypeFlags::Int16:
1463 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1464 case NeonTypeFlags::Int32:
1465 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1466 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001467 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001468 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1469 else
1470 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1471 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001472 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001473 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001474 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001475 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001476 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001477 if (IsInt64Long)
1478 return Context.UnsignedLongTy;
1479 else
1480 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001481 case NeonTypeFlags::Poly128:
1482 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001483 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001484 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001485 case NeonTypeFlags::Float32:
1486 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001487 case NeonTypeFlags::Float64:
1488 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001489 }
David Blaikie8a40f702012-01-17 06:56:22 +00001490 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001491}
1492
Tim Northover12670412014-02-19 10:37:05 +00001493bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001494 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001495 uint64_t mask = 0;
1496 unsigned TV = 0;
1497 int PtrArgNum = -1;
1498 bool HasConstPtr = false;
1499 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001500#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001501#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001502#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001503#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001504 }
1505
1506 // For NEON intrinsics which are overloaded on vector element type, validate
1507 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001508 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001509 if (mask) {
1510 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1511 return true;
1512
1513 TV = Result.getLimitedValue(64);
1514 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001515 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1516 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001517 }
1518
1519 if (PtrArgNum >= 0) {
1520 // Check that pointer arguments have the specified type.
1521 Expr *Arg = TheCall->getArg(PtrArgNum);
1522 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1523 Arg = ICE->getSubExpr();
1524 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1525 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001526
Tim Northovera2ee4332014-03-29 15:09:45 +00001527 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001528 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1529 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001530 bool IsInt64Long =
1531 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1532 QualType EltTy =
1533 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001534 if (HasConstPtr)
1535 EltTy = EltTy.withConst();
1536 QualType LHSTy = Context.getPointerType(EltTy);
1537 AssignConvertType ConvTy;
1538 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1539 if (RHS.isInvalid())
1540 return true;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001541 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
Tim Northover2fe823a2013-08-01 09:23:19 +00001542 RHS.get(), AA_Assigning))
1543 return true;
1544 }
1545
1546 // For NEON intrinsics which take an immediate value as part of the
1547 // instruction, range check them here.
1548 unsigned i = 0, l = 0, u = 0;
1549 switch (BuiltinID) {
1550 default:
1551 return false;
Luke Geesondc54b372018-06-12 09:54:27 +00001552 #define GET_NEON_IMMEDIATE_CHECK
1553 #include "clang/Basic/arm_neon.inc"
1554 #include "clang/Basic/arm_fp16.inc"
1555 #undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001556 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001557
Richard Sandiford28940af2014-04-16 08:47:51 +00001558 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001559}
1560
Tim Northovera2ee4332014-03-29 15:09:45 +00001561bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1562 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001563 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001564 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001565 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001566 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001567 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001568 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1569 BuiltinID == AArch64::BI__builtin_arm_strex ||
1570 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001571 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001572 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001573 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1574 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1575 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001576
1577 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1578
1579 // Ensure that we have the proper number of arguments.
1580 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1581 return true;
1582
1583 // Inspect the pointer argument of the atomic builtin. This should always be
1584 // a pointer type, whose element is an integral scalar or pointer type.
1585 // Because it is a pointer type, we don't have to worry about any implicit
1586 // casts here.
1587 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1588 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1589 if (PointerArgRes.isInvalid())
1590 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001591 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001592
1593 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1594 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001595 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1596 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001597 return true;
1598 }
1599
1600 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1601 // task is to insert the appropriate casts into the AST. First work out just
1602 // what the appropriate type is.
1603 QualType ValType = pointerType->getPointeeType();
1604 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1605 if (IsLdrex)
1606 AddrType.addConst();
1607
1608 // Issue a warning if the cast is dodgy.
1609 CastKind CastNeeded = CK_NoOp;
1610 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1611 CastNeeded = CK_BitCast;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001612 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1613 << PointerArg->getType() << Context.getPointerType(AddrType)
1614 << AA_Passing << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001615 }
1616
1617 // Finally, do the cast and replace the argument with the corrected version.
1618 AddrType = Context.getPointerType(AddrType);
1619 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1620 if (PointerArgRes.isInvalid())
1621 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001622 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001623
1624 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1625
1626 // In general, we allow ints, floats and pointers to be loaded and stored.
1627 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1628 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001629 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1630 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001631 return true;
1632 }
1633
1634 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001635 if (Context.getTypeSize(ValType) > MaxWidth) {
1636 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001637 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1638 << PointerArg->getType() << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001639 return true;
1640 }
1641
1642 switch (ValType.getObjCLifetime()) {
1643 case Qualifiers::OCL_None:
1644 case Qualifiers::OCL_ExplicitNone:
1645 // okay
1646 break;
1647
1648 case Qualifiers::OCL_Weak:
1649 case Qualifiers::OCL_Strong:
1650 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001651 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1652 << ValType << PointerArg->getSourceRange();
Tim Northover6aacd492013-07-16 09:47:53 +00001653 return true;
1654 }
1655
Tim Northover6aacd492013-07-16 09:47:53 +00001656 if (IsLdrex) {
1657 TheCall->setType(ValType);
1658 return false;
1659 }
1660
1661 // Initialize the argument to be stored.
1662 ExprResult ValArg = TheCall->getArg(0);
1663 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1664 Context, ValType, /*consume*/ false);
1665 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1666 if (ValArg.isInvalid())
1667 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001668 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001669
1670 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1671 // but the custom checker bypasses all default analysis.
1672 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001673 return false;
1674}
1675
Nate Begeman4904e322010-06-08 02:47:44 +00001676bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001677 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001678 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1679 BuiltinID == ARM::BI__builtin_arm_strex ||
1680 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001681 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001682 }
1683
Yi Kong26d104a2014-08-13 19:18:14 +00001684 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1685 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1686 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1687 }
1688
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001689 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1690 BuiltinID == ARM::BI__builtin_arm_wsr64)
1691 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1692
1693 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1694 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1695 BuiltinID == ARM::BI__builtin_arm_wsr ||
1696 BuiltinID == ARM::BI__builtin_arm_wsrp)
1697 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1698
Tim Northover12670412014-02-19 10:37:05 +00001699 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1700 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001701
Yi Kong4efadfb2014-07-03 16:01:25 +00001702 // For intrinsics which take an immediate value as part of the instruction,
1703 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001704 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001705 switch (BuiltinID) {
1706 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001707 case ARM::BI__builtin_arm_ssat:
1708 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1709 case ARM::BI__builtin_arm_usat:
1710 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1711 case ARM::BI__builtin_arm_ssat16:
1712 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1713 case ARM::BI__builtin_arm_usat16:
1714 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001715 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001716 case ARM::BI__builtin_arm_vcvtr_d:
1717 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001718 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001719 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001720 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001721 case ARM::BI__builtin_arm_dbg:
1722 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001723 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001724}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001725
Tim Northover573cbee2014-05-24 12:52:07 +00001726bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001727 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001728 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001729 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1730 BuiltinID == AArch64::BI__builtin_arm_strex ||
1731 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001732 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1733 }
1734
Yi Konga5548432014-08-13 19:18:20 +00001735 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1736 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1737 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1738 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1739 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1740 }
1741
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001742 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1743 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001744 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001745
1746 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1747 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1748 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1749 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1750 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1751
Mandeep Singh Grang2147b1a2018-10-18 23:35:35 +00001752 // Only check the valid encoding range. Any constant in this range would be
1753 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1754 // an exception for incorrect registers. This matches MSVC behavior.
1755 if (BuiltinID == AArch64::BI_ReadStatusReg ||
1756 BuiltinID == AArch64::BI_WriteStatusReg)
1757 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1758
Mandeep Singh Grangecc82ef2018-10-04 22:32:42 +00001759 if (BuiltinID == AArch64::BI__getReg)
1760 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1761
Tim Northovera2ee4332014-03-29 15:09:45 +00001762 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1763 return true;
1764
Yi Kong19a29ac2014-07-17 10:52:06 +00001765 // For intrinsics which take an immediate value as part of the instruction,
1766 // range check them here.
1767 unsigned i = 0, l = 0, u = 0;
1768 switch (BuiltinID) {
1769 default: return false;
1770 case AArch64::BI__builtin_arm_dmb:
1771 case AArch64::BI__builtin_arm_dsb:
1772 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1773 }
1774
Yi Kong19a29ac2014-07-17 10:52:06 +00001775 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001776}
1777
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001778bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001779 struct BuiltinAndString {
1780 unsigned BuiltinID;
1781 const char *Str;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00001782 };
1783
Reid Kleckner9e9606e2018-10-25 22:37:30 +00001784 static BuiltinAndString ValidCPU[] = {
1785 { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65" },
1786 { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65" },
1787 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65" },
1788 { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65" },
1789 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65" },
1790 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65" },
1791 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65" },
1792 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65" },
1793 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65" },
1794 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65" },
1795 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65" },
1796 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65" },
1797 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65" },
1798 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65" },
1799 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65" },
1800 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65" },
1801 { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65" },
1802 { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65" },
1803 { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65" },
1804 };
1805
1806 static BuiltinAndString ValidHVX[] = {
1807 { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65" },
1808 { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65" },
1809 { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65" },
1810 { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65" },
1811 { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65" },
1812 { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65" },
1813 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65" },
1814 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65" },
1815 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65" },
1816 { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65" },
1817 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65" },
1818 { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65" },
1819 { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65" },
1820 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65" },
1821 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65" },
1822 { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65" },
1823 { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65" },
1824 { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65" },
1825 { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65" },
1826 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65" },
1827 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65" },
1828 { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65" },
1829 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65" },
1830 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65" },
1831 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65" },
1832 { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65" },
1833 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65" },
1834 { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65" },
1835 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65" },
1836 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65" },
1837 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65" },
1838 { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65" },
1839 { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65" },
1840 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65" },
1841 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65" },
1842 { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65" },
1843 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65" },
1844 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65" },
1845 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65" },
1846 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65" },
1847 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65" },
1848 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65" },
1849 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65" },
1850 { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65" },
1851 { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65" },
1852 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65" },
1853 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65" },
1854 { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65" },
1855 { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65" },
1856 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65" },
1857 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65" },
1858 { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65" },
1859 { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65" },
1860 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65" },
1861 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65" },
1862 { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65" },
1863 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65" },
1864 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65" },
1865 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65" },
1866 { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65" },
1867 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65" },
1868 { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65" },
1869 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65" },
1870 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65" },
1871 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65" },
1872 { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65" },
1873 { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65" },
1874 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65" },
1875 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65" },
1876 { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65" },
1877 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65" },
1878 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65" },
1879 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65" },
1880 { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65" },
1881 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65" },
1882 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65" },
1883 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65" },
1884 { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65" },
1885 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65" },
1886 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65" },
1887 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65" },
1888 { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65" },
1889 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65" },
1890 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65" },
1891 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65" },
1892 { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65" },
1893 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65" },
1894 { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65" },
1895 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65" },
1896 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65" },
1897 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65" },
1898 { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65" },
1899 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65" },
1900 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65" },
1901 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65" },
1902 { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65" },
1903 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65" },
1904 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65" },
1905 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65" },
1906 { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65" },
1907 { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65" },
1908 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65" },
1909 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65" },
1910 { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65" },
1911 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65" },
1912 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65" },
1913 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65" },
1914 { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65" },
1915 { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65" },
1916 { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65" },
1917 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65" },
1918 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65" },
1919 { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65" },
1920 { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65" },
1921 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65" },
1922 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65" },
1923 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65" },
1924 { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65" },
1925 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65" },
1926 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65" },
1927 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65" },
1928 { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65" },
1929 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65" },
1930 { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65" },
1931 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65" },
1932 { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65" },
1933 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65" },
1934 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65" },
1935 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65" },
1936 { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65" },
1937 { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65" },
1938 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65" },
1939 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65" },
1940 { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65" },
1941 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65" },
1942 { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65" },
1943 { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65" },
1944 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65" },
1945 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65" },
1946 { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65" },
1947 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65" },
1948 { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65" },
1949 { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65" },
1950 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65" },
1951 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65" },
1952 { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65" },
1953 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65" },
1954 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65" },
1955 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65" },
1956 { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65" },
1957 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65" },
1958 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65" },
1959 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65" },
1960 { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65" },
1961 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65" },
1962 { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65" },
1963 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65" },
1964 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65" },
1965 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65" },
1966 { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65" },
1967 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65" },
1968 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65" },
1969 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65" },
1970 { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65" },
1971 { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65" },
1972 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65" },
1973 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65" },
1974 { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65" },
1975 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65" },
1976 { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65" },
1977 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65" },
1978 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65" },
1979 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65" },
1980 { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65" },
1981 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65" },
1982 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65" },
1983 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65" },
1984 { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65" },
1985 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65" },
1986 { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65" },
1987 { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65" },
1988 { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65" },
1989 { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65" },
1990 { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65" },
1991 { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65" },
1992 { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65" },
1993 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65" },
1994 { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65" },
1995 { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65" },
1996 { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65" },
1997 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65" },
1998 { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65" },
1999 { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65" },
2000 { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65" },
2001 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65" },
2002 { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65" },
2003 { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65" },
2004 { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65" },
2005 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65" },
2006 { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65" },
2007 { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65" },
2008 { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65" },
2009 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65" },
2010 { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65" },
2011 { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65" },
2012 { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65" },
2013 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65" },
2014 { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65" },
2015 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65" },
2016 { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65" },
2017 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65" },
2018 { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65" },
2019 { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65" },
2020 { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65" },
2021 { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65" },
2022 { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65" },
2023 { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65" },
2024 { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65" },
2025 { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65" },
2026 { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65" },
2027 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65" },
2028 { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65" },
2029 { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65" },
2030 { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65" },
2031 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65" },
2032 { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65" },
2033 { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65" },
2034 { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65" },
2035 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65" },
2036 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65" },
2037 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65" },
2038 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65" },
2039 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65" },
2040 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65" },
2041 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65" },
2042 { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65" },
2043 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65" },
2044 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65" },
2045 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65" },
2046 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65" },
2047 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65" },
2048 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65" },
2049 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65" },
2050 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65" },
2051 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65" },
2052 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65" },
2053 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65" },
2054 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65" },
2055 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65" },
2056 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65" },
2057 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65" },
2058 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65" },
2059 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65" },
2060 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65" },
2061 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65" },
2062 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65" },
2063 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65" },
2064 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65" },
2065 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65" },
2066 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65" },
2067 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65" },
2068 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65" },
2069 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65" },
2070 { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65" },
2071 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65" },
2072 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65" },
2073 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65" },
2074 { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65" },
2075 { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65" },
2076 { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65" },
2077 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65" },
2078 { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65" },
2079 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65" },
2080 { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65" },
2081 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65" },
2082 { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65" },
2083 { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65" },
2084 { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65" },
2085 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65" },
2086 { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65" },
2087 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65" },
2088 { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65" },
2089 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65" },
2090 { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65" },
2091 { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65" },
2092 { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65" },
2093 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65" },
2094 { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65" },
2095 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65" },
2096 { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65" },
2097 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65" },
2098 { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65" },
2099 { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65" },
2100 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65" },
2101 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65" },
2102 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65" },
2103 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65" },
2104 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65" },
2105 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65" },
2106 { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65" },
2107 { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65" },
2108 { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65" },
2109 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65" },
2110 { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65" },
2111 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65" },
2112 { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65" },
2113 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65" },
2114 { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65" },
2115 { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65" },
2116 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65" },
2117 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65" },
2118 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65" },
2119 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65" },
2120 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65" },
2121 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65" },
2122 { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65" },
2123 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65" },
2124 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65" },
2125 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65" },
2126 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65" },
2127 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65" },
2128 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65" },
2129 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65" },
2130 { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65" },
2131 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65" },
2132 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65" },
2133 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65" },
2134 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65" },
2135 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65" },
2136 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65" },
2137 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65" },
2138 { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65" },
2139 { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65" },
2140 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65" },
2141 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65" },
2142 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65" },
2143 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65" },
2144 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65" },
2145 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65" },
2146 { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65" },
2147 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65" },
2148 { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65" },
2149 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65" },
2150 { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65" },
2151 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65" },
2152 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65" },
2153 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65" },
2154 { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65" },
2155 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65" },
2156 { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65" },
2157 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65" },
2158 { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65" },
2159 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65" },
2160 { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65" },
2161 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65" },
2162 { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65" },
2163 { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65" },
2164 { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65" },
2165 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65" },
2166 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65" },
2167 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65" },
2168 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65" },
2169 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65" },
2170 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65" },
2171 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65" },
2172 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65" },
2173 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65" },
2174 { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65" },
2175 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65" },
2176 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65" },
2177 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65" },
2178 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65" },
2179 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65" },
2180 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65" },
2181 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65" },
2182 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65" },
2183 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65" },
2184 { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65" },
2185 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65" },
2186 { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65" },
2187 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65" },
2188 { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65" },
2189 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65" },
2190 { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65" },
2191 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65" },
2192 { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65" },
2193 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65" },
2194 { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65" },
2195 { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65" },
2196 { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65" },
2197 { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65" },
2198 { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65" },
2199 { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65" },
2200 { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65" },
2201 { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65" },
2202 { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65" },
2203 { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65" },
2204 { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65" },
2205 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65" },
2206 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65" },
2207 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65" },
2208 { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65" },
2209 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65" },
2210 { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65" },
2211 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65" },
2212 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65" },
2213 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65" },
2214 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65" },
2215 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65" },
2216 { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65" },
2217 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65" },
2218 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65" },
2219 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65" },
2220 { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65" },
2221 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65" },
2222 { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65" },
2223 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65" },
2224 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65" },
2225 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65" },
2226 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65" },
2227 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65" },
2228 { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65" },
2229 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65" },
2230 { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65" },
2231 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65" },
2232 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65" },
2233 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65" },
2234 { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65" },
2235 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65" },
2236 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65" },
2237 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65" },
2238 { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65" },
2239 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65" },
2240 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65" },
2241 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65" },
2242 { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65" },
2243 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65" },
2244 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65" },
2245 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65" },
2246 { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65" },
2247 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65" },
2248 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65" },
2249 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65" },
2250 { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65" },
2251 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65" },
2252 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65" },
2253 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65" },
2254 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65" },
2255 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65" },
2256 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65" },
2257 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65" },
2258 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65" },
2259 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65" },
2260 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65" },
2261 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65" },
2262 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65" },
2263 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65" },
2264 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65" },
2265 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65" },
2266 { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65" },
2267 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65" },
2268 { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65" },
2269 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65" },
2270 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65" },
2271 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65" },
2272 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65" },
2273 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65" },
2274 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65" },
2275 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65" },
2276 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65" },
2277 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65" },
2278 { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65" },
2279 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65" },
2280 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65" },
2281 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65" },
2282 { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65" },
2283 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65" },
2284 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65" },
2285 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65" },
2286 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65" },
2287 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65" },
2288 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65" },
2289 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65" },
2290 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65" },
2291 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65" },
2292 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65" },
2293 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65" },
2294 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65" },
2295 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65" },
2296 { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65" },
2297 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65" },
2298 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65" },
2299 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65" },
2300 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65" },
2301 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65" },
2302 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65" },
2303 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65" },
2304 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65" },
2305 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65" },
2306 { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65" },
2307 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65" },
2308 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65" },
2309 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65" },
2310 { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65" },
2311 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65" },
2312 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65" },
2313 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65" },
2314 { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65" },
2315 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65" },
2316 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65" },
2317 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65" },
2318 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65" },
2319 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65" },
2320 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65" },
2321 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65" },
2322 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65" },
2323 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65" },
2324 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65" },
2325 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65" },
2326 { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65" },
2327 { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65" },
2328 { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65" },
2329 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65" },
2330 { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65" },
2331 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65" },
2332 { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65" },
2333 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65" },
2334 { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65" },
2335 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65" },
2336 { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65" },
2337 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65" },
2338 { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65" },
2339 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65" },
2340 { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65" },
2341 { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65" },
2342 { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65" },
2343 { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65" },
2344 { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65" },
2345 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65" },
2346 { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65" },
2347 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65" },
2348 { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65" },
2349 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65" },
2350 { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65" },
2351 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65" },
2352 { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65" },
2353 { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65" },
2354 { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65" },
2355 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65" },
2356 { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65" },
2357 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65" },
2358 { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65" },
2359 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65" },
2360 { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65" },
2361 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65" },
2362 { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65" },
2363 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65" },
2364 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65" },
2365 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65" },
2366 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65" },
2367 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65" },
2368 { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65" },
2369 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65" },
2370 { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65" },
2371 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2372 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2373 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2374 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2375 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65" },
2376 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65" },
2377 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65" },
2378 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65" },
2379 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65" },
2380 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65" },
2381 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65" },
2382 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65" },
2383 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65" },
2384 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65" },
2385 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65" },
2386 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65" },
2387 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65" },
2388 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65" },
2389 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65" },
2390 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65" },
2391 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65" },
2392 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65" },
2393 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65" },
2394 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65" },
2395 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65" },
2396 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65" },
2397 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65" },
2398 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65" },
2399 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2400 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2401 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2402 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2403 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65" },
2404 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65" },
2405 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65" },
2406 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65" },
2407 { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65" },
2408 { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65" },
2409 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65" },
2410 { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65" },
2411 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65" },
2412 { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65" },
2413 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65" },
2414 { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65" },
2415 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65" },
2416 { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65" },
2417 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65" },
2418 { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65" },
2419 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65" },
2420 { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65" },
2421 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65" },
2422 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65" },
2423 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65" },
2424 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65" },
2425 { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65" },
2426 { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65" },
2427 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65" },
2428 { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65" },
2429 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65" },
2430 { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65" },
2431 { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65" },
2432 { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65" },
2433 { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65" },
2434 { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65" },
2435 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65" },
2436 { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65" },
2437 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65" },
2438 { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65" },
2439 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65" },
2440 { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65" },
2441 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65" },
2442 { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65" },
2443 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65" },
2444 { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65" },
2445 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65" },
2446 { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65" },
2447 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65" },
2448 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65" },
2449 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65" },
2450 { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65" },
2451 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65" },
2452 { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65" },
2453 { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65" },
2454 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65" },
2455 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65" },
2456 { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65" },
2457 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65" },
2458 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65" },
2459 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65" },
2460 { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65" },
2461 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65" },
2462 { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65" },
2463 { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65" },
2464 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65" },
2465 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65" },
2466 { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65" },
2467 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65" },
2468 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65" },
2469 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65" },
2470 { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65" },
2471 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65" },
2472 { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65" },
2473 { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65" },
2474 { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65" },
2475 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65" },
2476 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65" },
2477 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65" },
2478 { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65" },
2479 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65" },
2480 { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65" },
2481 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65" },
2482 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65" },
2483 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65" },
2484 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65" },
2485 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65" },
2486 { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65" },
2487 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65" },
2488 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65" },
2489 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65" },
2490 { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65" },
2491 { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65" },
2492 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65" },
2493 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65" },
2494 { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65" },
2495 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65" },
2496 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65" },
2497 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65" },
2498 { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65" },
2499 { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65" },
2500 { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65" },
2501 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65" },
2502 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65" },
2503 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65" },
2504 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65" },
2505 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65" },
2506 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65" },
2507 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65" },
2508 { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65" },
2509 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65" },
2510 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65" },
2511 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65" },
2512 { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65" },
2513 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65" },
2514 { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65" },
2515 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65" },
2516 { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65" },
2517 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65" },
2518 { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65" },
2519 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65" },
2520 { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65" },
2521 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65" },
2522 { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65" },
2523 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65" },
2524 { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65" },
2525 { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65" },
2526 { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65" },
2527 { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65" },
2528 { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65" },
2529 { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65" },
2530 { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65" },
2531 };
2532
2533 // Sort the tables on first execution so we can binary search them.
2534 auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2535 return LHS.BuiltinID < RHS.BuiltinID;
2536 };
2537 static const bool SortOnce =
2538 (std::sort(std::begin(ValidCPU), std::end(ValidCPU), SortCmp),
2539 std::sort(std::begin(ValidHVX), std::end(ValidHVX), SortCmp), true);
2540 (void)SortOnce;
2541 auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2542 return BI.BuiltinID < BuiltinID;
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002543 };
2544
2545 const TargetInfo &TI = Context.getTargetInfo();
2546
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002547 const BuiltinAndString *FC =
2548 std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2549 LowerBoundCmp);
2550 if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002551 const TargetOptions &Opts = TI.getTargetOpts();
2552 StringRef CPU = Opts.CPU;
2553 if (!CPU.empty()) {
2554 assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2555 CPU.consume_front("hexagon");
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002556 SmallVector<StringRef, 3> CPUs;
2557 StringRef(FC->Str).split(CPUs, ',');
2558 if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002559 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002560 diag::err_hexagon_builtin_unsupported_cpu);
2561 }
2562 }
2563
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002564 const BuiltinAndString *FH =
2565 std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2566 LowerBoundCmp);
2567 if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002568 if (!TI.hasFeature("hvx"))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002569 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002570 diag::err_hexagon_builtin_requires_hvx);
2571
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002572 SmallVector<StringRef, 3> HVXs;
2573 StringRef(FH->Str).split(HVXs, ',');
2574 bool IsValid = llvm::any_of(HVXs,
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002575 [&TI] (StringRef V) {
2576 std::string F = "hvx" + V.str();
2577 return TI.hasFeature(F);
2578 });
2579 if (!IsValid)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002580 return Diag(TheCall->getBeginLoc(),
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002581 diag::err_hexagon_builtin_unsupported_hvx);
2582 }
2583
2584 return false;
2585}
2586
2587bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002588 struct ArgInfo {
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002589 uint8_t OpNum;
2590 bool IsSigned;
2591 uint8_t BitWidth;
2592 uint8_t Align;
2593 };
2594 struct BuiltinInfo {
2595 unsigned BuiltinID;
2596 ArgInfo Infos[2];
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002597 };
2598
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002599 static BuiltinInfo Infos[] = {
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002600 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
2601 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
2602 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
2603 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
2604 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
2605 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
2606 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
2607 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
2608 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
2609 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
2610 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
2611
2612 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
2613 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
2614 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
2615 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
2616 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
2617 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
2618 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
2619 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
2620 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
2621 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
2622 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
2623
2624 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
2625 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
2626 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
2627 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
2628 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
2629 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
2630 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
2631 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
2632 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
2633 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
2634 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
2635 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
2636 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
2637 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
2638 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
2639 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
2640 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
2641 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
2642 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
2643 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
2644 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
2645 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
2646 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
2647 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
2648 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
2649 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
2650 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
2651 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
2652 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
2653 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
2654 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
2655 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
2656 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
2657 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
2658 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
2659 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
2660 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
2661 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
2662 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
2663 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
2664 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
2665 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
2666 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
2667 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
2668 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
2669 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
2670 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
2671 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
2672 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
2673 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
2674 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
2675 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2676 {{ 1, false, 6, 0 }} },
2677 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
2678 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
2679 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
2680 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
2681 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
2682 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
2683 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2684 {{ 1, false, 5, 0 }} },
2685 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
2686 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
2687 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
2688 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
2689 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
2690 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
2691 { 2, false, 5, 0 }} },
2692 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
2693 { 2, false, 6, 0 }} },
2694 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
2695 { 3, false, 5, 0 }} },
2696 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
2697 { 3, false, 6, 0 }} },
2698 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
2699 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
2700 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
2701 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
2702 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
2703 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
2704 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
2705 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
2706 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
2707 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
2708 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
2709 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
2710 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
2711 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
2712 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
2713 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2714 {{ 2, false, 4, 0 },
2715 { 3, false, 5, 0 }} },
2716 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2717 {{ 2, false, 4, 0 },
2718 { 3, false, 5, 0 }} },
2719 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2720 {{ 2, false, 4, 0 },
2721 { 3, false, 5, 0 }} },
2722 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2723 {{ 2, false, 4, 0 },
2724 { 3, false, 5, 0 }} },
2725 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
2726 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
2727 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
2728 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
2729 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
2730 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
2731 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
2732 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
2733 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
2734 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
2735 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
2736 { 2, false, 5, 0 }} },
2737 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
2738 { 2, false, 6, 0 }} },
2739 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
2740 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
2741 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
2742 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
2743 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
2744 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
2745 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
2746 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
2747 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2748 {{ 1, false, 4, 0 }} },
2749 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
2750 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2751 {{ 1, false, 4, 0 }} },
2752 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
2753 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
2754 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
2755 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
2756 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
2757 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
2758 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
2759 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
2760 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
2761 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
2762 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
2763 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
2764 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
2765 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
2766 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
2767 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
2768 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
2769 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
2770 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
2771 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2772 {{ 3, false, 1, 0 }} },
2773 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
2774 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
2775 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
2776 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2777 {{ 3, false, 1, 0 }} },
2778 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
2779 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
2780 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
2781 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2782 {{ 3, false, 1, 0 }} },
2783 };
2784
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002785 // Use a dynamically initialized static to sort the table exactly once on
2786 // first run.
2787 static const bool SortOnce =
2788 (std::sort(std::begin(Infos), std::end(Infos),
2789 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2790 return LHS.BuiltinID < RHS.BuiltinID;
2791 }),
2792 true);
2793 (void)SortOnce;
2794
2795 const BuiltinInfo *F =
2796 std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2797 [](const BuiltinInfo &BI, unsigned BuiltinID) {
2798 return BI.BuiltinID < BuiltinID;
2799 });
2800 if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002801 return false;
2802
2803 bool Error = false;
2804
Reid Kleckner9e9606e2018-10-25 22:37:30 +00002805 for (const ArgInfo &A : F->Infos) {
2806 // Ignore empty ArgInfo elements.
2807 if (A.BitWidth == 0)
2808 continue;
2809
2810 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2811 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00002812 if (!A.Align) {
2813 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2814 } else {
2815 unsigned M = 1 << A.Align;
2816 Min *= M;
2817 Max *= M;
2818 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2819 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2820 }
2821 }
2822 return Error;
2823}
2824
Krzysztof Parzyszek762dee52018-07-12 18:54:04 +00002825bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2826 CallExpr *TheCall) {
2827 return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2828 CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2829}
2830
2831
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002832// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2833// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2834// ordering for DSP is unspecified. MSA is ordered by the data format used
2835// by the underlying instruction i.e., df/m, df/n and then by size.
2836//
2837// FIXME: The size tests here should instead be tablegen'd along with the
2838// definitions from include/clang/Basic/BuiltinsMips.def.
2839// FIXME: GCC is strict on signedness for some of these intrinsics, we should
2840// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002841bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002842 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002843 switch (BuiltinID) {
2844 default: return false;
2845 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2846 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00002847 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2848 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2849 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2850 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2851 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002852 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
2853 // df/m field.
2854 // These intrinsics take an unsigned 3 bit immediate.
2855 case Mips::BI__builtin_msa_bclri_b:
2856 case Mips::BI__builtin_msa_bnegi_b:
2857 case Mips::BI__builtin_msa_bseti_b:
2858 case Mips::BI__builtin_msa_sat_s_b:
2859 case Mips::BI__builtin_msa_sat_u_b:
2860 case Mips::BI__builtin_msa_slli_b:
2861 case Mips::BI__builtin_msa_srai_b:
2862 case Mips::BI__builtin_msa_srari_b:
2863 case Mips::BI__builtin_msa_srli_b:
2864 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2865 case Mips::BI__builtin_msa_binsli_b:
2866 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2867 // These intrinsics take an unsigned 4 bit immediate.
2868 case Mips::BI__builtin_msa_bclri_h:
2869 case Mips::BI__builtin_msa_bnegi_h:
2870 case Mips::BI__builtin_msa_bseti_h:
2871 case Mips::BI__builtin_msa_sat_s_h:
2872 case Mips::BI__builtin_msa_sat_u_h:
2873 case Mips::BI__builtin_msa_slli_h:
2874 case Mips::BI__builtin_msa_srai_h:
2875 case Mips::BI__builtin_msa_srari_h:
2876 case Mips::BI__builtin_msa_srli_h:
2877 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2878 case Mips::BI__builtin_msa_binsli_h:
2879 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002880 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002881 // The first block of intrinsics actually have an unsigned 5 bit field,
2882 // not a df/n field.
2883 case Mips::BI__builtin_msa_clei_u_b:
2884 case Mips::BI__builtin_msa_clei_u_h:
2885 case Mips::BI__builtin_msa_clei_u_w:
2886 case Mips::BI__builtin_msa_clei_u_d:
2887 case Mips::BI__builtin_msa_clti_u_b:
2888 case Mips::BI__builtin_msa_clti_u_h:
2889 case Mips::BI__builtin_msa_clti_u_w:
2890 case Mips::BI__builtin_msa_clti_u_d:
2891 case Mips::BI__builtin_msa_maxi_u_b:
2892 case Mips::BI__builtin_msa_maxi_u_h:
2893 case Mips::BI__builtin_msa_maxi_u_w:
2894 case Mips::BI__builtin_msa_maxi_u_d:
2895 case Mips::BI__builtin_msa_mini_u_b:
2896 case Mips::BI__builtin_msa_mini_u_h:
2897 case Mips::BI__builtin_msa_mini_u_w:
2898 case Mips::BI__builtin_msa_mini_u_d:
2899 case Mips::BI__builtin_msa_addvi_b:
2900 case Mips::BI__builtin_msa_addvi_h:
2901 case Mips::BI__builtin_msa_addvi_w:
2902 case Mips::BI__builtin_msa_addvi_d:
2903 case Mips::BI__builtin_msa_bclri_w:
2904 case Mips::BI__builtin_msa_bnegi_w:
2905 case Mips::BI__builtin_msa_bseti_w:
2906 case Mips::BI__builtin_msa_sat_s_w:
2907 case Mips::BI__builtin_msa_sat_u_w:
2908 case Mips::BI__builtin_msa_slli_w:
2909 case Mips::BI__builtin_msa_srai_w:
2910 case Mips::BI__builtin_msa_srari_w:
2911 case Mips::BI__builtin_msa_srli_w:
2912 case Mips::BI__builtin_msa_srlri_w:
2913 case Mips::BI__builtin_msa_subvi_b:
2914 case Mips::BI__builtin_msa_subvi_h:
2915 case Mips::BI__builtin_msa_subvi_w:
2916 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2917 case Mips::BI__builtin_msa_binsli_w:
2918 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2919 // These intrinsics take an unsigned 6 bit immediate.
2920 case Mips::BI__builtin_msa_bclri_d:
2921 case Mips::BI__builtin_msa_bnegi_d:
2922 case Mips::BI__builtin_msa_bseti_d:
2923 case Mips::BI__builtin_msa_sat_s_d:
2924 case Mips::BI__builtin_msa_sat_u_d:
2925 case Mips::BI__builtin_msa_slli_d:
2926 case Mips::BI__builtin_msa_srai_d:
2927 case Mips::BI__builtin_msa_srari_d:
2928 case Mips::BI__builtin_msa_srli_d:
2929 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2930 case Mips::BI__builtin_msa_binsli_d:
2931 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2932 // These intrinsics take a signed 5 bit immediate.
2933 case Mips::BI__builtin_msa_ceqi_b:
2934 case Mips::BI__builtin_msa_ceqi_h:
2935 case Mips::BI__builtin_msa_ceqi_w:
2936 case Mips::BI__builtin_msa_ceqi_d:
2937 case Mips::BI__builtin_msa_clti_s_b:
2938 case Mips::BI__builtin_msa_clti_s_h:
2939 case Mips::BI__builtin_msa_clti_s_w:
2940 case Mips::BI__builtin_msa_clti_s_d:
2941 case Mips::BI__builtin_msa_clei_s_b:
2942 case Mips::BI__builtin_msa_clei_s_h:
2943 case Mips::BI__builtin_msa_clei_s_w:
2944 case Mips::BI__builtin_msa_clei_s_d:
2945 case Mips::BI__builtin_msa_maxi_s_b:
2946 case Mips::BI__builtin_msa_maxi_s_h:
2947 case Mips::BI__builtin_msa_maxi_s_w:
2948 case Mips::BI__builtin_msa_maxi_s_d:
2949 case Mips::BI__builtin_msa_mini_s_b:
2950 case Mips::BI__builtin_msa_mini_s_h:
2951 case Mips::BI__builtin_msa_mini_s_w:
2952 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2953 // These intrinsics take an unsigned 8 bit immediate.
2954 case Mips::BI__builtin_msa_andi_b:
2955 case Mips::BI__builtin_msa_nori_b:
2956 case Mips::BI__builtin_msa_ori_b:
2957 case Mips::BI__builtin_msa_shf_b:
2958 case Mips::BI__builtin_msa_shf_h:
2959 case Mips::BI__builtin_msa_shf_w:
2960 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2961 case Mips::BI__builtin_msa_bseli_b:
2962 case Mips::BI__builtin_msa_bmnzi_b:
2963 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2964 // df/n format
2965 // These intrinsics take an unsigned 4 bit immediate.
2966 case Mips::BI__builtin_msa_copy_s_b:
2967 case Mips::BI__builtin_msa_copy_u_b:
2968 case Mips::BI__builtin_msa_insve_b:
2969 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002970 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2971 // These intrinsics take an unsigned 3 bit immediate.
2972 case Mips::BI__builtin_msa_copy_s_h:
2973 case Mips::BI__builtin_msa_copy_u_h:
2974 case Mips::BI__builtin_msa_insve_h:
2975 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002976 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2977 // These intrinsics take an unsigned 2 bit immediate.
2978 case Mips::BI__builtin_msa_copy_s_w:
2979 case Mips::BI__builtin_msa_copy_u_w:
2980 case Mips::BI__builtin_msa_insve_w:
2981 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002982 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2983 // These intrinsics take an unsigned 1 bit immediate.
2984 case Mips::BI__builtin_msa_copy_s_d:
2985 case Mips::BI__builtin_msa_copy_u_d:
2986 case Mips::BI__builtin_msa_insve_d:
2987 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002988 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2989 // Memory offsets and immediate loads.
2990 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00002991 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002992 case Mips::BI__builtin_msa_ldi_h:
2993 case Mips::BI__builtin_msa_ldi_w:
2994 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2995 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2996 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2997 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2998 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2999 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
3000 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
3001 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
3002 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00003003 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003004
Simon Dardis1f90f2d2016-10-19 17:50:52 +00003005 if (!m)
3006 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3007
3008 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3009 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00003010}
3011
Kit Bartone50adcb2015-03-30 19:40:59 +00003012bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3013 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003014 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3015 BuiltinID == PPC::BI__builtin_divdeu ||
3016 BuiltinID == PPC::BI__builtin_bpermd;
3017 bool IsTarget64Bit = Context.getTargetInfo()
3018 .getTypeWidth(Context
3019 .getTargetInfo()
3020 .getIntPtrType()) == 64;
3021 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3022 BuiltinID == PPC::BI__builtin_divweu ||
3023 BuiltinID == PPC::BI__builtin_divde ||
3024 BuiltinID == PPC::BI__builtin_divdeu;
3025
3026 if (Is64BitBltin && !IsTarget64Bit)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003027 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3028 << TheCall->getSourceRange();
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003029
3030 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3031 (BuiltinID == PPC::BI__builtin_bpermd &&
3032 !Context.getTargetInfo().hasFeature("bpermd")))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003033 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00003034 << TheCall->getSourceRange();
3035
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003036 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3037 if (!Context.getTargetInfo().hasFeature("vsx"))
3038 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3039 << TheCall->getSourceRange();
3040 return false;
3041 };
3042
Kit Bartone50adcb2015-03-30 19:40:59 +00003043 switch (BuiltinID) {
3044 default: return false;
3045 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3046 case PPC::BI__builtin_altivec_crypto_vshasigmad:
3047 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3048 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3049 case PPC::BI__builtin_tbegin:
3050 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3051 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3052 case PPC::BI__builtin_tabortwc:
3053 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3054 case PPC::BI__builtin_tabortwci:
3055 case PPC::BI__builtin_tabortdci:
3056 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3057 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00003058 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00003059 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00003060 return SemaBuiltinVSX(TheCall);
QingShan Zhangaccb65b2018-09-20 05:04:57 +00003061 case PPC::BI__builtin_unpack_vector_int128:
3062 return SemaVSXCheck(TheCall) ||
3063 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3064 case PPC::BI__builtin_pack_vector_int128:
3065 return SemaVSXCheck(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00003066 }
3067 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3068}
3069
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003070bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3071 CallExpr *TheCall) {
3072 if (BuiltinID == SystemZ::BI__builtin_tabort) {
3073 Expr *Arg = TheCall->getArg(0);
3074 llvm::APSInt AbortCode(32);
3075 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3076 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003077 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003078 << Arg->getSourceRange();
3079 }
3080
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003081 // For intrinsics which take an immediate value as part of the instruction,
3082 // range check them here.
3083 unsigned i = 0, l = 0, u = 0;
3084 switch (BuiltinID) {
3085 default: return false;
3086 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3087 case SystemZ::BI__builtin_s390_verimb:
3088 case SystemZ::BI__builtin_s390_verimh:
3089 case SystemZ::BI__builtin_s390_verimf:
3090 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3091 case SystemZ::BI__builtin_s390_vfaeb:
3092 case SystemZ::BI__builtin_s390_vfaeh:
3093 case SystemZ::BI__builtin_s390_vfaef:
3094 case SystemZ::BI__builtin_s390_vfaebs:
3095 case SystemZ::BI__builtin_s390_vfaehs:
3096 case SystemZ::BI__builtin_s390_vfaefs:
3097 case SystemZ::BI__builtin_s390_vfaezb:
3098 case SystemZ::BI__builtin_s390_vfaezh:
3099 case SystemZ::BI__builtin_s390_vfaezf:
3100 case SystemZ::BI__builtin_s390_vfaezbs:
3101 case SystemZ::BI__builtin_s390_vfaezhs:
3102 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003103 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003104 case SystemZ::BI__builtin_s390_vfidb:
3105 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3106 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003107 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003108 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3109 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3110 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3111 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3112 case SystemZ::BI__builtin_s390_vstrcb:
3113 case SystemZ::BI__builtin_s390_vstrch:
3114 case SystemZ::BI__builtin_s390_vstrcf:
3115 case SystemZ::BI__builtin_s390_vstrczb:
3116 case SystemZ::BI__builtin_s390_vstrczh:
3117 case SystemZ::BI__builtin_s390_vstrczf:
3118 case SystemZ::BI__builtin_s390_vstrcbs:
3119 case SystemZ::BI__builtin_s390_vstrchs:
3120 case SystemZ::BI__builtin_s390_vstrcfs:
3121 case SystemZ::BI__builtin_s390_vstrczbs:
3122 case SystemZ::BI__builtin_s390_vstrczhs:
3123 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00003124 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3125 case SystemZ::BI__builtin_s390_vfminsb:
3126 case SystemZ::BI__builtin_s390_vfmaxsb:
3127 case SystemZ::BI__builtin_s390_vfmindb:
3128 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00003129 }
3130 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00003131}
3132
Craig Topper5ba2c502015-11-07 08:08:31 +00003133/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3134/// This checks that the target supports __builtin_cpu_supports and
3135/// that the string argument is constant and valid.
3136static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3137 Expr *Arg = TheCall->getArg(0);
3138
3139 // Check if the argument is a string literal.
3140 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003141 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper5ba2c502015-11-07 08:08:31 +00003142 << Arg->getSourceRange();
3143
3144 // Check the contents of the string.
3145 StringRef Feature =
3146 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3147 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003148 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
Craig Topper5ba2c502015-11-07 08:08:31 +00003149 << Arg->getSourceRange();
3150 return false;
3151}
3152
Craig Topper699ae0c2017-08-10 20:28:30 +00003153/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3154/// This checks that the target supports __builtin_cpu_is and
3155/// that the string argument is constant and valid.
3156static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3157 Expr *Arg = TheCall->getArg(0);
3158
3159 // Check if the argument is a string literal.
3160 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003161 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Craig Topper699ae0c2017-08-10 20:28:30 +00003162 << Arg->getSourceRange();
3163
3164 // Check the contents of the string.
3165 StringRef Feature =
3166 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3167 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003168 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
Craig Topper699ae0c2017-08-10 20:28:30 +00003169 << Arg->getSourceRange();
3170 return false;
3171}
3172
Craig Toppera7e253e2016-09-23 04:48:31 +00003173// Check if the rounding mode is legal.
3174bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3175 // Indicates if this instruction has rounding control or just SAE.
3176 bool HasRC = false;
3177
3178 unsigned ArgNum = 0;
3179 switch (BuiltinID) {
3180 default:
3181 return false;
3182 case X86::BI__builtin_ia32_vcvttsd2si32:
3183 case X86::BI__builtin_ia32_vcvttsd2si64:
3184 case X86::BI__builtin_ia32_vcvttsd2usi32:
3185 case X86::BI__builtin_ia32_vcvttsd2usi64:
3186 case X86::BI__builtin_ia32_vcvttss2si32:
3187 case X86::BI__builtin_ia32_vcvttss2si64:
3188 case X86::BI__builtin_ia32_vcvttss2usi32:
3189 case X86::BI__builtin_ia32_vcvttss2usi64:
3190 ArgNum = 1;
3191 break;
Craig Topper2da60bc2018-06-21 05:01:01 +00003192 case X86::BI__builtin_ia32_maxpd512:
3193 case X86::BI__builtin_ia32_maxps512:
3194 case X86::BI__builtin_ia32_minpd512:
3195 case X86::BI__builtin_ia32_minps512:
3196 ArgNum = 2;
3197 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003198 case X86::BI__builtin_ia32_cvtps2pd512_mask:
3199 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3200 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3201 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3202 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3203 case X86::BI__builtin_ia32_cvttps2dq512_mask:
3204 case X86::BI__builtin_ia32_cvttps2qq512_mask:
3205 case X86::BI__builtin_ia32_cvttps2udq512_mask:
3206 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3207 case X86::BI__builtin_ia32_exp2pd_mask:
3208 case X86::BI__builtin_ia32_exp2ps_mask:
3209 case X86::BI__builtin_ia32_getexppd512_mask:
3210 case X86::BI__builtin_ia32_getexpps512_mask:
3211 case X86::BI__builtin_ia32_rcp28pd_mask:
3212 case X86::BI__builtin_ia32_rcp28ps_mask:
3213 case X86::BI__builtin_ia32_rsqrt28pd_mask:
3214 case X86::BI__builtin_ia32_rsqrt28ps_mask:
3215 case X86::BI__builtin_ia32_vcomisd:
3216 case X86::BI__builtin_ia32_vcomiss:
3217 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3218 ArgNum = 3;
3219 break;
3220 case X86::BI__builtin_ia32_cmppd512_mask:
3221 case X86::BI__builtin_ia32_cmpps512_mask:
3222 case X86::BI__builtin_ia32_cmpsd_mask:
3223 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003224 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003225 case X86::BI__builtin_ia32_getexpsd128_round_mask:
3226 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003227 case X86::BI__builtin_ia32_maxsd_round_mask:
3228 case X86::BI__builtin_ia32_maxss_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003229 case X86::BI__builtin_ia32_minsd_round_mask:
3230 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00003231 case X86::BI__builtin_ia32_rcp28sd_round_mask:
3232 case X86::BI__builtin_ia32_rcp28ss_round_mask:
3233 case X86::BI__builtin_ia32_reducepd512_mask:
3234 case X86::BI__builtin_ia32_reduceps512_mask:
3235 case X86::BI__builtin_ia32_rndscalepd_mask:
3236 case X86::BI__builtin_ia32_rndscaleps_mask:
3237 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3238 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3239 ArgNum = 4;
3240 break;
3241 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003242 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003243 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003244 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003245 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003246 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003247 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003248 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00003249 case X86::BI__builtin_ia32_rangepd512_mask:
3250 case X86::BI__builtin_ia32_rangeps512_mask:
3251 case X86::BI__builtin_ia32_rangesd128_round_mask:
3252 case X86::BI__builtin_ia32_rangess128_round_mask:
3253 case X86::BI__builtin_ia32_reducesd_mask:
3254 case X86::BI__builtin_ia32_reducess_mask:
3255 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3256 case X86::BI__builtin_ia32_rndscaless_round_mask:
3257 ArgNum = 5;
3258 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003259 case X86::BI__builtin_ia32_vcvtsd2si64:
3260 case X86::BI__builtin_ia32_vcvtsd2si32:
3261 case X86::BI__builtin_ia32_vcvtsd2usi32:
3262 case X86::BI__builtin_ia32_vcvtsd2usi64:
3263 case X86::BI__builtin_ia32_vcvtss2si32:
3264 case X86::BI__builtin_ia32_vcvtss2si64:
3265 case X86::BI__builtin_ia32_vcvtss2usi32:
3266 case X86::BI__builtin_ia32_vcvtss2usi64:
Craig Topper8bf793f2018-06-29 05:43:33 +00003267 case X86::BI__builtin_ia32_sqrtpd512:
3268 case X86::BI__builtin_ia32_sqrtps512:
Craig Topper7609f1c2016-10-01 21:03:50 +00003269 ArgNum = 1;
3270 HasRC = true;
3271 break;
Craig Topper3614b412018-06-10 06:01:42 +00003272 case X86::BI__builtin_ia32_addpd512:
3273 case X86::BI__builtin_ia32_addps512:
3274 case X86::BI__builtin_ia32_divpd512:
3275 case X86::BI__builtin_ia32_divps512:
3276 case X86::BI__builtin_ia32_mulpd512:
3277 case X86::BI__builtin_ia32_mulps512:
3278 case X86::BI__builtin_ia32_subpd512:
3279 case X86::BI__builtin_ia32_subps512:
Craig Topper8e066312016-11-07 07:01:09 +00003280 case X86::BI__builtin_ia32_cvtsi2sd64:
3281 case X86::BI__builtin_ia32_cvtsi2ss32:
3282 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00003283 case X86::BI__builtin_ia32_cvtusi2sd64:
3284 case X86::BI__builtin_ia32_cvtusi2ss32:
3285 case X86::BI__builtin_ia32_cvtusi2ss64:
3286 ArgNum = 2;
3287 HasRC = true;
3288 break;
3289 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3290 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3291 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3292 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3293 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3294 case X86::BI__builtin_ia32_cvtps2qq512_mask:
3295 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3296 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3297 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3298 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3299 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3300 ArgNum = 3;
3301 HasRC = true;
3302 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00003303 case X86::BI__builtin_ia32_addss_round_mask:
3304 case X86::BI__builtin_ia32_addsd_round_mask:
3305 case X86::BI__builtin_ia32_divss_round_mask:
3306 case X86::BI__builtin_ia32_divsd_round_mask:
3307 case X86::BI__builtin_ia32_mulss_round_mask:
3308 case X86::BI__builtin_ia32_mulsd_round_mask:
3309 case X86::BI__builtin_ia32_subss_round_mask:
3310 case X86::BI__builtin_ia32_subsd_round_mask:
3311 case X86::BI__builtin_ia32_scalefpd512_mask:
3312 case X86::BI__builtin_ia32_scalefps512_mask:
3313 case X86::BI__builtin_ia32_scalefsd_round_mask:
3314 case X86::BI__builtin_ia32_scalefss_round_mask:
3315 case X86::BI__builtin_ia32_getmantpd512_mask:
3316 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00003317 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3318 case X86::BI__builtin_ia32_sqrtsd_round_mask:
3319 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00003320 case X86::BI__builtin_ia32_vfmaddsd3_mask:
3321 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3322 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3323 case X86::BI__builtin_ia32_vfmaddss3_mask:
3324 case X86::BI__builtin_ia32_vfmaddss3_maskz:
3325 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00003326 case X86::BI__builtin_ia32_vfmaddpd512_mask:
3327 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3328 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3329 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3330 case X86::BI__builtin_ia32_vfmaddps512_mask:
3331 case X86::BI__builtin_ia32_vfmaddps512_maskz:
3332 case X86::BI__builtin_ia32_vfmaddps512_mask3:
3333 case X86::BI__builtin_ia32_vfmsubps512_mask3:
3334 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3335 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3336 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3337 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3338 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3339 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3340 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3341 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00003342 ArgNum = 4;
3343 HasRC = true;
3344 break;
3345 case X86::BI__builtin_ia32_getmantsd_round_mask:
3346 case X86::BI__builtin_ia32_getmantss_round_mask:
3347 ArgNum = 5;
3348 HasRC = true;
3349 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00003350 }
3351
3352 llvm::APSInt Result;
3353
3354 // We can't check the value of a dependent argument.
3355 Expr *Arg = TheCall->getArg(ArgNum);
3356 if (Arg->isTypeDependent() || Arg->isValueDependent())
3357 return false;
3358
3359 // Check constant-ness first.
3360 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3361 return true;
3362
3363 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3364 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3365 // combined with ROUND_NO_EXC.
3366 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3367 Result == 8/*ROUND_NO_EXC*/ ||
3368 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3369 return false;
3370
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003371 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3372 << Arg->getSourceRange();
Craig Toppera7e253e2016-09-23 04:48:31 +00003373}
3374
Craig Topperdf5beb22017-03-13 17:16:50 +00003375// Check if the gather/scatter scale is legal.
3376bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3377 CallExpr *TheCall) {
3378 unsigned ArgNum = 0;
3379 switch (BuiltinID) {
3380 default:
3381 return false;
3382 case X86::BI__builtin_ia32_gatherpfdpd:
3383 case X86::BI__builtin_ia32_gatherpfdps:
3384 case X86::BI__builtin_ia32_gatherpfqpd:
3385 case X86::BI__builtin_ia32_gatherpfqps:
3386 case X86::BI__builtin_ia32_scatterpfdpd:
3387 case X86::BI__builtin_ia32_scatterpfdps:
3388 case X86::BI__builtin_ia32_scatterpfqpd:
3389 case X86::BI__builtin_ia32_scatterpfqps:
3390 ArgNum = 3;
3391 break;
3392 case X86::BI__builtin_ia32_gatherd_pd:
3393 case X86::BI__builtin_ia32_gatherd_pd256:
3394 case X86::BI__builtin_ia32_gatherq_pd:
3395 case X86::BI__builtin_ia32_gatherq_pd256:
3396 case X86::BI__builtin_ia32_gatherd_ps:
3397 case X86::BI__builtin_ia32_gatherd_ps256:
3398 case X86::BI__builtin_ia32_gatherq_ps:
3399 case X86::BI__builtin_ia32_gatherq_ps256:
3400 case X86::BI__builtin_ia32_gatherd_q:
3401 case X86::BI__builtin_ia32_gatherd_q256:
3402 case X86::BI__builtin_ia32_gatherq_q:
3403 case X86::BI__builtin_ia32_gatherq_q256:
3404 case X86::BI__builtin_ia32_gatherd_d:
3405 case X86::BI__builtin_ia32_gatherd_d256:
3406 case X86::BI__builtin_ia32_gatherq_d:
3407 case X86::BI__builtin_ia32_gatherq_d256:
3408 case X86::BI__builtin_ia32_gather3div2df:
3409 case X86::BI__builtin_ia32_gather3div2di:
3410 case X86::BI__builtin_ia32_gather3div4df:
3411 case X86::BI__builtin_ia32_gather3div4di:
3412 case X86::BI__builtin_ia32_gather3div4sf:
3413 case X86::BI__builtin_ia32_gather3div4si:
3414 case X86::BI__builtin_ia32_gather3div8sf:
3415 case X86::BI__builtin_ia32_gather3div8si:
3416 case X86::BI__builtin_ia32_gather3siv2df:
3417 case X86::BI__builtin_ia32_gather3siv2di:
3418 case X86::BI__builtin_ia32_gather3siv4df:
3419 case X86::BI__builtin_ia32_gather3siv4di:
3420 case X86::BI__builtin_ia32_gather3siv4sf:
3421 case X86::BI__builtin_ia32_gather3siv4si:
3422 case X86::BI__builtin_ia32_gather3siv8sf:
3423 case X86::BI__builtin_ia32_gather3siv8si:
3424 case X86::BI__builtin_ia32_gathersiv8df:
3425 case X86::BI__builtin_ia32_gathersiv16sf:
3426 case X86::BI__builtin_ia32_gatherdiv8df:
3427 case X86::BI__builtin_ia32_gatherdiv16sf:
3428 case X86::BI__builtin_ia32_gathersiv8di:
3429 case X86::BI__builtin_ia32_gathersiv16si:
3430 case X86::BI__builtin_ia32_gatherdiv8di:
3431 case X86::BI__builtin_ia32_gatherdiv16si:
3432 case X86::BI__builtin_ia32_scatterdiv2df:
3433 case X86::BI__builtin_ia32_scatterdiv2di:
3434 case X86::BI__builtin_ia32_scatterdiv4df:
3435 case X86::BI__builtin_ia32_scatterdiv4di:
3436 case X86::BI__builtin_ia32_scatterdiv4sf:
3437 case X86::BI__builtin_ia32_scatterdiv4si:
3438 case X86::BI__builtin_ia32_scatterdiv8sf:
3439 case X86::BI__builtin_ia32_scatterdiv8si:
3440 case X86::BI__builtin_ia32_scattersiv2df:
3441 case X86::BI__builtin_ia32_scattersiv2di:
3442 case X86::BI__builtin_ia32_scattersiv4df:
3443 case X86::BI__builtin_ia32_scattersiv4di:
3444 case X86::BI__builtin_ia32_scattersiv4sf:
3445 case X86::BI__builtin_ia32_scattersiv4si:
3446 case X86::BI__builtin_ia32_scattersiv8sf:
3447 case X86::BI__builtin_ia32_scattersiv8si:
3448 case X86::BI__builtin_ia32_scattersiv8df:
3449 case X86::BI__builtin_ia32_scattersiv16sf:
3450 case X86::BI__builtin_ia32_scatterdiv8df:
3451 case X86::BI__builtin_ia32_scatterdiv16sf:
3452 case X86::BI__builtin_ia32_scattersiv8di:
3453 case X86::BI__builtin_ia32_scattersiv16si:
3454 case X86::BI__builtin_ia32_scatterdiv8di:
3455 case X86::BI__builtin_ia32_scatterdiv16si:
3456 ArgNum = 4;
3457 break;
3458 }
3459
3460 llvm::APSInt Result;
3461
3462 // We can't check the value of a dependent argument.
3463 Expr *Arg = TheCall->getArg(ArgNum);
3464 if (Arg->isTypeDependent() || Arg->isValueDependent())
3465 return false;
3466
3467 // Check constant-ness first.
3468 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3469 return true;
3470
3471 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3472 return false;
3473
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003474 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3475 << Arg->getSourceRange();
Craig Topperdf5beb22017-03-13 17:16:50 +00003476}
3477
Craig Topper51738f82018-04-26 20:14:46 +00003478static bool isX86_32Builtin(unsigned BuiltinID) {
3479 // These builtins only work on x86-32 targets.
3480 switch (BuiltinID) {
3481 case X86::BI__builtin_ia32_readeflags_u32:
3482 case X86::BI__builtin_ia32_writeeflags_u32:
3483 return true;
3484 }
3485
3486 return false;
3487}
3488
Craig Topperf0ddc892016-09-23 04:48:27 +00003489bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3490 if (BuiltinID == X86::BI__builtin_cpu_supports)
3491 return SemaBuiltinCpuSupports(*this, TheCall);
3492
Craig Topper699ae0c2017-08-10 20:28:30 +00003493 if (BuiltinID == X86::BI__builtin_cpu_is)
3494 return SemaBuiltinCpuIs(*this, TheCall);
3495
Craig Topper51738f82018-04-26 20:14:46 +00003496 // Check for 32-bit only builtins on a 64-bit target.
3497 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3498 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003499 return Diag(TheCall->getCallee()->getBeginLoc(),
Craig Topper51738f82018-04-26 20:14:46 +00003500 diag::err_32_bit_builtin_64_bit_tgt);
3501
Craig Toppera7e253e2016-09-23 04:48:31 +00003502 // If the intrinsic has rounding or SAE make sure its valid.
3503 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3504 return true;
3505
Craig Topperdf5beb22017-03-13 17:16:50 +00003506 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3507 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3508 return true;
3509
Craig Topperf0ddc892016-09-23 04:48:27 +00003510 // For intrinsics which take an immediate value as part of the instruction,
3511 // range check them here.
3512 int i = 0, l = 0, u = 0;
3513 switch (BuiltinID) {
3514 default:
3515 return false;
Craig Topper11899b02018-06-05 21:54:35 +00003516 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00003517 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003518 case X86::BI__builtin_ia32_vextractf128_pd256:
3519 case X86::BI__builtin_ia32_vextractf128_ps256:
3520 case X86::BI__builtin_ia32_vextractf128_si256:
3521 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00003522 case X86::BI__builtin_ia32_extractf64x4_mask:
3523 case X86::BI__builtin_ia32_extracti64x4_mask:
3524 case X86::BI__builtin_ia32_extractf32x8_mask:
3525 case X86::BI__builtin_ia32_extracti32x8_mask:
3526 case X86::BI__builtin_ia32_extractf64x2_256_mask:
3527 case X86::BI__builtin_ia32_extracti64x2_256_mask:
3528 case X86::BI__builtin_ia32_extractf32x4_256_mask:
3529 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003530 i = 1; l = 0; u = 1;
3531 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003532 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00003533 case X86::BI__builtin_ia32_vinsertf128_pd256:
3534 case X86::BI__builtin_ia32_vinsertf128_ps256:
3535 case X86::BI__builtin_ia32_vinsertf128_si256:
3536 case X86::BI__builtin_ia32_insert128i256:
3537 case X86::BI__builtin_ia32_insertf32x8:
3538 case X86::BI__builtin_ia32_inserti32x8:
3539 case X86::BI__builtin_ia32_insertf64x4:
3540 case X86::BI__builtin_ia32_inserti64x4:
3541 case X86::BI__builtin_ia32_insertf64x2_256:
3542 case X86::BI__builtin_ia32_inserti64x2_256:
3543 case X86::BI__builtin_ia32_insertf32x4_256:
3544 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00003545 i = 2; l = 0; u = 1;
3546 break;
Craig Topperacf56012018-06-08 00:59:27 +00003547 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00003548 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003549 case X86::BI__builtin_ia32_vec_ext_v4si:
3550 case X86::BI__builtin_ia32_vec_ext_v4sf:
3551 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00003552 case X86::BI__builtin_ia32_extractf32x4_mask:
3553 case X86::BI__builtin_ia32_extracti32x4_mask:
3554 case X86::BI__builtin_ia32_extractf64x2_512_mask:
3555 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00003556 i = 1; l = 0; u = 3;
3557 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003558 case X86::BI_mm_prefetch:
3559 case X86::BI__builtin_ia32_vec_ext_v8hi:
3560 case X86::BI__builtin_ia32_vec_ext_v8si:
3561 i = 1; l = 0; u = 7;
3562 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00003563 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00003564 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00003565 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00003566 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00003567 case X86::BI__builtin_ia32_vec_set_v4si:
3568 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00003569 case X86::BI__builtin_ia32_shuf_f32x4_256:
3570 case X86::BI__builtin_ia32_shuf_f64x2_256:
3571 case X86::BI__builtin_ia32_shuf_i32x4_256:
3572 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00003573 case X86::BI__builtin_ia32_insertf64x2_512:
3574 case X86::BI__builtin_ia32_inserti64x2_512:
3575 case X86::BI__builtin_ia32_insertf32x4:
3576 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00003577 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003578 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00003579 case X86::BI__builtin_ia32_vpermil2pd:
3580 case X86::BI__builtin_ia32_vpermil2pd256:
3581 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00003582 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00003583 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00003584 break;
Craig Topper95b0d732015-01-25 23:30:05 +00003585 case X86::BI__builtin_ia32_cmpb128_mask:
3586 case X86::BI__builtin_ia32_cmpw128_mask:
3587 case X86::BI__builtin_ia32_cmpd128_mask:
3588 case X86::BI__builtin_ia32_cmpq128_mask:
3589 case X86::BI__builtin_ia32_cmpb256_mask:
3590 case X86::BI__builtin_ia32_cmpw256_mask:
3591 case X86::BI__builtin_ia32_cmpd256_mask:
3592 case X86::BI__builtin_ia32_cmpq256_mask:
3593 case X86::BI__builtin_ia32_cmpb512_mask:
3594 case X86::BI__builtin_ia32_cmpw512_mask:
3595 case X86::BI__builtin_ia32_cmpd512_mask:
3596 case X86::BI__builtin_ia32_cmpq512_mask:
3597 case X86::BI__builtin_ia32_ucmpb128_mask:
3598 case X86::BI__builtin_ia32_ucmpw128_mask:
3599 case X86::BI__builtin_ia32_ucmpd128_mask:
3600 case X86::BI__builtin_ia32_ucmpq128_mask:
3601 case X86::BI__builtin_ia32_ucmpb256_mask:
3602 case X86::BI__builtin_ia32_ucmpw256_mask:
3603 case X86::BI__builtin_ia32_ucmpd256_mask:
3604 case X86::BI__builtin_ia32_ucmpq256_mask:
3605 case X86::BI__builtin_ia32_ucmpb512_mask:
3606 case X86::BI__builtin_ia32_ucmpw512_mask:
3607 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00003608 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00003609 case X86::BI__builtin_ia32_vpcomub:
3610 case X86::BI__builtin_ia32_vpcomuw:
3611 case X86::BI__builtin_ia32_vpcomud:
3612 case X86::BI__builtin_ia32_vpcomuq:
3613 case X86::BI__builtin_ia32_vpcomb:
3614 case X86::BI__builtin_ia32_vpcomw:
3615 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00003616 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00003617 case X86::BI__builtin_ia32_vec_set_v8hi:
3618 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00003619 i = 2; l = 0; u = 7;
3620 break;
Craig Topperacf56012018-06-08 00:59:27 +00003621 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003622 case X86::BI__builtin_ia32_roundps:
3623 case X86::BI__builtin_ia32_roundpd:
3624 case X86::BI__builtin_ia32_roundps256:
3625 case X86::BI__builtin_ia32_roundpd256:
Craig Topper03a1d482018-06-15 17:03:32 +00003626 case X86::BI__builtin_ia32_getmantpd128_mask:
3627 case X86::BI__builtin_ia32_getmantpd256_mask:
3628 case X86::BI__builtin_ia32_getmantps128_mask:
3629 case X86::BI__builtin_ia32_getmantps256_mask:
3630 case X86::BI__builtin_ia32_getmantpd512_mask:
3631 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003632 case X86::BI__builtin_ia32_vec_ext_v16qi:
3633 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003634 i = 1; l = 0; u = 15;
3635 break;
Craig Topper7d17d722018-06-08 00:00:21 +00003636 case X86::BI__builtin_ia32_pblendd128:
3637 case X86::BI__builtin_ia32_blendps:
3638 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00003639 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00003640 case X86::BI__builtin_ia32_roundss:
3641 case X86::BI__builtin_ia32_roundsd:
3642 case X86::BI__builtin_ia32_rangepd128_mask:
3643 case X86::BI__builtin_ia32_rangepd256_mask:
3644 case X86::BI__builtin_ia32_rangepd512_mask:
3645 case X86::BI__builtin_ia32_rangeps128_mask:
3646 case X86::BI__builtin_ia32_rangeps256_mask:
3647 case X86::BI__builtin_ia32_rangeps512_mask:
3648 case X86::BI__builtin_ia32_getmantsd_round_mask:
3649 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003650 case X86::BI__builtin_ia32_vec_set_v16qi:
3651 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00003652 i = 2; l = 0; u = 15;
3653 break;
Craig Topperf3914b72018-06-06 00:24:55 +00003654 case X86::BI__builtin_ia32_vec_ext_v32qi:
3655 i = 1; l = 0; u = 31;
3656 break;
Craig Topper39c87102016-05-18 03:18:12 +00003657 case X86::BI__builtin_ia32_cmpps:
3658 case X86::BI__builtin_ia32_cmpss:
3659 case X86::BI__builtin_ia32_cmppd:
3660 case X86::BI__builtin_ia32_cmpsd:
3661 case X86::BI__builtin_ia32_cmpps256:
3662 case X86::BI__builtin_ia32_cmppd256:
3663 case X86::BI__builtin_ia32_cmpps128_mask:
3664 case X86::BI__builtin_ia32_cmppd128_mask:
3665 case X86::BI__builtin_ia32_cmpps256_mask:
3666 case X86::BI__builtin_ia32_cmppd256_mask:
3667 case X86::BI__builtin_ia32_cmpps512_mask:
3668 case X86::BI__builtin_ia32_cmppd512_mask:
3669 case X86::BI__builtin_ia32_cmpsd_mask:
3670 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00003671 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00003672 i = 2; l = 0; u = 31;
3673 break;
Craig Topper03f4f042018-06-08 18:00:25 +00003674 case X86::BI__builtin_ia32_permdf256:
3675 case X86::BI__builtin_ia32_permdi256:
3676 case X86::BI__builtin_ia32_permdf512:
3677 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00003678 case X86::BI__builtin_ia32_vpermilps:
3679 case X86::BI__builtin_ia32_vpermilps256:
3680 case X86::BI__builtin_ia32_vpermilpd512:
3681 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00003682 case X86::BI__builtin_ia32_pshufd:
3683 case X86::BI__builtin_ia32_pshufd256:
3684 case X86::BI__builtin_ia32_pshufd512:
3685 case X86::BI__builtin_ia32_pshufhw:
3686 case X86::BI__builtin_ia32_pshufhw256:
3687 case X86::BI__builtin_ia32_pshufhw512:
3688 case X86::BI__builtin_ia32_pshuflw:
3689 case X86::BI__builtin_ia32_pshuflw256:
3690 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00003691 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00003692 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003693 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00003694 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3695 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00003696 case X86::BI__builtin_ia32_rndscaleps_128_mask:
3697 case X86::BI__builtin_ia32_rndscalepd_128_mask:
3698 case X86::BI__builtin_ia32_rndscaleps_256_mask:
3699 case X86::BI__builtin_ia32_rndscalepd_256_mask:
3700 case X86::BI__builtin_ia32_rndscaleps_mask:
3701 case X86::BI__builtin_ia32_rndscalepd_mask:
3702 case X86::BI__builtin_ia32_reducepd128_mask:
3703 case X86::BI__builtin_ia32_reducepd256_mask:
3704 case X86::BI__builtin_ia32_reducepd512_mask:
3705 case X86::BI__builtin_ia32_reduceps128_mask:
3706 case X86::BI__builtin_ia32_reduceps256_mask:
3707 case X86::BI__builtin_ia32_reduceps512_mask:
Craig Topper0e9de762018-06-30 01:32:14 +00003708 case X86::BI__builtin_ia32_prold512:
3709 case X86::BI__builtin_ia32_prolq512:
3710 case X86::BI__builtin_ia32_prold128:
3711 case X86::BI__builtin_ia32_prold256:
3712 case X86::BI__builtin_ia32_prolq128:
3713 case X86::BI__builtin_ia32_prolq256:
3714 case X86::BI__builtin_ia32_prord512:
3715 case X86::BI__builtin_ia32_prorq512:
3716 case X86::BI__builtin_ia32_prord128:
3717 case X86::BI__builtin_ia32_prord256:
3718 case X86::BI__builtin_ia32_prorq128:
3719 case X86::BI__builtin_ia32_prorq256:
Craig Topper39c87102016-05-18 03:18:12 +00003720 case X86::BI__builtin_ia32_fpclasspd128_mask:
3721 case X86::BI__builtin_ia32_fpclasspd256_mask:
3722 case X86::BI__builtin_ia32_fpclassps128_mask:
3723 case X86::BI__builtin_ia32_fpclassps256_mask:
3724 case X86::BI__builtin_ia32_fpclassps512_mask:
3725 case X86::BI__builtin_ia32_fpclasspd512_mask:
3726 case X86::BI__builtin_ia32_fpclasssd_mask:
3727 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper31730ae2018-06-14 22:02:35 +00003728 case X86::BI__builtin_ia32_pslldqi128_byteshift:
3729 case X86::BI__builtin_ia32_pslldqi256_byteshift:
3730 case X86::BI__builtin_ia32_pslldqi512_byteshift:
3731 case X86::BI__builtin_ia32_psrldqi128_byteshift:
3732 case X86::BI__builtin_ia32_psrldqi256_byteshift:
3733 case X86::BI__builtin_ia32_psrldqi512_byteshift:
Craig Topper2aa8efc2018-08-31 18:22:52 +00003734 case X86::BI__builtin_ia32_kshiftliqi:
3735 case X86::BI__builtin_ia32_kshiftlihi:
3736 case X86::BI__builtin_ia32_kshiftlisi:
3737 case X86::BI__builtin_ia32_kshiftlidi:
3738 case X86::BI__builtin_ia32_kshiftriqi:
3739 case X86::BI__builtin_ia32_kshiftrihi:
3740 case X86::BI__builtin_ia32_kshiftrisi:
3741 case X86::BI__builtin_ia32_kshiftridi:
Craig Topper39c87102016-05-18 03:18:12 +00003742 i = 1; l = 0; u = 255;
3743 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00003744 case X86::BI__builtin_ia32_vperm2f128_pd256:
3745 case X86::BI__builtin_ia32_vperm2f128_ps256:
3746 case X86::BI__builtin_ia32_vperm2f128_si256:
3747 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00003748 case X86::BI__builtin_ia32_pblendw128:
3749 case X86::BI__builtin_ia32_pblendw256:
3750 case X86::BI__builtin_ia32_blendps256:
3751 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00003752 case X86::BI__builtin_ia32_palignr128:
3753 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00003754 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00003755 case X86::BI__builtin_ia32_alignq512:
3756 case X86::BI__builtin_ia32_alignd512:
3757 case X86::BI__builtin_ia32_alignd128:
3758 case X86::BI__builtin_ia32_alignd256:
3759 case X86::BI__builtin_ia32_alignq128:
3760 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00003761 case X86::BI__builtin_ia32_vcomisd:
3762 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00003763 case X86::BI__builtin_ia32_shuf_f32x4:
3764 case X86::BI__builtin_ia32_shuf_f64x2:
3765 case X86::BI__builtin_ia32_shuf_i32x4:
3766 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00003767 case X86::BI__builtin_ia32_shufpd512:
3768 case X86::BI__builtin_ia32_shufps:
3769 case X86::BI__builtin_ia32_shufps256:
3770 case X86::BI__builtin_ia32_shufps512:
Craig Topper91bbe982018-06-11 06:18:29 +00003771 case X86::BI__builtin_ia32_dbpsadbw128:
3772 case X86::BI__builtin_ia32_dbpsadbw256:
3773 case X86::BI__builtin_ia32_dbpsadbw512:
Craig Topper2527c372018-06-13 07:19:28 +00003774 case X86::BI__builtin_ia32_vpshldd128:
3775 case X86::BI__builtin_ia32_vpshldd256:
3776 case X86::BI__builtin_ia32_vpshldd512:
3777 case X86::BI__builtin_ia32_vpshldq128:
3778 case X86::BI__builtin_ia32_vpshldq256:
3779 case X86::BI__builtin_ia32_vpshldq512:
3780 case X86::BI__builtin_ia32_vpshldw128:
3781 case X86::BI__builtin_ia32_vpshldw256:
3782 case X86::BI__builtin_ia32_vpshldw512:
3783 case X86::BI__builtin_ia32_vpshrdd128:
3784 case X86::BI__builtin_ia32_vpshrdd256:
3785 case X86::BI__builtin_ia32_vpshrdd512:
3786 case X86::BI__builtin_ia32_vpshrdq128:
3787 case X86::BI__builtin_ia32_vpshrdq256:
3788 case X86::BI__builtin_ia32_vpshrdq512:
3789 case X86::BI__builtin_ia32_vpshrdw128:
3790 case X86::BI__builtin_ia32_vpshrdw256:
3791 case X86::BI__builtin_ia32_vpshrdw512:
Craig Topper39c87102016-05-18 03:18:12 +00003792 i = 2; l = 0; u = 255;
3793 break;
3794 case X86::BI__builtin_ia32_fixupimmpd512_mask:
3795 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3796 case X86::BI__builtin_ia32_fixupimmps512_mask:
3797 case X86::BI__builtin_ia32_fixupimmps512_maskz:
3798 case X86::BI__builtin_ia32_fixupimmsd_mask:
3799 case X86::BI__builtin_ia32_fixupimmsd_maskz:
3800 case X86::BI__builtin_ia32_fixupimmss_mask:
3801 case X86::BI__builtin_ia32_fixupimmss_maskz:
3802 case X86::BI__builtin_ia32_fixupimmpd128_mask:
3803 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3804 case X86::BI__builtin_ia32_fixupimmpd256_mask:
3805 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3806 case X86::BI__builtin_ia32_fixupimmps128_mask:
3807 case X86::BI__builtin_ia32_fixupimmps128_maskz:
3808 case X86::BI__builtin_ia32_fixupimmps256_mask:
3809 case X86::BI__builtin_ia32_fixupimmps256_maskz:
3810 case X86::BI__builtin_ia32_pternlogd512_mask:
3811 case X86::BI__builtin_ia32_pternlogd512_maskz:
3812 case X86::BI__builtin_ia32_pternlogq512_mask:
3813 case X86::BI__builtin_ia32_pternlogq512_maskz:
3814 case X86::BI__builtin_ia32_pternlogd128_mask:
3815 case X86::BI__builtin_ia32_pternlogd128_maskz:
3816 case X86::BI__builtin_ia32_pternlogd256_mask:
3817 case X86::BI__builtin_ia32_pternlogd256_maskz:
3818 case X86::BI__builtin_ia32_pternlogq128_mask:
3819 case X86::BI__builtin_ia32_pternlogq128_maskz:
3820 case X86::BI__builtin_ia32_pternlogq256_mask:
3821 case X86::BI__builtin_ia32_pternlogq256_maskz:
3822 i = 3; l = 0; u = 255;
3823 break;
Craig Topper9625db02017-03-12 22:19:10 +00003824 case X86::BI__builtin_ia32_gatherpfdpd:
3825 case X86::BI__builtin_ia32_gatherpfdps:
3826 case X86::BI__builtin_ia32_gatherpfqpd:
3827 case X86::BI__builtin_ia32_gatherpfqps:
3828 case X86::BI__builtin_ia32_scatterpfdpd:
3829 case X86::BI__builtin_ia32_scatterpfdps:
3830 case X86::BI__builtin_ia32_scatterpfqpd:
3831 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00003832 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00003833 break;
Craig Topper39c87102016-05-18 03:18:12 +00003834 case X86::BI__builtin_ia32_rndscalesd_round_mask:
3835 case X86::BI__builtin_ia32_rndscaless_round_mask:
3836 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00003837 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003838 }
Chandler Carruth16e6bc22018-06-21 23:46:09 +00003839
3840 // Note that we don't force a hard error on the range check here, allowing
3841 // template-generated or macro-generated dead code to potentially have out-of-
3842 // range values. These need to code generate, but don't need to necessarily
3843 // make any sense. We use a warning that defaults to an error.
3844 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003845}
3846
Richard Smith55ce3522012-06-25 20:30:08 +00003847/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3848/// parameter with the FormatAttr's correct format_idx and firstDataArg.
3849/// Returns true when the format fits the function and the FormatStringInfo has
3850/// been populated.
3851bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3852 FormatStringInfo *FSI) {
3853 FSI->HasVAListArg = Format->getFirstArg() == 0;
3854 FSI->FormatIdx = Format->getFormatIdx() - 1;
3855 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003856
Richard Smith55ce3522012-06-25 20:30:08 +00003857 // The way the format attribute works in GCC, the implicit this argument
3858 // of member functions is counted. However, it doesn't appear in our own
3859 // lists, so decrement format_idx in that case.
3860 if (IsCXXMember) {
3861 if(FSI->FormatIdx == 0)
3862 return false;
3863 --FSI->FormatIdx;
3864 if (FSI->FirstDataArg != 0)
3865 --FSI->FirstDataArg;
3866 }
3867 return true;
3868}
Mike Stump11289f42009-09-09 15:08:12 +00003869
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003870/// Checks if a the given expression evaluates to null.
3871///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003872/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00003873static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003874 // If the expression has non-null type, it doesn't evaluate to null.
3875 if (auto nullability
3876 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3877 if (*nullability == NullabilityKind::NonNull)
3878 return false;
3879 }
3880
Ted Kremeneka146db32014-01-17 06:24:47 +00003881 // As a special case, transparent unions initialized with zero are
3882 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003883 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00003884 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3885 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003886 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00003887 if (const InitListExpr *ILE =
3888 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003889 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00003890 }
3891
3892 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00003893 return (!Expr->isValueDependent() &&
3894 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3895 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00003896}
3897
3898static void CheckNonNullArgument(Sema &S,
3899 const Expr *ArgExpr,
3900 SourceLocation CallSiteLoc) {
3901 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00003902 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3903 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00003904}
3905
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003906bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3907 FormatStringInfo FSI;
3908 if ((GetFormatStringType(Format) == FST_NSString) &&
3909 getFormatStringInfo(Format, false, &FSI)) {
3910 Idx = FSI.FormatIdx;
3911 return true;
3912 }
3913 return false;
3914}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003915
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003916/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003917/// as formatting string to formatting method.
3918static void
3919DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3920 const NamedDecl *FDecl,
3921 Expr **Args,
3922 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003923 unsigned Idx = 0;
3924 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003925 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3926 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003927 Idx = 2;
3928 Format = true;
3929 }
3930 else
3931 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3932 if (S.GetFormatNSStringIdx(I, Idx)) {
3933 Format = true;
3934 break;
3935 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003936 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003937 if (!Format || NumArgs <= Idx)
3938 return;
3939 const Expr *FormatExpr = Args[Idx];
3940 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3941 FormatExpr = CSCE->getSubExpr();
3942 const StringLiteral *FormatString;
3943 if (const ObjCStringLiteral *OSL =
3944 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3945 FormatString = OSL->getString();
3946 else
3947 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3948 if (!FormatString)
3949 return;
3950 if (S.FormatStringHasSArg(FormatString)) {
3951 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3952 << "%s" << 1 << 1;
3953 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3954 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003955 }
3956}
3957
Douglas Gregorb4866e82015-06-19 18:13:19 +00003958/// Determine whether the given type has a non-null nullability annotation.
3959static bool isNonNullType(ASTContext &ctx, QualType type) {
3960 if (auto nullability = type->getNullability(ctx))
3961 return *nullability == NullabilityKind::NonNull;
Fangrui Song6907ce22018-07-30 19:24:48 +00003962
Douglas Gregorb4866e82015-06-19 18:13:19 +00003963 return false;
3964}
3965
Ted Kremenek2bc73332014-01-17 06:24:43 +00003966static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00003967 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003968 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00003969 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00003970 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003971 assert((FDecl || Proto) && "Need a function declaration or prototype");
3972
Ted Kremenek9aedc152014-01-17 06:24:56 +00003973 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00003974 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00003975 if (FDecl) {
3976 // Handle the nonnull attribute on the function/method declaration itself.
3977 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3978 if (!NonNull->args_size()) {
3979 // Easy case: all pointer arguments are nonnull.
3980 for (const auto *Arg : Args)
3981 if (S.isValidPointerAttrType(Arg->getType()))
3982 CheckNonNullArgument(S, Arg, CallSiteLoc);
3983 return;
3984 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003985
Joel E. Denny81508102018-03-13 14:51:22 +00003986 for (const ParamIdx &Idx : NonNull->args()) {
3987 unsigned IdxAST = Idx.getASTIndex();
3988 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00003989 continue;
3990 if (NonNullArgs.empty())
3991 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00003992 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003993 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003994 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003995 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003996
Douglas Gregorb4866e82015-06-19 18:13:19 +00003997 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3998 // Handle the nonnull attribute on the parameters of the
3999 // function/method.
4000 ArrayRef<ParmVarDecl*> parms;
4001 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4002 parms = FD->parameters();
4003 else
4004 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
Fangrui Song6907ce22018-07-30 19:24:48 +00004005
Douglas Gregorb4866e82015-06-19 18:13:19 +00004006 unsigned ParamIndex = 0;
4007 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4008 I != E; ++I, ++ParamIndex) {
4009 const ParmVarDecl *PVD = *I;
Fangrui Song6907ce22018-07-30 19:24:48 +00004010 if (PVD->hasAttr<NonNullAttr>() ||
Douglas Gregorb4866e82015-06-19 18:13:19 +00004011 isNonNullType(S.Context, PVD->getType())) {
4012 if (NonNullArgs.empty())
4013 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00004014
Douglas Gregorb4866e82015-06-19 18:13:19 +00004015 NonNullArgs.set(ParamIndex);
4016 }
4017 }
4018 } else {
4019 // If we have a non-function, non-method declaration but no
4020 // function prototype, try to dig out the function prototype.
4021 if (!Proto) {
4022 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4023 QualType type = VD->getType().getNonReferenceType();
4024 if (auto pointerType = type->getAs<PointerType>())
4025 type = pointerType->getPointeeType();
4026 else if (auto blockType = type->getAs<BlockPointerType>())
4027 type = blockType->getPointeeType();
4028 // FIXME: data member pointers?
4029
4030 // Dig out the function prototype, if there is one.
4031 Proto = type->getAs<FunctionProtoType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00004032 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00004033 }
4034
4035 // Fill in non-null argument information from the nullability
4036 // information on the parameter types (if we have them).
4037 if (Proto) {
4038 unsigned Index = 0;
4039 for (auto paramType : Proto->getParamTypes()) {
4040 if (isNonNullType(S.Context, paramType)) {
4041 if (NonNullArgs.empty())
4042 NonNullArgs.resize(Args.size());
Fangrui Song6907ce22018-07-30 19:24:48 +00004043
Douglas Gregorb4866e82015-06-19 18:13:19 +00004044 NonNullArgs.set(Index);
4045 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004046
Douglas Gregorb4866e82015-06-19 18:13:19 +00004047 ++Index;
4048 }
4049 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00004050 }
Richard Smith588bd9b2014-08-27 04:59:42 +00004051
Douglas Gregorb4866e82015-06-19 18:13:19 +00004052 // Check for non-null arguments.
Fangrui Song6907ce22018-07-30 19:24:48 +00004053 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
Douglas Gregorb4866e82015-06-19 18:13:19 +00004054 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00004055 if (NonNullArgs[ArgIndex])
4056 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004057 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00004058}
4059
Richard Smith55ce3522012-06-25 20:30:08 +00004060/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00004061/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4062/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004063void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00004064 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4065 bool IsMemberFunction, SourceLocation Loc,
4066 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00004067 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00004068 if (CurContext->isDependentContext())
4069 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00004070
Ted Kremenekb8176da2010-09-09 04:33:05 +00004071 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00004072 llvm::SmallBitVector CheckedVarArgs;
4073 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004074 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004075 // Only create vector if there are format attributes.
4076 CheckedVarArgs.resize(Args.size());
4077
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00004078 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00004079 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00004080 }
Richard Smithd7293d72013-08-05 18:49:43 +00004081 }
Richard Smith55ce3522012-06-25 20:30:08 +00004082
4083 // Refuse POD arguments that weren't caught by the format string
4084 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00004085 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4086 if (CallType != VariadicDoesNotApply &&
4087 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00004088 unsigned NumParams = Proto ? Proto->getNumParams()
4089 : FDecl && isa<FunctionDecl>(FDecl)
4090 ? cast<FunctionDecl>(FDecl)->getNumParams()
4091 : FDecl && isa<ObjCMethodDecl>(FDecl)
4092 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4093 : 0;
4094
Alp Toker9cacbab2014-01-20 20:26:09 +00004095 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004096 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00004097 if (const Expr *Arg = Args[ArgIdx]) {
4098 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4099 checkVariadicArgument(Arg, CallType);
4100 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00004101 }
Richard Smithd7293d72013-08-05 18:49:43 +00004102 }
Mike Stump11289f42009-09-09 15:08:12 +00004103
Douglas Gregorb4866e82015-06-19 18:13:19 +00004104 if (FDecl || Proto) {
4105 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004106
Richard Trieu41bc0992013-06-22 00:20:41 +00004107 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00004108 if (FDecl) {
4109 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00004110 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00004111 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004112 }
George Burgess IVce6284b2017-01-28 02:19:40 +00004113
4114 if (FD)
4115 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00004116}
4117
4118/// CheckConstructorCall - Check a constructor call for correctness and safety
4119/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004120void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4121 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004122 const FunctionProtoType *Proto,
4123 SourceLocation Loc) {
4124 VariadicCallType CallType =
4125 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00004126 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4127 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00004128}
4129
4130/// CheckFunctionCall - Check a direct function call for various correctness
4131/// and safety properties not strictly enforced by the C type system.
4132bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4133 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004134 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4135 isa<CXXMethodDecl>(FDecl);
4136 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4137 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00004138 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4139 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00004140 Expr** Args = TheCall->getArgs();
4141 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00004142
4143 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00004144 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00004145 // If this is a call to a member operator, hide the first argument
4146 // from checkCall.
4147 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00004148 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00004149 ++Args;
4150 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00004151 } else if (IsMemberFunction)
4152 ImplicitThis =
4153 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4154
4155 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00004156 IsMemberFunction, TheCall->getRParenLoc(),
4157 TheCall->getCallee()->getSourceRange(), CallType);
4158
4159 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4160 // None of the checks below are needed for functions that don't have
4161 // simple names (e.g., C++ conversion functions).
4162 if (!FnInfo)
4163 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004164
Richard Trieua7f30b12016-12-06 01:42:28 +00004165 CheckAbsoluteValueFunction(TheCall, FDecl);
4166 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00004167
Erik Pilkingtonfa983902018-10-30 20:31:30 +00004168 if (getLangOpts().ObjC)
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00004169 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004170
Anna Zaks22122702012-01-17 00:37:07 +00004171 unsigned CMId = FDecl->getMemoryFunctionKind();
4172 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00004173 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00004174
Anna Zaks201d4892012-01-13 21:52:01 +00004175 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00004176 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00004177 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00004178 else if (CMId == Builtin::BIstrncat)
4179 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00004180 else
Anna Zaks22122702012-01-17 00:37:07 +00004181 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004182
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004183 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00004184}
4185
Fangrui Song6907ce22018-07-30 19:24:48 +00004186bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00004187 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00004188 VariadicCallType CallType =
4189 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004190
George Burgess IVce6284b2017-01-28 02:19:40 +00004191 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4192 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004193 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004194
4195 return false;
4196}
4197
Richard Trieu664c4c62013-06-20 21:03:13 +00004198bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4199 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00004200 QualType Ty;
4201 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004202 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004203 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00004204 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00004205 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004206 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004207
Douglas Gregorb4866e82015-06-19 18:13:19 +00004208 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4209 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004210 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004211
Richard Trieu664c4c62013-06-20 21:03:13 +00004212 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00004213 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00004214 CallType = VariadicDoesNotApply;
4215 } else if (Ty->isBlockPointerType()) {
4216 CallType = VariadicBlock;
4217 } else { // Ty->isFunctionPointerType()
4218 CallType = VariadicFunction;
4219 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004220
George Burgess IVce6284b2017-01-28 02:19:40 +00004221 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00004222 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4223 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00004224 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00004225
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004226 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00004227}
4228
Richard Trieu41bc0992013-06-22 00:20:41 +00004229/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4230/// such as function pointers returned from functions.
4231bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004232 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00004233 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00004234 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00004235 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00004236 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00004237 TheCall->getCallee()->getSourceRange(), CallType);
4238
4239 return false;
4240}
4241
Tim Northovere94a34c2014-03-11 10:49:14 +00004242static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00004243 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00004244 return false;
4245
JF Bastiendda2cb12016-04-18 18:01:49 +00004246 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00004247 switch (Op) {
4248 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004249 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00004250 llvm_unreachable("There is no ordering argument for an init");
4251
4252 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004253 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00004254 case AtomicExpr::AO__atomic_load_n:
4255 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00004256 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4257 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004258
4259 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004260 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00004261 case AtomicExpr::AO__atomic_store:
4262 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00004263 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4264 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4265 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00004266
4267 default:
4268 return true;
4269 }
4270}
4271
Richard Smithfeea8832012-04-12 05:08:17 +00004272ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4273 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004274 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4275 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004276
Yaxun Liu39195062017-08-04 18:16:31 +00004277 // All the non-OpenCL operations take one of the following forms.
4278 // The OpenCL operations take the __c11 forms with one extra argument for
4279 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00004280 enum {
4281 // C __c11_atomic_init(A *, C)
4282 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004283
Richard Smithfeea8832012-04-12 05:08:17 +00004284 // C __c11_atomic_load(A *, int)
4285 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004286
Richard Smithfeea8832012-04-12 05:08:17 +00004287 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00004288 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004289
Eric Fiselier8d662442016-03-30 23:39:56 +00004290 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00004291 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004292
Richard Smithfeea8832012-04-12 05:08:17 +00004293 // C __c11_atomic_add(A *, M, int)
4294 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004295
Richard Smithfeea8832012-04-12 05:08:17 +00004296 // C __atomic_exchange_n(A *, CP, int)
4297 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004298
Richard Smithfeea8832012-04-12 05:08:17 +00004299 // void __atomic_exchange(A *, C *, CP, int)
4300 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004301
Richard Smithfeea8832012-04-12 05:08:17 +00004302 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4303 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004304
Richard Smithfeea8832012-04-12 05:08:17 +00004305 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4306 GNUCmpXchg
4307 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004308
Yaxun Liu39195062017-08-04 18:16:31 +00004309 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00004310 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4311 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00004312 // where:
4313 // C is an appropriate type,
4314 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4315 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4316 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4317 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004318
Yaxun Liu39195062017-08-04 18:16:31 +00004319 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4320 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4321 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00004322 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4323 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4324 AtomicExpr::AO__atomic_load,
4325 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00004326 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4327 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4328 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4329 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4330 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00004331 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4332 Op == AtomicExpr::AO__atomic_store_n ||
4333 Op == AtomicExpr::AO__atomic_exchange_n ||
4334 Op == AtomicExpr::AO__atomic_compare_exchange_n;
4335 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004336 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00004337
4338 switch (Op) {
4339 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00004340 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00004341 Form = Init;
4342 break;
4343
4344 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00004345 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00004346 case AtomicExpr::AO__atomic_load_n:
4347 Form = Load;
4348 break;
4349
Richard Smithfeea8832012-04-12 05:08:17 +00004350 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00004351 Form = LoadCopy;
4352 break;
4353
4354 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00004355 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00004356 case AtomicExpr::AO__atomic_store:
4357 case AtomicExpr::AO__atomic_store_n:
4358 Form = Copy;
4359 break;
4360
4361 case AtomicExpr::AO__c11_atomic_fetch_add:
4362 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00004363 case AtomicExpr::AO__opencl_atomic_fetch_add:
4364 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4365 case AtomicExpr::AO__opencl_atomic_fetch_min:
4366 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00004367 case AtomicExpr::AO__atomic_fetch_add:
4368 case AtomicExpr::AO__atomic_fetch_sub:
4369 case AtomicExpr::AO__atomic_add_fetch:
4370 case AtomicExpr::AO__atomic_sub_fetch:
4371 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00004372 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00004373 case AtomicExpr::AO__c11_atomic_fetch_and:
4374 case AtomicExpr::AO__c11_atomic_fetch_or:
4375 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00004376 case AtomicExpr::AO__opencl_atomic_fetch_and:
4377 case AtomicExpr::AO__opencl_atomic_fetch_or:
4378 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00004379 case AtomicExpr::AO__atomic_fetch_and:
4380 case AtomicExpr::AO__atomic_fetch_or:
4381 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00004382 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00004383 case AtomicExpr::AO__atomic_and_fetch:
4384 case AtomicExpr::AO__atomic_or_fetch:
4385 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00004386 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00004387 Form = Arithmetic;
4388 break;
4389
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004390 case AtomicExpr::AO__atomic_fetch_min:
4391 case AtomicExpr::AO__atomic_fetch_max:
4392 IsMinMax = true;
4393 Form = Arithmetic;
4394 break;
4395
Richard Smithfeea8832012-04-12 05:08:17 +00004396 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00004397 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00004398 case AtomicExpr::AO__atomic_exchange_n:
4399 Form = Xchg;
4400 break;
4401
4402 case AtomicExpr::AO__atomic_exchange:
4403 Form = GNUXchg;
4404 break;
4405
4406 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4407 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00004408 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4409 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00004410 Form = C11CmpXchg;
4411 break;
4412
4413 case AtomicExpr::AO__atomic_compare_exchange:
4414 case AtomicExpr::AO__atomic_compare_exchange_n:
4415 Form = GNUCmpXchg;
4416 break;
4417 }
4418
Yaxun Liu39195062017-08-04 18:16:31 +00004419 unsigned AdjustedNumArgs = NumArgs[Form];
4420 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4421 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00004422 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00004423 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004424 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4425 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4426 << TheCall->getCallee()->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004427 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00004428 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004429 Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004430 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004431 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4432 << TheCall->getCallee()->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004433 return ExprError();
4434 }
4435
Richard Smithfeea8832012-04-12 05:08:17 +00004436 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004437 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00004438 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4439 if (ConvertedPtr.isInvalid())
4440 return ExprError();
4441
4442 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004443 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4444 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004445 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4446 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004447 return ExprError();
4448 }
4449
Richard Smithfeea8832012-04-12 05:08:17 +00004450 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4451 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4452 QualType ValType = AtomTy; // 'C'
4453 if (IsC11) {
4454 if (!AtomTy->isAtomicType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004455 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4456 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004457 return ExprError();
4458 }
JF Bastienb4b1f592018-08-02 17:35:46 +00004459 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
Yaxun Liu39195062017-08-04 18:16:31 +00004460 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004461 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00004462 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4463 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00004464 return ExprError();
4465 }
Richard Smithfeea8832012-04-12 05:08:17 +00004466 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00004467 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004468 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004469 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4470 << Ptr->getType() << Ptr->getSourceRange();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00004471 return ExprError();
4472 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004473 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004474
Richard Smithfeea8832012-04-12 05:08:17 +00004475 // For an arithmetic operation, the implied arithmetic must be well-formed.
4476 if (Form == Arithmetic) {
4477 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004478 if (IsAddSub && !ValType->isIntegerType()
4479 && !ValType->isPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004480 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4481 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004482 return ExprError();
4483 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004484 if (IsMinMax) {
4485 const BuiltinType *BT = ValType->getAs<BuiltinType>();
4486 if (!BT || (BT->getKind() != BuiltinType::Int &&
4487 BT->getKind() != BuiltinType::UInt)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004488 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00004489 return ExprError();
4490 }
4491 }
4492 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004493 Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4494 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004495 return ExprError();
4496 }
David Majnemere85cff82015-01-28 05:48:06 +00004497 if (IsC11 && ValType->isPointerType() &&
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004498 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
David Majnemere85cff82015-01-28 05:48:06 +00004499 diag::err_incomplete_type)) {
4500 return ExprError();
4501 }
Richard Smithfeea8832012-04-12 05:08:17 +00004502 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4503 // For __atomic_*_n operations, the value type must be a scalar integral or
4504 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004505 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4506 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
Richard Smithfeea8832012-04-12 05:08:17 +00004507 return ExprError();
4508 }
4509
Eli Friedmanaa769812013-09-11 03:49:34 +00004510 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4511 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00004512 // For GNU atomics, require a trivially-copyable type. This is not part of
4513 // the GNU atomics specification, but we enforce it for sanity.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004514 Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4515 << Ptr->getType() << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004516 return ExprError();
4517 }
4518
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004519 switch (ValType.getObjCLifetime()) {
4520 case Qualifiers::OCL_None:
4521 case Qualifiers::OCL_ExplicitNone:
4522 // okay
4523 break;
4524
4525 case Qualifiers::OCL_Weak:
4526 case Qualifiers::OCL_Strong:
4527 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00004528 // FIXME: Can this happen? By this point, ValType should be known
4529 // to be trivially copyable.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004530 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4531 << ValType << Ptr->getSourceRange();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004532 return ExprError();
4533 }
4534
JF Bastien7f0a05a2018-05-25 00:07:09 +00004535 // All atomic operations have an overload which takes a pointer to a volatile
4536 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4537 // into the result or the other operands. Similarly atomic_load takes a
4538 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00004539 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00004540 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004541 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00004542 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4543 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004544 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00004545 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004546 ResultType = Context.BoolTy;
4547
Richard Smithfeea8832012-04-12 05:08:17 +00004548 // The type of a parameter passed 'by value'. In the GNU atomics, such
4549 // arguments are actually passed as pointers.
4550 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00004551 bool IsPassedByAddress = false;
4552 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00004553 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00004554 IsPassedByAddress = true;
4555 }
Richard Smithfeea8832012-04-12 05:08:17 +00004556
JF Bastien7f0a05a2018-05-25 00:07:09 +00004557 // The first argument's non-CV pointer type is used to deduce the type of
4558 // subsequent arguments, except for:
4559 // - weak flag (always converted to bool)
4560 // - memory order (always converted to int)
4561 // - scope (always converted to int)
4562 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004563 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00004564 if (i < NumVals[Form] + 1) {
4565 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00004566 case 0:
4567 // The first argument is always a pointer. It has a fixed type.
4568 // It is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004569 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
JF Bastien7f0a05a2018-05-25 00:07:09 +00004570 // Nothing else to do: we already know all we want about this pointer.
4571 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00004572 case 1:
4573 // The second argument is the non-atomic operand. For arithmetic, this
4574 // is always passed by value, and for a compare_exchange it is always
4575 // passed by address. For the rest, GNU uses by-address and C11 uses
4576 // by-value.
4577 assert(Form != Load);
4578 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4579 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004580 else if (Form == Copy || Form == Xchg) {
4581 if (IsPassedByAddress)
4582 // The value pointer is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004583 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
Richard Smithfeea8832012-04-12 05:08:17 +00004584 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00004585 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00004586 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004587 else {
4588 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00004589 // The value pointer is always dereferenced, a nullptr is undefined.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004590 CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
Alexander Richardson6d989432017-10-15 18:48:14 +00004591 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00004592 // Keep address space of non-atomic pointer type.
4593 if (const PointerType *PtrTy =
4594 ValArg->getType()->getAs<PointerType>()) {
4595 AS = PtrTy->getPointeeType().getAddressSpace();
4596 }
4597 Ty = Context.getPointerType(
4598 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4599 }
Richard Smithfeea8832012-04-12 05:08:17 +00004600 break;
4601 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00004602 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00004603 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4604 if (IsPassedByAddress)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004605 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
Richard Smithfeea8832012-04-12 05:08:17 +00004606 Ty = ByValType;
4607 break;
4608 case 3:
4609 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4610 Ty = Context.BoolTy;
4611 break;
4612 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004613 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00004614 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004615 Ty = Context.IntTy;
4616 }
Richard Smithfeea8832012-04-12 05:08:17 +00004617
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004618 InitializedEntity Entity =
4619 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00004620 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004621 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4622 if (Arg.isInvalid())
4623 return true;
4624 TheCall->setArg(i, Arg.get());
4625 }
4626
Richard Smithfeea8832012-04-12 05:08:17 +00004627 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004628 SmallVector<Expr*, 5> SubExprs;
4629 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00004630 switch (Form) {
4631 case Init:
4632 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00004633 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004634 break;
4635 case Load:
4636 SubExprs.push_back(TheCall->getArg(1)); // Order
4637 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00004638 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00004639 case Copy:
4640 case Arithmetic:
4641 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004642 SubExprs.push_back(TheCall->getArg(2)); // Order
4643 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00004644 break;
4645 case GNUXchg:
4646 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4647 SubExprs.push_back(TheCall->getArg(3)); // Order
4648 SubExprs.push_back(TheCall->getArg(1)); // Val1
4649 SubExprs.push_back(TheCall->getArg(2)); // Val2
4650 break;
4651 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004652 SubExprs.push_back(TheCall->getArg(3)); // Order
4653 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004654 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00004655 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00004656 break;
4657 case GNUCmpXchg:
4658 SubExprs.push_back(TheCall->getArg(4)); // Order
4659 SubExprs.push_back(TheCall->getArg(1)); // Val1
4660 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4661 SubExprs.push_back(TheCall->getArg(2)); // Val2
4662 SubExprs.push_back(TheCall->getArg(3)); // Weak
4663 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004664 }
Tim Northovere94a34c2014-03-11 10:49:14 +00004665
4666 if (SubExprs.size() >= 2 && Form != Init) {
4667 llvm::APSInt Result(32);
4668 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4669 !isValidOrderingForOp(Result.getSExtValue(), Op))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004670 Diag(SubExprs[1]->getBeginLoc(),
Tim Northoverc83472e2014-03-11 11:35:10 +00004671 diag::warn_atomic_op_has_invalid_memory_order)
4672 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00004673 }
4674
Yaxun Liu30d652a2017-08-15 16:02:49 +00004675 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4676 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4677 llvm::APSInt Result(32);
4678 if (Scope->isIntegerConstantExpr(Result, Context) &&
4679 !ScopeModel->isValid(Result.getZExtValue())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004680 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
Yaxun Liu30d652a2017-08-15 16:02:49 +00004681 << Scope->getSourceRange();
4682 }
4683 SubExprs.push_back(Scope);
4684 }
4685
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004686 AtomicExpr *AE =
4687 new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4688 ResultType, Op, TheCall->getRParenLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00004689
Fariborz Jahanian615de762013-05-28 17:37:39 +00004690 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00004691 Op == AtomicExpr::AO__c11_atomic_store ||
4692 Op == AtomicExpr::AO__opencl_atomic_load ||
4693 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00004694 Context.AtomicUsesUnsupportedLibcall(AE))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004695 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
Yaxun Liu39195062017-08-04 18:16:31 +00004696 << ((Op == AtomicExpr::AO__c11_atomic_load ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004697 Op == AtomicExpr::AO__opencl_atomic_load)
4698 ? 0
4699 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00004700
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004701 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004702}
4703
John McCall29ad95b2011-08-27 01:09:30 +00004704/// checkBuiltinArgument - Given a call to a builtin function, perform
4705/// normal type-checking on the given argument, updating the call in
4706/// place. This is useful when a builtin function requires custom
4707/// type-checking for some of its arguments but not necessarily all of
4708/// them.
4709///
4710/// Returns true on error.
4711static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4712 FunctionDecl *Fn = E->getDirectCallee();
4713 assert(Fn && "builtin call without direct callee!");
4714
4715 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4716 InitializedEntity Entity =
4717 InitializedEntity::InitializeParameter(S.Context, Param);
4718
4719 ExprResult Arg = E->getArg(0);
4720 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4721 if (Arg.isInvalid())
4722 return true;
4723
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004724 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00004725 return false;
4726}
4727
JF Bastiene77b48b2018-09-10 20:42:56 +00004728/// We have a call to a function like __sync_fetch_and_add, which is an
4729/// overloaded function based on the pointer type of its first argument.
4730/// The main ActOnCallExpr routines have already promoted the types of
4731/// arguments because all of these calls are prototyped as void(...).
Chris Lattnerdc046542009-05-08 06:58:22 +00004732///
4733/// This function goes through and does final semantic checking for these
JF Bastiene77b48b2018-09-10 20:42:56 +00004734/// builtins, as well as generating any warnings.
John McCalldadc5752010-08-24 06:29:42 +00004735ExprResult
4736Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
JF Bastiene77b48b2018-09-10 20:42:56 +00004737 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4738 Expr *Callee = TheCall->getCallee();
4739 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
Chris Lattnerdc046542009-05-08 06:58:22 +00004740 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4741
4742 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004743 if (TheCall->getNumArgs() < 1) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004744 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
JF Bastiene77b48b2018-09-10 20:42:56 +00004745 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004746 return ExprError();
4747 }
Mike Stump11289f42009-09-09 15:08:12 +00004748
Chris Lattnerdc046542009-05-08 06:58:22 +00004749 // Inspect the first argument of the atomic builtin. This should always be
4750 // a pointer type, whose element is an integral scalar or pointer type.
4751 // Because it is a pointer type, we don't have to worry about any implicit
4752 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004753 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00004754 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00004755 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4756 if (FirstArgResult.isInvalid())
4757 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004758 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00004759 TheCall->setArg(0, FirstArg);
4760
John McCall31168b02011-06-15 23:02:42 +00004761 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4762 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004763 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4764 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004765 return ExprError();
4766 }
Mike Stump11289f42009-09-09 15:08:12 +00004767
John McCall31168b02011-06-15 23:02:42 +00004768 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00004769 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004770 !ValType->isBlockPointerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004771 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4772 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004773 return ExprError();
4774 }
Chris Lattnerdc046542009-05-08 06:58:22 +00004775
Aaron Ballmana383c942018-05-05 17:38:42 +00004776 if (ValType.isConstQualified()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004777 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
Aaron Ballmana383c942018-05-05 17:38:42 +00004778 << FirstArg->getType() << FirstArg->getSourceRange();
4779 return ExprError();
4780 }
4781
John McCall31168b02011-06-15 23:02:42 +00004782 switch (ValType.getObjCLifetime()) {
4783 case Qualifiers::OCL_None:
4784 case Qualifiers::OCL_ExplicitNone:
4785 // okay
4786 break;
4787
4788 case Qualifiers::OCL_Weak:
4789 case Qualifiers::OCL_Strong:
4790 case Qualifiers::OCL_Autoreleasing:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004791 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4792 << ValType << FirstArg->getSourceRange();
John McCall31168b02011-06-15 23:02:42 +00004793 return ExprError();
4794 }
4795
John McCallb50451a2011-10-05 07:41:44 +00004796 // Strip any qualifiers off ValType.
4797 ValType = ValType.getUnqualifiedType();
4798
Chandler Carruth3973af72010-07-18 20:54:12 +00004799 // The majority of builtins return a value, but a few have special return
4800 // types, so allow them to override appropriately below.
4801 QualType ResultType = ValType;
4802
Chris Lattnerdc046542009-05-08 06:58:22 +00004803 // We need to figure out which concrete builtin this maps onto. For example,
4804 // __sync_fetch_and_add with a 2 byte object turns into
4805 // __sync_fetch_and_add_2.
4806#define BUILTIN_ROW(x) \
4807 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4808 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00004809
Chris Lattnerdc046542009-05-08 06:58:22 +00004810 static const unsigned BuiltinIndices[][5] = {
4811 BUILTIN_ROW(__sync_fetch_and_add),
4812 BUILTIN_ROW(__sync_fetch_and_sub),
4813 BUILTIN_ROW(__sync_fetch_and_or),
4814 BUILTIN_ROW(__sync_fetch_and_and),
4815 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00004816 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00004817
Chris Lattnerdc046542009-05-08 06:58:22 +00004818 BUILTIN_ROW(__sync_add_and_fetch),
4819 BUILTIN_ROW(__sync_sub_and_fetch),
4820 BUILTIN_ROW(__sync_and_and_fetch),
4821 BUILTIN_ROW(__sync_or_and_fetch),
4822 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00004823 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00004824
Chris Lattnerdc046542009-05-08 06:58:22 +00004825 BUILTIN_ROW(__sync_val_compare_and_swap),
4826 BUILTIN_ROW(__sync_bool_compare_and_swap),
4827 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00004828 BUILTIN_ROW(__sync_lock_release),
4829 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00004830 };
Mike Stump11289f42009-09-09 15:08:12 +00004831#undef BUILTIN_ROW
4832
Chris Lattnerdc046542009-05-08 06:58:22 +00004833 // Determine the index of the size.
4834 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00004835 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00004836 case 1: SizeIndex = 0; break;
4837 case 2: SizeIndex = 1; break;
4838 case 4: SizeIndex = 2; break;
4839 case 8: SizeIndex = 3; break;
4840 case 16: SizeIndex = 4; break;
4841 default:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004842 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4843 << FirstArg->getType() << FirstArg->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004844 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00004845 }
Mike Stump11289f42009-09-09 15:08:12 +00004846
Chris Lattnerdc046542009-05-08 06:58:22 +00004847 // Each of these builtins has one pointer argument, followed by some number of
4848 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4849 // that we ignore. Find out which row of BuiltinIndices to read from as well
4850 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00004851 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00004852 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00004853 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00004854 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00004855 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Fangrui Song6907ce22018-07-30 19:24:48 +00004856 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +00004857 case Builtin::BI__sync_fetch_and_add_1:
4858 case Builtin::BI__sync_fetch_and_add_2:
4859 case Builtin::BI__sync_fetch_and_add_4:
4860 case Builtin::BI__sync_fetch_and_add_8:
4861 case Builtin::BI__sync_fetch_and_add_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004862 BuiltinIndex = 0;
Douglas Gregor73722482011-11-28 16:30:08 +00004863 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004864
4865 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +00004866 case Builtin::BI__sync_fetch_and_sub_1:
4867 case Builtin::BI__sync_fetch_and_sub_2:
4868 case Builtin::BI__sync_fetch_and_sub_4:
4869 case Builtin::BI__sync_fetch_and_sub_8:
4870 case Builtin::BI__sync_fetch_and_sub_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004871 BuiltinIndex = 1;
Douglas Gregor73722482011-11-28 16:30:08 +00004872 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004873
4874 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +00004875 case Builtin::BI__sync_fetch_and_or_1:
4876 case Builtin::BI__sync_fetch_and_or_2:
4877 case Builtin::BI__sync_fetch_and_or_4:
4878 case Builtin::BI__sync_fetch_and_or_8:
4879 case Builtin::BI__sync_fetch_and_or_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004880 BuiltinIndex = 2;
Douglas Gregor73722482011-11-28 16:30:08 +00004881 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004882
4883 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +00004884 case Builtin::BI__sync_fetch_and_and_1:
4885 case Builtin::BI__sync_fetch_and_and_2:
4886 case Builtin::BI__sync_fetch_and_and_4:
4887 case Builtin::BI__sync_fetch_and_and_8:
4888 case Builtin::BI__sync_fetch_and_and_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004889 BuiltinIndex = 3;
Douglas Gregor73722482011-11-28 16:30:08 +00004890 break;
Mike Stump11289f42009-09-09 15:08:12 +00004891
Fangrui Song6907ce22018-07-30 19:24:48 +00004892 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +00004893 case Builtin::BI__sync_fetch_and_xor_1:
4894 case Builtin::BI__sync_fetch_and_xor_2:
4895 case Builtin::BI__sync_fetch_and_xor_4:
4896 case Builtin::BI__sync_fetch_and_xor_8:
4897 case Builtin::BI__sync_fetch_and_xor_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004898 BuiltinIndex = 4;
Douglas Gregor73722482011-11-28 16:30:08 +00004899 break;
4900
Fangrui Song6907ce22018-07-30 19:24:48 +00004901 case Builtin::BI__sync_fetch_and_nand:
Hal Finkeld2208b52014-10-02 20:53:50 +00004902 case Builtin::BI__sync_fetch_and_nand_1:
4903 case Builtin::BI__sync_fetch_and_nand_2:
4904 case Builtin::BI__sync_fetch_and_nand_4:
4905 case Builtin::BI__sync_fetch_and_nand_8:
4906 case Builtin::BI__sync_fetch_and_nand_16:
4907 BuiltinIndex = 5;
4908 WarnAboutSemanticsChange = true;
4909 break;
4910
Fangrui Song6907ce22018-07-30 19:24:48 +00004911 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004912 case Builtin::BI__sync_add_and_fetch_1:
4913 case Builtin::BI__sync_add_and_fetch_2:
4914 case Builtin::BI__sync_add_and_fetch_4:
4915 case Builtin::BI__sync_add_and_fetch_8:
4916 case Builtin::BI__sync_add_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004917 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00004918 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004919
4920 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004921 case Builtin::BI__sync_sub_and_fetch_1:
4922 case Builtin::BI__sync_sub_and_fetch_2:
4923 case Builtin::BI__sync_sub_and_fetch_4:
4924 case Builtin::BI__sync_sub_and_fetch_8:
4925 case Builtin::BI__sync_sub_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004926 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00004927 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004928
4929 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004930 case Builtin::BI__sync_and_and_fetch_1:
4931 case Builtin::BI__sync_and_and_fetch_2:
4932 case Builtin::BI__sync_and_and_fetch_4:
4933 case Builtin::BI__sync_and_and_fetch_8:
4934 case Builtin::BI__sync_and_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004935 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00004936 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004937
4938 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004939 case Builtin::BI__sync_or_and_fetch_1:
4940 case Builtin::BI__sync_or_and_fetch_2:
4941 case Builtin::BI__sync_or_and_fetch_4:
4942 case Builtin::BI__sync_or_and_fetch_8:
4943 case Builtin::BI__sync_or_and_fetch_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004944 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00004945 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004946
4947 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00004948 case Builtin::BI__sync_xor_and_fetch_1:
4949 case Builtin::BI__sync_xor_and_fetch_2:
4950 case Builtin::BI__sync_xor_and_fetch_4:
4951 case Builtin::BI__sync_xor_and_fetch_8:
4952 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004953 BuiltinIndex = 10;
4954 break;
4955
Fangrui Song6907ce22018-07-30 19:24:48 +00004956 case Builtin::BI__sync_nand_and_fetch:
Hal Finkeld2208b52014-10-02 20:53:50 +00004957 case Builtin::BI__sync_nand_and_fetch_1:
4958 case Builtin::BI__sync_nand_and_fetch_2:
4959 case Builtin::BI__sync_nand_and_fetch_4:
4960 case Builtin::BI__sync_nand_and_fetch_8:
4961 case Builtin::BI__sync_nand_and_fetch_16:
4962 BuiltinIndex = 11;
4963 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00004964 break;
Mike Stump11289f42009-09-09 15:08:12 +00004965
Chris Lattnerdc046542009-05-08 06:58:22 +00004966 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004967 case Builtin::BI__sync_val_compare_and_swap_1:
4968 case Builtin::BI__sync_val_compare_and_swap_2:
4969 case Builtin::BI__sync_val_compare_and_swap_4:
4970 case Builtin::BI__sync_val_compare_and_swap_8:
4971 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004972 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00004973 NumFixed = 2;
4974 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004975
Chris Lattnerdc046542009-05-08 06:58:22 +00004976 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004977 case Builtin::BI__sync_bool_compare_and_swap_1:
4978 case Builtin::BI__sync_bool_compare_and_swap_2:
4979 case Builtin::BI__sync_bool_compare_and_swap_4:
4980 case Builtin::BI__sync_bool_compare_and_swap_8:
4981 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004982 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00004983 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00004984 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004985 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004986
JF Bastien7f0a05a2018-05-25 00:07:09 +00004987 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00004988 case Builtin::BI__sync_lock_test_and_set_1:
4989 case Builtin::BI__sync_lock_test_and_set_2:
4990 case Builtin::BI__sync_lock_test_and_set_4:
4991 case Builtin::BI__sync_lock_test_and_set_8:
4992 case Builtin::BI__sync_lock_test_and_set_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00004993 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00004994 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004995
Chris Lattnerdc046542009-05-08 06:58:22 +00004996 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00004997 case Builtin::BI__sync_lock_release_1:
4998 case Builtin::BI__sync_lock_release_2:
4999 case Builtin::BI__sync_lock_release_4:
5000 case Builtin::BI__sync_lock_release_8:
5001 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00005002 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00005003 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00005004 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00005005 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00005006
5007 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00005008 case Builtin::BI__sync_swap_1:
5009 case Builtin::BI__sync_swap_2:
5010 case Builtin::BI__sync_swap_4:
5011 case Builtin::BI__sync_swap_8:
5012 case Builtin::BI__sync_swap_16:
Fangrui Song6907ce22018-07-30 19:24:48 +00005013 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00005014 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00005015 }
Mike Stump11289f42009-09-09 15:08:12 +00005016
Chris Lattnerdc046542009-05-08 06:58:22 +00005017 // Now that we know how many fixed arguments we expect, first check that we
5018 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005019 if (TheCall->getNumArgs() < 1+NumFixed) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005020 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5021 << 0 << 1 + NumFixed << TheCall->getNumArgs()
JF Bastiene77b48b2018-09-10 20:42:56 +00005022 << Callee->getSourceRange();
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005023 return ExprError();
5024 }
Mike Stump11289f42009-09-09 15:08:12 +00005025
JF Bastiene77b48b2018-09-10 20:42:56 +00005026 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5027 << Callee->getSourceRange();
5028
Hal Finkeld2208b52014-10-02 20:53:50 +00005029 if (WarnAboutSemanticsChange) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005030 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
JF Bastiene77b48b2018-09-10 20:42:56 +00005031 << Callee->getSourceRange();
Hal Finkeld2208b52014-10-02 20:53:50 +00005032 }
5033
Chris Lattner5b9241b2009-05-08 15:36:58 +00005034 // Get the decl for the concrete builtin from this, we can tell what the
5035 // concrete integer type we should convert to is.
5036 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00005037 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005038 FunctionDecl *NewBuiltinDecl;
5039 if (NewBuiltinID == BuiltinID)
5040 NewBuiltinDecl = FDecl;
5041 else {
5042 // Perform builtin lookup to avoid redeclaring it.
5043 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005044 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005045 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5046 assert(Res.getFoundDecl());
5047 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005048 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00005049 return ExprError();
5050 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005051
John McCallcf142162010-08-07 06:22:56 +00005052 // The first argument --- the pointer --- has a fixed type; we
5053 // deduce the types of the rest of the arguments accordingly. Walk
5054 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00005055 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00005056 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00005057
Chris Lattnerdc046542009-05-08 06:58:22 +00005058 // GCC does an implicit conversion to the pointer or integer ValType. This
5059 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00005060 // Initialize the argument.
5061 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5062 ValType, /*consume*/ false);
5063 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00005064 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005065 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00005066
Chris Lattnerdc046542009-05-08 06:58:22 +00005067 // Okay, we have something that *can* be converted to the right type. Check
5068 // to see if there is a potentially weird extension going on here. This can
5069 // happen when you do an atomic operation on something like an char* and
5070 // pass in 42. The 42 gets converted to char. This is even more strange
5071 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00005072 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005073 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00005074 }
Mike Stump11289f42009-09-09 15:08:12 +00005075
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005076 ASTContext& Context = this->getASTContext();
5077
5078 // Create a new DeclRefExpr to refer to the new decl.
5079 DeclRefExpr* NewDRE = DeclRefExpr::Create(
5080 Context,
5081 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00005082 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005083 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00005084 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005085 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00005086 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00005087 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00005088
Chris Lattnerdc046542009-05-08 06:58:22 +00005089 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00005090 // FIXME: This loses syntactic information.
5091 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5092 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5093 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005094 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00005095
Chandler Carruthbc8cab12010-07-18 07:23:17 +00005096 // Change the result type of the call to match the original value type. This
5097 // is arbitrary, but the codegen for these builtins ins design to handle it
5098 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00005099 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00005100
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005101 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00005102}
5103
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005104/// SemaBuiltinNontemporalOverloaded - We have a call to
5105/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5106/// overloaded function based on the pointer type of its last argument.
5107///
5108/// This function goes through and does final semantic checking for these
5109/// builtins.
5110ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5111 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5112 DeclRefExpr *DRE =
5113 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5114 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5115 unsigned BuiltinID = FDecl->getBuiltinID();
5116 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5117 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5118 "Unexpected nontemporal load/store builtin!");
5119 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5120 unsigned numArgs = isStore ? 2 : 1;
5121
5122 // Ensure that we have the proper number of arguments.
5123 if (checkArgCount(*this, TheCall, numArgs))
5124 return ExprError();
5125
5126 // Inspect the last argument of the nontemporal builtin. This should always
5127 // be a pointer type, from which we imply the type of the memory access.
5128 // Because it is a pointer type, we don't have to worry about any implicit
5129 // casts here.
5130 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5131 ExprResult PointerArgResult =
5132 DefaultFunctionArrayLvalueConversion(PointerArg);
5133
5134 if (PointerArgResult.isInvalid())
5135 return ExprError();
5136 PointerArg = PointerArgResult.get();
5137 TheCall->setArg(numArgs - 1, PointerArg);
5138
5139 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5140 if (!pointerType) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005141 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005142 << PointerArg->getType() << PointerArg->getSourceRange();
5143 return ExprError();
5144 }
5145
5146 QualType ValType = pointerType->getPointeeType();
5147
5148 // Strip any qualifiers off ValType.
5149 ValType = ValType.getUnqualifiedType();
5150 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5151 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5152 !ValType->isVectorType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005153 Diag(DRE->getBeginLoc(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00005154 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5155 << PointerArg->getType() << PointerArg->getSourceRange();
5156 return ExprError();
5157 }
5158
5159 if (!isStore) {
5160 TheCall->setType(ValType);
5161 return TheCallResult;
5162 }
5163
5164 ExprResult ValArg = TheCall->getArg(0);
5165 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5166 Context, ValType, /*consume*/ false);
5167 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5168 if (ValArg.isInvalid())
5169 return ExprError();
5170
5171 TheCall->setArg(0, ValArg.get());
5172 TheCall->setType(Context.VoidTy);
5173 return TheCallResult;
5174}
5175
Chris Lattner6436fb62009-02-18 06:01:06 +00005176/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00005177/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00005178/// Note: It might also make sense to do the UTF-16 conversion here (would
5179/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00005180bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00005181 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00005182 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5183
Douglas Gregorfb65e592011-07-27 05:40:30 +00005184 if (!Literal || !Literal->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005185 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5186 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00005187 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00005188 }
Mike Stump11289f42009-09-09 15:08:12 +00005189
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005190 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005191 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005192 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00005193 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5194 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5195 llvm::UTF16 *ToPtr = &ToBuf[0];
5196
5197 llvm::ConversionResult Result =
5198 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5199 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005200 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00005201 if (Result != llvm::conversionOK)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005202 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5203 << Arg->getSourceRange();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00005204 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00005205 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005206}
5207
Mehdi Amini06d367c2016-10-24 20:39:34 +00005208/// CheckObjCString - Checks that the format string argument to the os_log()
5209/// and os_trace() functions is correct, and converts it to const char *.
5210ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5211 Arg = Arg->IgnoreParenCasts();
5212 auto *Literal = dyn_cast<StringLiteral>(Arg);
5213 if (!Literal) {
5214 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5215 Literal = ObjcLiteral->getString();
5216 }
5217 }
5218
5219 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5220 return ExprError(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005221 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005222 << Arg->getSourceRange());
5223 }
5224
5225 ExprResult Result(Literal);
5226 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5227 InitializedEntity Entity =
5228 InitializedEntity::InitializeParameter(Context, ResultTy, false);
5229 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5230 return Result;
5231}
5232
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005233/// Check that the user is calling the appropriate va_start builtin for the
5234/// target and calling convention.
5235static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5236 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5237 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00005238 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005239 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00005240 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5241 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005242 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005243 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5244 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5245 if (IsMSVAStart) {
5246 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00005247 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005248 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005249 diag::err_ms_va_start_used_in_sysv_function);
5250 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00005251 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005252 // On x64 Windows, don't allow this in System V ABI functions.
5253 // (Yes, that means there's no corresponding way to support variadic
5254 // System V ABI functions on Windows.)
5255 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00005256 (!IsWindows && CC == CC_Win64))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005257 return S.Diag(Fn->getBeginLoc(),
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005258 diag::err_va_start_used_in_wrong_abi_function)
5259 << !IsWindows;
5260 }
5261 return false;
5262 }
5263
5264 if (IsMSVAStart)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005265 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005266 return false;
5267}
5268
5269static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5270 ParmVarDecl **LastParam = nullptr) {
5271 // Determine whether the current function, block, or obj-c method is variadic
5272 // and get its parameter list.
5273 bool IsVariadic = false;
5274 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00005275 DeclContext *Caller = S.CurContext;
5276 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5277 IsVariadic = Block->isVariadic();
5278 Params = Block->parameters();
5279 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005280 IsVariadic = FD->isVariadic();
5281 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005282 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005283 IsVariadic = MD->isVariadic();
5284 // FIXME: This isn't correct for methods (results in bogus warning).
5285 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00005286 } else if (isa<CapturedDecl>(Caller)) {
5287 // We don't support va_start in a CapturedDecl.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005288 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005289 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005290 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00005291 // This must be some other declcontext that parses exprs.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005292 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
Reid Klecknerf1deb832017-05-04 19:51:05 +00005293 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005294 }
5295
5296 if (!IsVariadic) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005297 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00005298 return true;
5299 }
5300
5301 if (LastParam)
5302 *LastParam = Params.empty() ? nullptr : Params.back();
5303
5304 return false;
5305}
5306
Aaron Ballman68d50642018-06-19 14:53:20 +00005307/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5308/// for validity. Emit an error and return true on failure; return false
5309/// on success.
5310bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5311 Expr *Fn = TheCall->getCallee();
5312
5313 if (checkVAStartABI(*this, BuiltinID, Fn))
5314 return true;
5315
5316 if (TheCall->getNumArgs() > 2) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005317 Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005318 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005319 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5320 << Fn->getSourceRange()
5321 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005322 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005323 return true;
5324 }
5325
5326 if (TheCall->getNumArgs() < 2) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005327 return Diag(TheCall->getEndLoc(),
5328 diag::err_typecheck_call_too_few_args_at_least)
5329 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Aaron Ballman68d50642018-06-19 14:53:20 +00005330 }
5331
5332 // Type-check the first argument normally.
5333 if (checkBuiltinArgument(*this, TheCall, 0))
5334 return true;
5335
5336 // Check that the current function is variadic, and get its last parameter.
5337 ParmVarDecl *LastParam;
5338 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5339 return true;
5340
5341 // Verify that the second argument to the builtin is the last argument of the
5342 // current function or method.
5343 bool SecondArgIsLastNamedArgument = false;
5344 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5345
5346 // These are valid if SecondArgIsLastNamedArgument is false after the next
5347 // block.
5348 QualType Type;
5349 SourceLocation ParamLoc;
5350 bool IsCRegister = false;
5351
5352 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5353 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5354 SecondArgIsLastNamedArgument = PV == LastParam;
5355
5356 Type = PV->getType();
5357 ParamLoc = PV->getLocation();
5358 IsCRegister =
5359 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5360 }
5361 }
5362
5363 if (!SecondArgIsLastNamedArgument)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005364 Diag(TheCall->getArg(1)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005365 diag::warn_second_arg_of_va_start_not_last_named_param);
5366 else if (IsCRegister || Type->isReferenceType() ||
5367 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5368 // Promotable integers are UB, but enumerations need a bit of
5369 // extra checking to see what their promotable type actually is.
5370 if (!Type->isPromotableIntegerType())
5371 return false;
5372 if (!Type->isEnumeralType())
5373 return true;
5374 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5375 return !(ED &&
5376 Context.typesAreCompatible(ED->getPromotionType(), Type));
5377 }()) {
5378 unsigned Reason = 0;
5379 if (Type->isReferenceType()) Reason = 1;
5380 else if (IsCRegister) Reason = 2;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005381 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
Aaron Ballman68d50642018-06-19 14:53:20 +00005382 Diag(ParamLoc, diag::note_parameter_type) << Type;
5383 }
5384
5385 TheCall->setType(Context.VoidTy);
5386 return false;
5387}
5388
5389bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5390 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5391 // const char *named_addr);
5392
5393 Expr *Func = Call->getCallee();
5394
5395 if (Call->getNumArgs() < 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005396 return Diag(Call->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005397 diag::err_typecheck_call_too_few_args_at_least)
5398 << 0 /*function call*/ << 3 << Call->getNumArgs();
5399
5400 // Type-check the first argument normally.
5401 if (checkBuiltinArgument(*this, Call, 0))
5402 return true;
5403
5404 // Check that the current function is variadic.
5405 if (checkVAStartIsInVariadicFunction(*this, Func))
5406 return true;
5407
5408 // __va_start on Windows does not validate the parameter qualifiers
5409
5410 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5411 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5412
5413 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5414 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5415
5416 const QualType &ConstCharPtrTy =
5417 Context.getPointerType(Context.CharTy.withConst());
5418 if (!Arg1Ty->isPointerType() ||
5419 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005420 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5421 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5422 << 0 /* qualifier difference */
5423 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005424 << 2 << Arg1->getType() << ConstCharPtrTy;
5425
5426 const QualType SizeTy = Context.getSizeType();
5427 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005428 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5429 << Arg2->getType() << SizeTy << 1 /* different class */
5430 << 0 /* qualifier difference */
5431 << 3 /* parameter mismatch */
Aaron Ballman68d50642018-06-19 14:53:20 +00005432 << 3 << Arg2->getType() << SizeTy;
5433
5434 return false;
5435}
5436
5437/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5438/// friends. This is declared to take (...), so we have to check everything.
5439bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5440 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005441 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5442 << 0 << 2 << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005443 if (TheCall->getNumArgs() > 2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005444 return Diag(TheCall->getArg(2)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005445 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005446 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5447 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005448 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005449
5450 ExprResult OrigArg0 = TheCall->getArg(0);
5451 ExprResult OrigArg1 = TheCall->getArg(1);
5452
5453 // Do standard promotions between the two arguments, returning their common
5454 // type.
5455 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5456 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5457 return true;
5458
5459 // Make sure any conversions are pushed back into the call; this is
5460 // type safe since unordered compare builtins are declared as "_Bool
5461 // foo(...)".
5462 TheCall->setArg(0, OrigArg0.get());
5463 TheCall->setArg(1, OrigArg1.get());
5464
5465 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5466 return false;
5467
5468 // If the common type isn't a real floating type, then the arguments were
5469 // invalid for this operation.
5470 if (Res.isNull() || !Res->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005471 return Diag(OrigArg0.get()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005472 diag::err_typecheck_call_invalid_ordered_compare)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005473 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5474 << SourceRange(OrigArg0.get()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005475 OrigArg1.get()->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005476
5477 return false;
5478}
5479
5480/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5481/// __builtin_isnan and friends. This is declared to take (...), so we have
5482/// to check everything. We expect the last argument to be a floating point
5483/// value.
5484bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5485 if (TheCall->getNumArgs() < NumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005486 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5487 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
Aaron Ballman68d50642018-06-19 14:53:20 +00005488 if (TheCall->getNumArgs() > NumArgs)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005489 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005490 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005491 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5492 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005493 (*(TheCall->arg_end() - 1))->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005494
5495 Expr *OrigArg = TheCall->getArg(NumArgs-1);
5496
5497 if (OrigArg->isTypeDependent())
5498 return false;
5499
5500 // This operation requires a non-_Complex floating-point number.
5501 if (!OrigArg->getType()->isRealFloatingType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005502 return Diag(OrigArg->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005503 diag::err_typecheck_call_invalid_unary_fp)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005504 << OrigArg->getType() << OrigArg->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005505
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005506 // If this is an implicit conversion from float -> float, double, or
5507 // long double, remove it.
Aaron Ballman68d50642018-06-19 14:53:20 +00005508 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5509 // Only remove standard FloatCasts, leaving other casts inplace
5510 if (Cast->getCastKind() == CK_FloatingCast) {
5511 Expr *CastArg = Cast->getSubExpr();
5512 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00005513 assert(
5514 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5515 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5516 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5517 "promotion from float to either float, double, or long double is "
5518 "the only expected cast here");
Aaron Ballman68d50642018-06-19 14:53:20 +00005519 Cast->setSubExpr(nullptr);
5520 TheCall->setArg(NumArgs-1, CastArg);
5521 }
5522 }
5523 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005524
Aaron Ballman68d50642018-06-19 14:53:20 +00005525 return false;
5526}
5527
5528// Customized Sema Checking for VSX builtins that have the following signature:
5529// vector [...] builtinName(vector [...], vector [...], const int);
5530// Which takes the same type of vectors (any legal vector type) for the first
5531// two arguments and takes compile time constant for the third argument.
5532// Example builtins are :
5533// vector double vec_xxpermdi(vector double, vector double, int);
5534// vector short vec_xxsldwi(vector short, vector short, int);
5535bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5536 unsigned ExpectedNumArgs = 3;
5537 if (TheCall->getNumArgs() < ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005538 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005539 diag::err_typecheck_call_too_few_args_at_least)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005540 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
Aaron Ballman68d50642018-06-19 14:53:20 +00005541 << TheCall->getSourceRange();
5542
5543 if (TheCall->getNumArgs() > ExpectedNumArgs)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005544 return Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005545 diag::err_typecheck_call_too_many_args_at_most)
5546 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5547 << TheCall->getSourceRange();
5548
5549 // Check the third argument is a compile time constant
5550 llvm::APSInt Value;
5551 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005552 return Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005553 diag::err_vsx_builtin_nonconstant_argument)
5554 << 3 /* argument index */ << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005555 << SourceRange(TheCall->getArg(2)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005556 TheCall->getArg(2)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005557
5558 QualType Arg1Ty = TheCall->getArg(0)->getType();
5559 QualType Arg2Ty = TheCall->getArg(1)->getType();
5560
5561 // Check the type of argument 1 and argument 2 are vectors.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005562 SourceLocation BuiltinLoc = TheCall->getBeginLoc();
Aaron Ballman68d50642018-06-19 14:53:20 +00005563 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5564 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5565 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5566 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005567 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005568 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005569 }
5570
5571 // Check the first two arguments are the same type.
5572 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5573 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5574 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005575 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005576 TheCall->getArg(1)->getEndLoc());
Aaron Ballman68d50642018-06-19 14:53:20 +00005577 }
5578
5579 // When default clang type checking is turned off and the customized type
5580 // checking is used, the returning type of the function must be explicitly
5581 // set. Otherwise it is _Bool by default.
5582 TheCall->setType(Arg1Ty);
5583
5584 return false;
5585}
5586
5587/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5588// This is declared to take (...), so we have to check everything.
5589ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5590 if (TheCall->getNumArgs() < 2)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005591 return ExprError(Diag(TheCall->getEndLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005592 diag::err_typecheck_call_too_few_args_at_least)
5593 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5594 << TheCall->getSourceRange());
5595
5596 // Determine which of the following types of shufflevector we're checking:
5597 // 1) unary, vector mask: (lhs, mask)
5598 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5599 QualType resType = TheCall->getArg(0)->getType();
5600 unsigned numElements = 0;
5601
5602 if (!TheCall->getArg(0)->isTypeDependent() &&
5603 !TheCall->getArg(1)->isTypeDependent()) {
5604 QualType LHSType = TheCall->getArg(0)->getType();
5605 QualType RHSType = TheCall->getArg(1)->getType();
5606
5607 if (!LHSType->isVectorType() || !RHSType->isVectorType())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005608 return ExprError(
5609 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5610 << TheCall->getDirectCallee()
5611 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005612 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005613
5614 numElements = LHSType->getAs<VectorType>()->getNumElements();
5615 unsigned numResElements = TheCall->getNumArgs() - 2;
5616
5617 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5618 // with mask. If so, verify that RHS is an integer vector type with the
5619 // same number of elts as lhs.
5620 if (TheCall->getNumArgs() == 2) {
5621 if (!RHSType->hasIntegerRepresentation() ||
5622 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005623 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005624 diag::err_vec_builtin_incompatible_vector)
5625 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005626 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005627 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005628 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005629 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005630 diag::err_vec_builtin_incompatible_vector)
5631 << TheCall->getDirectCallee()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005632 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005633 TheCall->getArg(1)->getEndLoc()));
Aaron Ballman68d50642018-06-19 14:53:20 +00005634 } else if (numElements != numResElements) {
5635 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5636 resType = Context.getVectorType(eltType, numResElements,
5637 VectorType::GenericVector);
5638 }
5639 }
5640
5641 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5642 if (TheCall->getArg(i)->isTypeDependent() ||
5643 TheCall->getArg(i)->isValueDependent())
5644 continue;
5645
5646 llvm::APSInt Result(32);
5647 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005648 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005649 diag::err_shufflevector_nonconstant_argument)
5650 << TheCall->getArg(i)->getSourceRange());
5651
5652 // Allow -1 which will be translated to undef in the IR.
5653 if (Result.isSigned() && Result.isAllOnesValue())
5654 continue;
5655
5656 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005657 return ExprError(Diag(TheCall->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005658 diag::err_shufflevector_argument_too_large)
5659 << TheCall->getArg(i)->getSourceRange());
5660 }
5661
5662 SmallVector<Expr*, 32> exprs;
5663
5664 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5665 exprs.push_back(TheCall->getArg(i));
5666 TheCall->setArg(i, nullptr);
5667 }
5668
5669 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005670 TheCall->getCallee()->getBeginLoc(),
Aaron Ballman68d50642018-06-19 14:53:20 +00005671 TheCall->getRParenLoc());
5672}
5673
5674/// SemaConvertVectorExpr - Handle __builtin_convertvector
5675ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5676 SourceLocation BuiltinLoc,
5677 SourceLocation RParenLoc) {
5678 ExprValueKind VK = VK_RValue;
5679 ExprObjectKind OK = OK_Ordinary;
5680 QualType DstTy = TInfo->getType();
5681 QualType SrcTy = E->getType();
5682
5683 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5684 return ExprError(Diag(BuiltinLoc,
5685 diag::err_convertvector_non_vector)
5686 << E->getSourceRange());
5687 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5688 return ExprError(Diag(BuiltinLoc,
5689 diag::err_convertvector_non_vector_type));
5690
5691 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5692 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5693 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5694 if (SrcElts != DstElts)
5695 return ExprError(Diag(BuiltinLoc,
5696 diag::err_convertvector_incompatible_vector)
5697 << E->getSourceRange());
5698 }
5699
5700 return new (Context)
5701 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5702}
5703
5704/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5705// This is declared to take (const void*, ...) and can take two
5706// optional constant int args.
5707bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5708 unsigned NumArgs = TheCall->getNumArgs();
5709
5710 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005711 return Diag(TheCall->getEndLoc(),
5712 diag::err_typecheck_call_too_many_args_at_most)
5713 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Aaron Ballman68d50642018-06-19 14:53:20 +00005714
5715 // Argument 0 is checked for us and the remaining arguments must be
5716 // constant integers.
5717 for (unsigned i = 1; i != NumArgs; ++i)
Richard Sandiford28940af2014-04-16 08:47:51 +00005718 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005719 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005720
Warren Hunt20e4a5d2014-02-21 23:08:53 +00005721 return false;
5722}
5723
Hal Finkelf0417332014-07-17 14:25:55 +00005724/// SemaBuiltinAssume - Handle __assume (MS Extension).
5725// __assume does not evaluate its arguments, and should warn if its argument
5726// has side effects.
5727bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5728 Expr *Arg = TheCall->getArg(0);
5729 if (Arg->isInstantiationDependent()) return false;
5730
5731 if (Arg->HasSideEffects(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005732 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5733 << Arg->getSourceRange()
5734 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
Hal Finkelbcc06082014-09-07 22:58:14 +00005735
5736 return false;
5737}
5738
David Majnemer86b1bfa2016-10-31 18:07:57 +00005739/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00005740/// as (size_t, size_t) where the second size_t must be a power of 2 greater
5741/// than 8.
5742bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5743 // The alignment must be a constant integer.
5744 Expr *Arg = TheCall->getArg(1);
5745
5746 // We can't check the value of a dependent argument.
5747 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00005748 if (const auto *UE =
5749 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
Richard Smith6822bd72018-10-26 19:26:45 +00005750 if (UE->getKind() == UETT_AlignOf ||
5751 UE->getKind() == UETT_PreferredAlignOf)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005752 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5753 << Arg->getSourceRange();
David Majnemer86b1bfa2016-10-31 18:07:57 +00005754
David Majnemer51169932016-10-31 05:37:48 +00005755 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5756
5757 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005758 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5759 << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005760
5761 if (Result < Context.getCharWidth())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005762 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5763 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005764
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005765 if (Result > std::numeric_limits<int32_t>::max())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005766 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5767 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
David Majnemer51169932016-10-31 05:37:48 +00005768 }
5769
5770 return false;
5771}
5772
5773/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00005774/// as (const void*, size_t, ...) and can take one optional constant int arg.
5775bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5776 unsigned NumArgs = TheCall->getNumArgs();
5777
5778 if (NumArgs > 3)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005779 return Diag(TheCall->getEndLoc(),
5780 diag::err_typecheck_call_too_many_args_at_most)
5781 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00005782
5783 // The alignment must be a constant integer.
5784 Expr *Arg = TheCall->getArg(1);
5785
5786 // We can't check the value of a dependent argument.
5787 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5788 llvm::APSInt Result;
5789 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5790 return true;
5791
5792 if (!Result.isPowerOf2())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005793 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5794 << Arg->getSourceRange();
Hal Finkelbcc06082014-09-07 22:58:14 +00005795 }
5796
5797 if (NumArgs > 2) {
5798 ExprResult Arg(TheCall->getArg(2));
5799 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5800 Context.getSizeType(), false);
5801 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5802 if (Arg.isInvalid()) return true;
5803 TheCall->setArg(2, Arg.get());
5804 }
Hal Finkelf0417332014-07-17 14:25:55 +00005805
5806 return false;
5807}
5808
Mehdi Amini06d367c2016-10-24 20:39:34 +00005809bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5810 unsigned BuiltinID =
5811 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5812 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5813
5814 unsigned NumArgs = TheCall->getNumArgs();
5815 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5816 if (NumArgs < NumRequiredArgs) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005817 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005818 << 0 /* function call */ << NumRequiredArgs << NumArgs
5819 << TheCall->getSourceRange();
5820 }
5821 if (NumArgs >= NumRequiredArgs + 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005822 return Diag(TheCall->getEndLoc(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005823 diag::err_typecheck_call_too_many_args_at_most)
5824 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5825 << TheCall->getSourceRange();
5826 }
5827 unsigned i = 0;
5828
5829 // For formatting call, check buffer arg.
5830 if (!IsSizeCall) {
5831 ExprResult Arg(TheCall->getArg(i));
5832 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5833 Context, Context.VoidPtrTy, false);
5834 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5835 if (Arg.isInvalid())
5836 return true;
5837 TheCall->setArg(i, Arg.get());
5838 i++;
5839 }
5840
5841 // Check string literal arg.
5842 unsigned FormatIdx = i;
5843 {
5844 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5845 if (Arg.isInvalid())
5846 return true;
5847 TheCall->setArg(i, Arg.get());
5848 i++;
5849 }
5850
5851 // Make sure variadic args are scalar.
5852 unsigned FirstDataArg = i;
5853 while (i < NumArgs) {
5854 ExprResult Arg = DefaultVariadicArgumentPromotion(
5855 TheCall->getArg(i), VariadicFunction, nullptr);
5856 if (Arg.isInvalid())
5857 return true;
5858 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5859 if (ArgSize.getQuantity() >= 0x100) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005860 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005861 << i << (int)ArgSize.getQuantity() << 0xff
5862 << TheCall->getSourceRange();
5863 }
5864 TheCall->setArg(i, Arg.get());
5865 i++;
5866 }
5867
5868 // Check formatting specifiers. NOTE: We're only doing this for the non-size
5869 // call to avoid duplicate diagnostics.
5870 if (!IsSizeCall) {
5871 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5872 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5873 bool Success = CheckFormatArguments(
5874 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005875 VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005876 CheckedVarArgs);
5877 if (!Success)
5878 return true;
5879 }
5880
5881 if (IsSizeCall) {
5882 TheCall->setType(Context.getSizeType());
5883 } else {
5884 TheCall->setType(Context.VoidPtrTy);
5885 }
5886 return false;
5887}
5888
Eric Christopher8d0c6212010-04-17 02:26:23 +00005889/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5890/// TheCall is a constant expression.
5891bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5892 llvm::APSInt &Result) {
5893 Expr *Arg = TheCall->getArg(ArgNum);
5894 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5895 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00005896
Eric Christopher8d0c6212010-04-17 02:26:23 +00005897 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00005898
Eric Christopher8d0c6212010-04-17 02:26:23 +00005899 if (!Arg->isIntegerConstantExpr(Result, Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005900 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5901 << FDecl->getDeclName() << Arg->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00005902
Chris Lattnerd545ad12009-09-23 06:06:36 +00005903 return false;
5904}
5905
Richard Sandiford28940af2014-04-16 08:47:51 +00005906/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5907/// TheCall is a constant expression in the range [Low, High].
5908bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005909 int Low, int High, bool RangeIsError) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00005910 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005911
5912 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00005913 Expr *Arg = TheCall->getArg(ArgNum);
5914 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005915 return false;
5916
Eric Christopher8d0c6212010-04-17 02:26:23 +00005917 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00005918 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005919 return true;
5920
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005921 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5922 if (RangeIsError)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005923 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005924 << Result.toString(10) << Low << High << Arg->getSourceRange();
5925 else
5926 // Defer the warning until we know if the code will be emitted so that
5927 // dead code can ignore this.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005928 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5929 PDiag(diag::warn_argument_invalid_range)
5930 << Result.toString(10) << Low << High
5931 << Arg->getSourceRange());
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005932 }
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00005933
5934 return false;
5935}
5936
Simon Dardis1f90f2d2016-10-19 17:50:52 +00005937/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5938/// TheCall is a constant expression is a multiple of Num..
5939bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5940 unsigned Num) {
5941 llvm::APSInt Result;
5942
5943 // We can't check the value of a dependent argument.
5944 Expr *Arg = TheCall->getArg(ArgNum);
5945 if (Arg->isTypeDependent() || Arg->isValueDependent())
5946 return false;
5947
5948 // Check constant-ness first.
5949 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5950 return true;
5951
5952 if (Result.getSExtValue() % Num != 0)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005953 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5954 << Num << Arg->getSourceRange();
Simon Dardis1f90f2d2016-10-19 17:50:52 +00005955
5956 return false;
5957}
5958
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005959/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5960/// TheCall is an ARM/AArch64 special register string literal.
5961bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5962 int ArgNum, unsigned ExpectedFieldNum,
5963 bool AllowName) {
5964 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5965 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5966 BuiltinID == ARM::BI__builtin_arm_rsr ||
5967 BuiltinID == ARM::BI__builtin_arm_rsrp ||
5968 BuiltinID == ARM::BI__builtin_arm_wsr ||
5969 BuiltinID == ARM::BI__builtin_arm_wsrp;
5970 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5971 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5972 BuiltinID == AArch64::BI__builtin_arm_rsr ||
5973 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5974 BuiltinID == AArch64::BI__builtin_arm_wsr ||
5975 BuiltinID == AArch64::BI__builtin_arm_wsrp;
5976 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5977
5978 // We can't check the value of a dependent argument.
5979 Expr *Arg = TheCall->getArg(ArgNum);
5980 if (Arg->isTypeDependent() || Arg->isValueDependent())
5981 return false;
5982
5983 // Check if the argument is a string literal.
5984 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005985 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005986 << Arg->getSourceRange();
5987
5988 // Check the type of special register given.
5989 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5990 SmallVector<StringRef, 6> Fields;
5991 Reg.split(Fields, ":");
5992
5993 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005994 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005995 << Arg->getSourceRange();
5996
5997 // If the string is the name of a register then we cannot check that it is
5998 // valid here but if the string is of one the forms described in ACLE then we
5999 // can check that the supplied fields are integers and within the valid
6000 // ranges.
6001 if (Fields.size() > 1) {
6002 bool FiveFields = Fields.size() == 5;
6003
6004 bool ValidString = true;
6005 if (IsARMBuiltin) {
6006 ValidString &= Fields[0].startswith_lower("cp") ||
6007 Fields[0].startswith_lower("p");
6008 if (ValidString)
6009 Fields[0] =
6010 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6011
6012 ValidString &= Fields[2].startswith_lower("c");
6013 if (ValidString)
6014 Fields[2] = Fields[2].drop_front(1);
6015
6016 if (FiveFields) {
6017 ValidString &= Fields[3].startswith_lower("c");
6018 if (ValidString)
6019 Fields[3] = Fields[3].drop_front(1);
6020 }
6021 }
6022
6023 SmallVector<int, 5> Ranges;
6024 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00006025 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006026 else
6027 Ranges.append({15, 7, 15});
6028
6029 for (unsigned i=0; i<Fields.size(); ++i) {
6030 int IntField;
6031 ValidString &= !Fields[i].getAsInteger(10, IntField);
6032 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6033 }
6034
6035 if (!ValidString)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006036 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006037 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00006038 } else if (IsAArch64Builtin && Fields.size() == 1) {
6039 // If the register name is one of those that appear in the condition below
6040 // and the special register builtin being used is one of the write builtins,
6041 // then we require that the argument provided for writing to the register
6042 // is an integer constant expression. This is because it will be lowered to
6043 // an MSR (immediate) instruction, so we need to know the immediate at
6044 // compile time.
6045 if (TheCall->getNumArgs() != 2)
6046 return false;
6047
6048 std::string RegLower = Reg.lower();
6049 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6050 RegLower != "pan" && RegLower != "uao")
6051 return false;
6052
6053 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6054 }
6055
6056 return false;
6057}
6058
Eli Friedmanc97d0142009-05-03 06:04:26 +00006059/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006060/// This checks that the target supports __builtin_longjmp and
6061/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006062bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006063 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006064 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006065 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006066
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006067 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00006068 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00006069
Eric Christopher8d0c6212010-04-17 02:26:23 +00006070 // TODO: This is less than ideal. Overload this to take a value.
6071 if (SemaBuiltinConstantArg(TheCall, 1, Result))
6072 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00006073
Eric Christopher8d0c6212010-04-17 02:26:23 +00006074 if (Result != 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006075 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006076 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
Eli Friedmaneed8ad22009-05-03 04:46:36 +00006077
6078 return false;
6079}
6080
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006081/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6082/// This checks that the target supports __builtin_setjmp.
6083bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6084 if (!Context.getTargetInfo().hasSjLjLowering())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006085 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006086 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
Joerg Sonnenberger27173282015-03-11 23:46:32 +00006087 return false;
6088}
6089
Richard Smithd7293d72013-08-05 18:49:43 +00006090namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006091
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006092class UncoveredArgHandler {
6093 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006094
6095 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006096 SmallVector<const Expr *, 4> DiagnosticExprs;
6097
6098public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006099 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006100
6101 bool hasUncoveredArg() const {
6102 return (FirstUncoveredArg >= 0);
6103 }
6104
6105 unsigned getUncoveredArg() const {
6106 assert(hasUncoveredArg() && "no uncovered argument");
6107 return FirstUncoveredArg;
6108 }
6109
6110 void setAllCovered() {
6111 // A string has been found with all arguments covered, so clear out
6112 // the diagnostics.
6113 DiagnosticExprs.clear();
6114 FirstUncoveredArg = AllCovered;
6115 }
6116
6117 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6118 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6119
6120 // Don't update if a previous string covers all arguments.
6121 if (FirstUncoveredArg == AllCovered)
6122 return;
6123
6124 // UncoveredArgHandler tracks the highest uncovered argument index
6125 // and with it all the strings that match this index.
6126 if (NewFirstUncoveredArg == FirstUncoveredArg)
6127 DiagnosticExprs.push_back(StrExpr);
6128 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6129 DiagnosticExprs.clear();
6130 DiagnosticExprs.push_back(StrExpr);
6131 FirstUncoveredArg = NewFirstUncoveredArg;
6132 }
6133 }
6134
6135 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6136};
6137
Richard Smithd7293d72013-08-05 18:49:43 +00006138enum StringLiteralCheckType {
6139 SLCT_NotALiteral,
6140 SLCT_UncheckedLiteral,
6141 SLCT_CheckedLiteral
6142};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006143
6144} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00006145
Stephen Hines648c3692016-09-16 01:07:04 +00006146static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6147 BinaryOperatorKind BinOpKind,
6148 bool AddendIsRight) {
6149 unsigned BitWidth = Offset.getBitWidth();
6150 unsigned AddendBitWidth = Addend.getBitWidth();
6151 // There might be negative interim results.
6152 if (Addend.isUnsigned()) {
6153 Addend = Addend.zext(++AddendBitWidth);
6154 Addend.setIsSigned(true);
6155 }
6156 // Adjust the bit width of the APSInts.
6157 if (AddendBitWidth > BitWidth) {
6158 Offset = Offset.sext(AddendBitWidth);
6159 BitWidth = AddendBitWidth;
6160 } else if (BitWidth > AddendBitWidth) {
6161 Addend = Addend.sext(BitWidth);
6162 }
6163
6164 bool Ov = false;
6165 llvm::APSInt ResOffset = Offset;
6166 if (BinOpKind == BO_Add)
6167 ResOffset = Offset.sadd_ov(Addend, Ov);
6168 else {
6169 assert(AddendIsRight && BinOpKind == BO_Sub &&
6170 "operator must be add or sub with addend on the right");
6171 ResOffset = Offset.ssub_ov(Addend, Ov);
6172 }
6173
6174 // We add an offset to a pointer here so we should support an offset as big as
6175 // possible.
6176 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006177 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6178 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00006179 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00006180 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6181 return;
6182 }
6183
6184 Offset = ResOffset;
6185}
6186
6187namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006188
Stephen Hines648c3692016-09-16 01:07:04 +00006189// This is a wrapper class around StringLiteral to support offsetted string
6190// literals as format strings. It takes the offset into account when returning
6191// the string and its length or the source locations to display notes correctly.
6192class FormatStringLiteral {
6193 const StringLiteral *FExpr;
6194 int64_t Offset;
6195
6196 public:
6197 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6198 : FExpr(fexpr), Offset(Offset) {}
6199
6200 StringRef getString() const {
6201 return FExpr->getString().drop_front(Offset);
6202 }
6203
6204 unsigned getByteLength() const {
6205 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6206 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006207
Stephen Hines648c3692016-09-16 01:07:04 +00006208 unsigned getLength() const { return FExpr->getLength() - Offset; }
6209 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6210
6211 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6212
6213 QualType getType() const { return FExpr->getType(); }
6214
6215 bool isAscii() const { return FExpr->isAscii(); }
6216 bool isWide() const { return FExpr->isWide(); }
6217 bool isUTF8() const { return FExpr->isUTF8(); }
6218 bool isUTF16() const { return FExpr->isUTF16(); }
6219 bool isUTF32() const { return FExpr->isUTF32(); }
6220 bool isPascal() const { return FExpr->isPascal(); }
6221
6222 SourceLocation getLocationOfByte(
6223 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6224 const TargetInfo &Target, unsigned *StartToken = nullptr,
6225 unsigned *StartTokenByteOffset = nullptr) const {
6226 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6227 StartToken, StartTokenByteOffset);
6228 }
6229
Stephen Kelly724e9e52018-08-09 20:05:03 +00006230 SourceLocation getBeginLoc() const LLVM_READONLY {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006231 return FExpr->getBeginLoc().getLocWithOffset(Offset);
Stephen Hines648c3692016-09-16 01:07:04 +00006232 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006233
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006234 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
Stephen Hines648c3692016-09-16 01:07:04 +00006235};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006236
6237} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00006238
6239static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006240 const Expr *OrigFormatExpr,
6241 ArrayRef<const Expr *> Args,
6242 bool HasVAListArg, unsigned format_idx,
6243 unsigned firstDataArg,
6244 Sema::FormatStringType Type,
6245 bool inFunctionCall,
6246 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006247 llvm::SmallBitVector &CheckedVarArgs,
6248 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006249
Richard Smith55ce3522012-06-25 20:30:08 +00006250// Determine if an expression is a string literal or constant string.
6251// If this function returns false on the arguments to a function expecting a
6252// format string, we will usually need to emit a warning.
6253// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00006254static StringLiteralCheckType
6255checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6256 bool HasVAListArg, unsigned format_idx,
6257 unsigned firstDataArg, Sema::FormatStringType Type,
6258 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006259 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006260 UncoveredArgHandler &UncoveredArg,
6261 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00006262 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00006263 assert(Offset.isSigned() && "invalid offset");
6264
Douglas Gregorc25f7662009-05-19 22:10:17 +00006265 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00006266 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006267
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006268 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00006269
Richard Smithd7293d72013-08-05 18:49:43 +00006270 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00006271 // Technically -Wformat-nonliteral does not warn about this case.
6272 // The behavior of printf and friends in this case is implementation
6273 // dependent. Ideally if the format string cannot be null then
6274 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00006275 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00006276
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006277 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00006278 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006279 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00006280 // The expression is a literal if both sub-expressions were, and it was
6281 // completely checked only if both sub-expressions were checked.
6282 const AbstractConditionalOperator *C =
6283 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006284
6285 // Determine whether it is necessary to check both sub-expressions, for
6286 // example, because the condition expression is a constant that can be
6287 // evaluated at compile time.
6288 bool CheckLeft = true, CheckRight = true;
6289
6290 bool Cond;
6291 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6292 if (Cond)
6293 CheckRight = false;
6294 else
6295 CheckLeft = false;
6296 }
6297
Stephen Hines648c3692016-09-16 01:07:04 +00006298 // We need to maintain the offsets for the right and the left hand side
6299 // separately to check if every possible indexed expression is a valid
6300 // string literal. They might have different offsets for different string
6301 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006302 StringLiteralCheckType Left;
6303 if (!CheckLeft)
6304 Left = SLCT_UncheckedLiteral;
6305 else {
6306 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6307 HasVAListArg, format_idx, firstDataArg,
6308 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00006309 CheckedVarArgs, UncoveredArg, Offset);
6310 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006311 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00006312 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006313 }
6314
Richard Smith55ce3522012-06-25 20:30:08 +00006315 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00006316 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006317 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006318 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006319 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006320
6321 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006322 }
6323
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006324 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00006325 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6326 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006327
John McCallc07a0c72011-02-17 10:25:35 +00006328 case Stmt::OpaqueValueExprClass:
6329 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6330 E = src;
6331 goto tryAgain;
6332 }
Richard Smith55ce3522012-06-25 20:30:08 +00006333 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00006334
Ted Kremeneka8890832011-02-24 23:03:04 +00006335 case Stmt::PredefinedExprClass:
6336 // While __func__, etc., are technically not string literals, they
6337 // cannot contain format specifiers and thus are not a security
6338 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00006339 return SLCT_UncheckedLiteral;
Fangrui Song6907ce22018-07-30 19:24:48 +00006340
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006341 case Stmt::DeclRefExprClass: {
6342 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006343
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006344 // As an exception, do not flag errors for variables binding to
6345 // const string literals.
6346 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6347 bool isConstant = false;
6348 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006349
Richard Smithd7293d72013-08-05 18:49:43 +00006350 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6351 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00006352 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00006353 isConstant = T.isConstant(S.Context) &&
6354 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00006355 } else if (T->isObjCObjectPointerType()) {
6356 // In ObjC, there is usually no "const ObjectPointer" type,
6357 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00006358 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006359 }
Mike Stump11289f42009-09-09 15:08:12 +00006360
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006361 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006362 if (const Expr *Init = VD->getAnyInitializer()) {
6363 // Look through initializers like const char c[] = { "foo" }
6364 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6365 if (InitList->isStringLiteralInit())
6366 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6367 }
Richard Smithd7293d72013-08-05 18:49:43 +00006368 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006369 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006370 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006371 /*InFunctionCall*/ false, CheckedVarArgs,
6372 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00006373 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006374 }
Mike Stump11289f42009-09-09 15:08:12 +00006375
Anders Carlssonb012ca92009-06-28 19:55:58 +00006376 // For vprintf* functions (i.e., HasVAListArg==true), we add a
6377 // special check to see if the format string is a function parameter
6378 // of the function calling the printf function. If the function
6379 // has an attribute indicating it is a printf-like function, then we
6380 // should suppress warnings concerning non-literals being used in a call
6381 // to a vprintf function. For example:
6382 //
6383 // void
6384 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6385 // va_list ap;
6386 // va_start(ap, fmt);
6387 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
6388 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00006389 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006390 if (HasVAListArg) {
6391 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6392 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6393 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00006394 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006395 // adjust for implicit parameter
6396 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6397 if (MD->isInstance())
6398 ++PVIndex;
6399 // We also check if the formats are compatible.
6400 // We can't pass a 'scanf' string to a 'printf' function.
6401 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00006402 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00006403 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00006404 }
6405 }
6406 }
6407 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006408 }
Mike Stump11289f42009-09-09 15:08:12 +00006409
Richard Smith55ce3522012-06-25 20:30:08 +00006410 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006411 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006412
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006413 case Stmt::CallExprClass:
6414 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006415 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00006416 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
Michael Krusef18adbb2018-07-04 01:37:11 +00006417 bool IsFirst = true;
6418 StringLiteralCheckType CommonResult;
6419 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00006420 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Michael Krusef18adbb2018-07-04 01:37:11 +00006421 StringLiteralCheckType Result = checkFormatStringExpr(
6422 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6423 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6424 if (IsFirst) {
6425 CommonResult = Result;
6426 IsFirst = false;
6427 }
6428 }
6429 if (!IsFirst)
6430 return CommonResult;
6431
6432 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006433 unsigned BuiltinID = FD->getBuiltinID();
6434 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6435 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6436 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00006437 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00006438 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006439 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006440 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00006441 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006442 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006443 }
6444 }
Mike Stump11289f42009-09-09 15:08:12 +00006445
Richard Smith55ce3522012-06-25 20:30:08 +00006446 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00006447 }
Alex Lorenzd9007142016-10-24 09:42:34 +00006448 case Stmt::ObjCMessageExprClass: {
6449 const auto *ME = cast<ObjCMessageExpr>(E);
6450 if (const auto *ND = ME->getMethodDecl()) {
6451 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00006452 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00006453 return checkFormatStringExpr(
6454 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6455 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6456 }
6457 }
6458
6459 return SLCT_NotALiteral;
6460 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006461 case Stmt::ObjCStringLiteralClass:
6462 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00006463 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006464
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006465 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006466 StrE = ObjCFExpr->getString();
6467 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006468 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006469
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006470 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00006471 if (Offset.isNegative() || Offset > StrE->getLength()) {
6472 // TODO: It would be better to have an explicit warning for out of
6473 // bounds literals.
6474 return SLCT_NotALiteral;
6475 }
6476 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6477 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006478 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006479 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00006480 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006481 }
Mike Stump11289f42009-09-09 15:08:12 +00006482
Richard Smith55ce3522012-06-25 20:30:08 +00006483 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006484 }
Stephen Hines648c3692016-09-16 01:07:04 +00006485 case Stmt::BinaryOperatorClass: {
6486 llvm::APSInt LResult;
6487 llvm::APSInt RResult;
6488
6489 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6490
6491 // A string literal + an int offset is still a string literal.
6492 if (BinOp->isAdditiveOp()) {
6493 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6494 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6495
6496 if (LIsInt != RIsInt) {
6497 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6498
6499 if (LIsInt) {
6500 if (BinOpKind == BO_Add) {
6501 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
6502 E = BinOp->getRHS();
6503 goto tryAgain;
6504 }
6505 } else {
6506 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
6507 E = BinOp->getLHS();
6508 goto tryAgain;
6509 }
6510 }
Stephen Hines648c3692016-09-16 01:07:04 +00006511 }
George Burgess IVd273aab2016-09-22 00:00:26 +00006512
6513 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00006514 }
6515 case Stmt::UnaryOperatorClass: {
6516 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6517 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006518 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00006519 llvm::APSInt IndexResult;
6520 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
6521 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
6522 E = ASE->getBase();
6523 goto tryAgain;
6524 }
6525 }
6526
6527 return SLCT_NotALiteral;
6528 }
Mike Stump11289f42009-09-09 15:08:12 +00006529
Ted Kremenekdfd72c22009-03-20 21:35:28 +00006530 default:
Richard Smith55ce3522012-06-25 20:30:08 +00006531 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006532 }
6533}
6534
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006535Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00006536 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00006537 .Case("scanf", FST_Scanf)
6538 .Cases("printf", "printf0", FST_Printf)
6539 .Cases("NSString", "CFString", FST_NSString)
6540 .Case("strftime", FST_Strftime)
6541 .Case("strfmon", FST_Strfmon)
6542 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6543 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6544 .Case("os_trace", FST_OSLog)
6545 .Case("os_log", FST_OSLog)
6546 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006547}
6548
Jordan Rose3e0ec582012-07-19 18:10:23 +00006549/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00006550/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00006551/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006552bool Sema::CheckFormatArguments(const FormatAttr *Format,
6553 ArrayRef<const Expr *> Args,
6554 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006555 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00006556 SourceLocation Loc, SourceRange Range,
6557 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00006558 FormatStringInfo FSI;
6559 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006560 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00006561 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00006562 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00006563 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006564}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00006565
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006566bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006567 bool HasVAListArg, unsigned format_idx,
6568 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006569 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00006570 SourceLocation Loc, SourceRange Range,
6571 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00006572 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006573 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006574 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00006575 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006576 }
Mike Stump11289f42009-09-09 15:08:12 +00006577
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006578 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006579
Chris Lattnerb87b1b32007-08-10 20:18:51 +00006580 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00006581 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006582 // Dynamically generated format strings are difficult to
6583 // automatically vet at compile time. Requiring that format strings
6584 // are string literals: (1) permits the checking of format strings by
6585 // the compiler and thereby (2) can practically remove the source of
6586 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00006587
Mike Stump11289f42009-09-09 15:08:12 +00006588 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00006589 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00006590 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00006591 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006592 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00006593 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00006594 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6595 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00006596 /*IsFunctionCall*/ true, CheckedVarArgs,
6597 UncoveredArg,
6598 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006599
6600 // Generate a diagnostic where an uncovered argument is detected.
6601 if (UncoveredArg.hasUncoveredArg()) {
6602 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6603 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6604 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6605 }
6606
Richard Smith55ce3522012-06-25 20:30:08 +00006607 if (CT != SLCT_NotALiteral)
6608 // Literal format string found, check done!
6609 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00006610
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00006611 // Strftime is particular as it always uses a single 'time' argument,
6612 // so it is safe to pass a non-literal string.
6613 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00006614 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00006615
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00006616 // Do not emit diag when the string param is a macro expansion and the
6617 // format is either NSString or CFString. This is a hack to prevent
6618 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6619 // which are usually used in place of NS and CF string literals.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006620 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006621 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00006622 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00006623
Chris Lattnercc5d1c22009-04-29 04:59:47 +00006624 // If there are no arguments specified, warn with -Wformat-security, otherwise
6625 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006626 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00006627 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6628 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006629 switch (Type) {
6630 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006631 break;
6632 case FST_Kprintf:
6633 case FST_FreeBSDKPrintf:
6634 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00006635 Diag(FormatLoc, diag::note_format_security_fixit)
6636 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006637 break;
6638 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00006639 Diag(FormatLoc, diag::note_format_security_fixit)
6640 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006641 break;
6642 }
6643 } else {
6644 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00006645 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00006646 }
Richard Smith55ce3522012-06-25 20:30:08 +00006647 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00006648}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00006649
Ted Kremenekab278de2010-01-28 23:39:18 +00006650namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006651
Ted Kremenek02087932010-07-16 02:11:22 +00006652class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6653protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00006654 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00006655 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00006656 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006657 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00006658 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00006659 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00006660 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00006661 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006662 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00006663 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00006664 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006665 bool usesPositionalArgs = false;
6666 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006667 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00006668 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00006669 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006670 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006671
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006672public:
Stephen Hines648c3692016-09-16 01:07:04 +00006673 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006674 const Expr *origFormatExpr,
6675 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006676 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006677 ArrayRef<const Expr *> Args, unsigned formatIdx,
6678 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006679 llvm::SmallBitVector &CheckedVarArgs,
6680 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006681 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6682 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6683 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00006684 inFunctionCall(inFunctionCall), CallType(callType),
6685 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00006686 CoveredArgs.resize(numDataArgs);
6687 CoveredArgs.reset();
6688 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006689
Ted Kremenek019d2242010-01-29 01:50:07 +00006690 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006691
Ted Kremenek02087932010-07-16 02:11:22 +00006692 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006693 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006694
Jordan Rose92303592012-09-08 04:00:03 +00006695 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00006696 const analyze_format_string::FormatSpecifier &FS,
6697 const analyze_format_string::ConversionSpecifier &CS,
6698 const char *startSpecifier, unsigned specifierLen,
6699 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00006700
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006701 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00006702 const analyze_format_string::FormatSpecifier &FS,
6703 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006704
6705 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00006706 const analyze_format_string::ConversionSpecifier &CS,
6707 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006708
Craig Toppere14c0f82014-03-12 04:55:44 +00006709 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00006710
Craig Toppere14c0f82014-03-12 04:55:44 +00006711 void HandleInvalidPosition(const char *startSpecifier,
6712 unsigned specifierLen,
6713 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00006714
Craig Toppere14c0f82014-03-12 04:55:44 +00006715 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00006716
Craig Toppere14c0f82014-03-12 04:55:44 +00006717 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006718
Richard Trieu03cf7b72011-10-28 00:41:25 +00006719 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00006720 static void
6721 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6722 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6723 bool IsStringLocation, Range StringRange,
6724 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00006725
Ted Kremenek02087932010-07-16 02:11:22 +00006726protected:
Ted Kremenekce815422010-07-19 21:25:57 +00006727 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6728 const char *startSpec,
6729 unsigned specifierLen,
6730 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00006731
6732 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6733 const char *startSpec,
6734 unsigned specifierLen);
Fangrui Song6907ce22018-07-30 19:24:48 +00006735
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006736 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00006737 CharSourceRange getSpecifierRange(const char *startSpecifier,
6738 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00006739 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006740
Ted Kremenek5739de72010-01-29 01:06:55 +00006741 const Expr *getDataArg(unsigned i) const;
Fangrui Song6907ce22018-07-30 19:24:48 +00006742
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006743 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6744 const analyze_format_string::ConversionSpecifier &CS,
6745 const char *startSpecifier, unsigned specifierLen,
6746 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00006747
6748 template <typename Range>
6749 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6750 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00006751 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00006752};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006753
6754} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006755
Ted Kremenek02087932010-07-16 02:11:22 +00006756SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00006757 return OrigFormatExpr->getSourceRange();
6758}
6759
Ted Kremenek02087932010-07-16 02:11:22 +00006760CharSourceRange CheckFormatHandler::
6761getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00006762 SourceLocation Start = getLocationOfByte(startSpecifier);
6763 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
6764
6765 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00006766 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00006767
6768 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006769}
6770
Ted Kremenek02087932010-07-16 02:11:22 +00006771SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00006772 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6773 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00006774}
6775
Ted Kremenek02087932010-07-16 02:11:22 +00006776void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6777 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00006778 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6779 getLocationOfByte(startSpecifier),
6780 /*IsStringLocation*/true,
6781 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00006782}
6783
Jordan Rose92303592012-09-08 04:00:03 +00006784void CheckFormatHandler::HandleInvalidLengthModifier(
6785 const analyze_format_string::FormatSpecifier &FS,
6786 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00006787 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00006788 using namespace analyze_format_string;
6789
6790 const LengthModifier &LM = FS.getLengthModifier();
6791 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6792
6793 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00006794 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00006795 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00006796 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00006797 getLocationOfByte(LM.getStart()),
6798 /*IsStringLocation*/true,
6799 getSpecifierRange(startSpecifier, specifierLen));
6800
6801 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6802 << FixedLM->toString()
6803 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6804
6805 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00006806 FixItHint Hint;
6807 if (DiagID == diag::warn_format_nonsensical_length)
6808 Hint = FixItHint::CreateRemoval(LMRange);
6809
6810 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00006811 getLocationOfByte(LM.getStart()),
6812 /*IsStringLocation*/true,
6813 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00006814 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00006815 }
6816}
6817
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006818void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00006819 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006820 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00006821 using namespace analyze_format_string;
6822
6823 const LengthModifier &LM = FS.getLengthModifier();
6824 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6825
6826 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00006827 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00006828 if (FixedLM) {
6829 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6830 << LM.toString() << 0,
6831 getLocationOfByte(LM.getStart()),
6832 /*IsStringLocation*/true,
6833 getSpecifierRange(startSpecifier, specifierLen));
6834
6835 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6836 << FixedLM->toString()
6837 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6838
6839 } else {
6840 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6841 << LM.toString() << 0,
6842 getLocationOfByte(LM.getStart()),
6843 /*IsStringLocation*/true,
6844 getSpecifierRange(startSpecifier, specifierLen));
6845 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006846}
6847
6848void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6849 const analyze_format_string::ConversionSpecifier &CS,
6850 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00006851 using namespace analyze_format_string;
6852
6853 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00006854 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00006855 if (FixedCS) {
6856 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6857 << CS.toString() << /*conversion specifier*/1,
6858 getLocationOfByte(CS.getStart()),
6859 /*IsStringLocation*/true,
6860 getSpecifierRange(startSpecifier, specifierLen));
6861
6862 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6863 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6864 << FixedCS->toString()
6865 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6866 } else {
6867 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6868 << CS.toString() << /*conversion specifier*/1,
6869 getLocationOfByte(CS.getStart()),
6870 /*IsStringLocation*/true,
6871 getSpecifierRange(startSpecifier, specifierLen));
6872 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006873}
6874
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00006875void CheckFormatHandler::HandlePosition(const char *startPos,
6876 unsigned posLen) {
6877 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6878 getLocationOfByte(startPos),
6879 /*IsStringLocation*/true,
6880 getSpecifierRange(startPos, posLen));
6881}
6882
Ted Kremenekd1668192010-02-27 01:41:03 +00006883void
Ted Kremenek02087932010-07-16 02:11:22 +00006884CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
6885 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006886 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
6887 << (unsigned) p,
6888 getLocationOfByte(startPos), /*IsStringLocation*/true,
6889 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00006890}
6891
Ted Kremenek02087932010-07-16 02:11:22 +00006892void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00006893 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006894 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6895 getLocationOfByte(startPos),
6896 /*IsStringLocation*/true,
6897 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00006898}
6899
Ted Kremenek02087932010-07-16 02:11:22 +00006900void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00006901 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00006902 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006903 EmitFormatDiagnostic(
6904 S.PDiag(diag::warn_printf_format_string_contains_null_char),
6905 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6906 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00006907 }
Ted Kremenek02087932010-07-16 02:11:22 +00006908}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006909
Jordan Rose58bbe422012-07-19 18:10:08 +00006910// Note that this may return NULL if there was an error parsing or building
6911// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00006912const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006913 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00006914}
6915
6916void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006917 // Does the number of data arguments exceed the number of
6918 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00006919 if (!HasVAListArg) {
6920 // Find any arguments that weren't covered.
6921 CoveredArgs.flip();
6922 signed notCoveredArg = CoveredArgs.find_first();
6923 if (notCoveredArg >= 0) {
6924 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006925 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6926 } else {
6927 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00006928 }
6929 }
6930}
6931
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006932void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6933 const Expr *ArgExpr) {
6934 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6935 "Invalid state");
6936
6937 if (!ArgExpr)
6938 return;
6939
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006940 SourceLocation Loc = ArgExpr->getBeginLoc();
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006941
6942 if (S.getSourceManager().isInSystemMacro(Loc))
6943 return;
6944
6945 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6946 for (auto E : DiagnosticExprs)
6947 PDiag << E->getSourceRange();
6948
6949 CheckFormatHandler::EmitFormatDiagnostic(
6950 S, IsFunctionCall, DiagnosticExprs[0],
6951 PDiag, Loc, /*IsStringLocation*/false,
6952 DiagnosticExprs[0]->getSourceRange());
6953}
6954
Ted Kremenekce815422010-07-19 21:25:57 +00006955bool
6956CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6957 SourceLocation Loc,
6958 const char *startSpec,
6959 unsigned specifierLen,
6960 const char *csStart,
6961 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00006962 bool keepGoing = true;
6963 if (argIndex < NumDataArgs) {
6964 // Consider the argument coverered, even though the specifier doesn't
6965 // make sense.
6966 CoveredArgs.set(argIndex);
6967 }
6968 else {
6969 // If argIndex exceeds the number of data arguments we
6970 // don't issue a warning because that is just a cascade of warnings (and
6971 // they may have intended '%%' anyway). We don't want to continue processing
6972 // the format string after this point, however, as we will like just get
6973 // gibberish when trying to match arguments.
6974 keepGoing = false;
6975 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006976
6977 StringRef Specifier(csStart, csLen);
6978
6979 // If the specifier in non-printable, it could be the first byte of a UTF-8
6980 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6981 // hex value.
6982 std::string CodePointStr;
6983 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00006984 llvm::UTF32 CodePoint;
6985 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6986 const llvm::UTF8 *E =
6987 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6988 llvm::ConversionResult Result =
6989 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006990
Justin Lebar90910552016-09-30 00:38:45 +00006991 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006992 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00006993 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006994 }
6995
6996 llvm::raw_string_ostream OS(CodePointStr);
6997 if (CodePoint < 256)
6998 OS << "\\x" << llvm::format("%02x", CodePoint);
6999 else if (CodePoint <= 0xFFFF)
7000 OS << "\\u" << llvm::format("%04x", CodePoint);
7001 else
7002 OS << "\\U" << llvm::format("%08x", CodePoint);
7003 OS.flush();
7004 Specifier = CodePointStr;
7005 }
7006
7007 EmitFormatDiagnostic(
7008 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7009 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7010
Ted Kremenekce815422010-07-19 21:25:57 +00007011 return keepGoing;
7012}
7013
Richard Trieu03cf7b72011-10-28 00:41:25 +00007014void
7015CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7016 const char *startSpec,
7017 unsigned specifierLen) {
7018 EmitFormatDiagnostic(
7019 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7020 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7021}
7022
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007023bool
7024CheckFormatHandler::CheckNumArgs(
7025 const analyze_format_string::FormatSpecifier &FS,
7026 const analyze_format_string::ConversionSpecifier &CS,
7027 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7028
7029 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007030 PartialDiagnostic PDiag = FS.usesPositionalArg()
7031 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7032 << (argIndex+1) << NumDataArgs)
7033 : S.PDiag(diag::warn_printf_insufficient_data_args);
7034 EmitFormatDiagnostic(
7035 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7036 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007037
7038 // Since more arguments than conversion tokens are given, by extension
7039 // all arguments are covered, so mark this as so.
7040 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007041 return false;
7042 }
7043 return true;
7044}
7045
Richard Trieu03cf7b72011-10-28 00:41:25 +00007046template<typename Range>
7047void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7048 SourceLocation Loc,
7049 bool IsStringLocation,
7050 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00007051 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00007052 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00007053 Loc, IsStringLocation, StringRange, FixIt);
7054}
7055
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007056/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00007057/// so that the function call and string are in diagnostic messages.
7058///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007059/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00007060/// call and only one diagnostic message will be produced. Otherwise, an
7061/// extra note will be emitted pointing to location of the format string.
7062///
7063/// \param ArgumentExpr the expression that is passed as the format string
7064/// argument in the function call. Used for getting locations when two
7065/// diagnostics are emitted.
7066///
7067/// \param PDiag the callee should already have provided any strings for the
7068/// diagnostic message. This function only adds locations and fixits
7069/// to diagnostics.
7070///
7071/// \param Loc primary location for diagnostic. If two diagnostics are
7072/// required, one will be at Loc and a new SourceLocation will be created for
7073/// the other one.
7074///
7075/// \param IsStringLocation if true, Loc points to the format string should be
7076/// used for the note. Otherwise, Loc points to the argument list and will
7077/// be used with PDiag.
7078///
7079/// \param StringRange some or all of the string to highlight. This is
7080/// templated so it can accept either a CharSourceRange or a SourceRange.
7081///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00007082/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00007083template <typename Range>
7084void CheckFormatHandler::EmitFormatDiagnostic(
7085 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7086 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7087 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00007088 if (InFunctionCall) {
7089 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7090 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007091 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00007092 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007093 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7094 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00007095
7096 const Sema::SemaDiagnosticBuilder &Note =
7097 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7098 diag::note_format_string_defined);
7099
7100 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00007101 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00007102 }
7103}
7104
Ted Kremenek02087932010-07-16 02:11:22 +00007105//===--- CHECK: Printf format string checking ------------------------------===//
7106
7107namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007108
Ted Kremenek02087932010-07-16 02:11:22 +00007109class CheckPrintfHandler : public CheckFormatHandler {
7110public:
Stephen Hines648c3692016-09-16 01:07:04 +00007111 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007112 const Expr *origFormatExpr,
7113 const Sema::FormatStringType type, unsigned firstDataArg,
7114 unsigned numDataArgs, bool isObjC, const char *beg,
7115 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00007116 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00007117 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007118 llvm::SmallBitVector &CheckedVarArgs,
7119 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007120 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7121 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7122 inFunctionCall, CallType, CheckedVarArgs,
7123 UncoveredArg) {}
7124
7125 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7126
7127 /// Returns true if '%@' specifiers are allowed in the format string.
7128 bool allowsObjCArg() const {
7129 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7130 FSType == Sema::FST_OSTrace;
7131 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00007132
Ted Kremenek02087932010-07-16 02:11:22 +00007133 bool HandleInvalidPrintfConversionSpecifier(
7134 const analyze_printf::PrintfSpecifier &FS,
7135 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007136 unsigned specifierLen) override;
7137
Ted Kremenek02087932010-07-16 02:11:22 +00007138 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7139 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007140 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007141 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7142 const char *StartSpecifier,
7143 unsigned SpecifierLen,
7144 const Expr *E);
7145
Ted Kremenek02087932010-07-16 02:11:22 +00007146 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7147 const char *startSpecifier, unsigned specifierLen);
7148 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7149 const analyze_printf::OptionalAmount &Amt,
7150 unsigned type,
7151 const char *startSpecifier, unsigned specifierLen);
7152 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7153 const analyze_printf::OptionalFlag &flag,
7154 const char *startSpecifier, unsigned specifierLen);
7155 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7156 const analyze_printf::OptionalFlag &ignoredFlag,
7157 const analyze_printf::OptionalFlag &flag,
7158 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007159 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00007160 const Expr *E);
Fangrui Song6907ce22018-07-30 19:24:48 +00007161
Ted Kremenek2b417712015-07-02 05:39:16 +00007162 void HandleEmptyObjCModifierFlag(const char *startFlag,
7163 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00007164
Ted Kremenek2b417712015-07-02 05:39:16 +00007165 void HandleInvalidObjCModifierFlag(const char *startFlag,
7166 unsigned flagLen) override;
7167
7168 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7169 const char *flagsEnd,
Fangrui Song6907ce22018-07-30 19:24:48 +00007170 const char *conversionPosition)
Ted Kremenek2b417712015-07-02 05:39:16 +00007171 override;
7172};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007173
7174} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00007175
7176bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7177 const analyze_printf::PrintfSpecifier &FS,
7178 const char *startSpecifier,
7179 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007180 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007181 FS.getConversionSpecifier();
Fangrui Song6907ce22018-07-30 19:24:48 +00007182
Ted Kremenekce815422010-07-19 21:25:57 +00007183 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7184 getLocationOfByte(CS.getStart()),
7185 startSpecifier, specifierLen,
7186 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00007187}
7188
Ted Kremenek02087932010-07-16 02:11:22 +00007189bool CheckPrintfHandler::HandleAmount(
7190 const analyze_format_string::OptionalAmount &Amt,
7191 unsigned k, const char *startSpecifier,
7192 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007193 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007194 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00007195 unsigned argIndex = Amt.getArgIndex();
7196 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007197 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7198 << k,
7199 getLocationOfByte(Amt.getStart()),
7200 /*IsStringLocation*/true,
7201 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007202 // Don't do any more checking. We will just emit
7203 // spurious errors.
7204 return false;
7205 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007206
Ted Kremenek5739de72010-01-29 01:06:55 +00007207 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00007208 // Although not in conformance with C99, we also allow the argument to be
7209 // an 'unsigned int' as that is a reasonably safe case. GCC also
7210 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00007211 CoveredArgs.set(argIndex);
7212 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007213 if (!Arg)
7214 return false;
7215
Ted Kremenek5739de72010-01-29 01:06:55 +00007216 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007217
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007218 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7219 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007220
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007221 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007222 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007223 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00007224 << T << Arg->getSourceRange(),
7225 getLocationOfByte(Amt.getStart()),
7226 /*IsStringLocation*/true,
7227 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00007228 // Don't do any more checking. We will just emit
7229 // spurious errors.
7230 return false;
7231 }
7232 }
7233 }
7234 return true;
7235}
Ted Kremenek5739de72010-01-29 01:06:55 +00007236
Tom Careb49ec692010-06-17 19:00:27 +00007237void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00007238 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007239 const analyze_printf::OptionalAmount &Amt,
7240 unsigned type,
7241 const char *startSpecifier,
7242 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007243 const analyze_printf::PrintfConversionSpecifier &CS =
7244 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00007245
Richard Trieu03cf7b72011-10-28 00:41:25 +00007246 FixItHint fixit =
7247 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7248 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7249 Amt.getConstantLength()))
7250 : FixItHint();
7251
7252 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7253 << type << CS.toString(),
7254 getLocationOfByte(Amt.getStart()),
7255 /*IsStringLocation*/true,
7256 getSpecifierRange(startSpecifier, specifierLen),
7257 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00007258}
7259
Ted Kremenek02087932010-07-16 02:11:22 +00007260void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007261 const analyze_printf::OptionalFlag &flag,
7262 const char *startSpecifier,
7263 unsigned specifierLen) {
7264 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007265 const analyze_printf::PrintfConversionSpecifier &CS =
7266 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00007267 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7268 << flag.toString() << CS.toString(),
7269 getLocationOfByte(flag.getPosition()),
7270 /*IsStringLocation*/true,
7271 getSpecifierRange(startSpecifier, specifierLen),
7272 FixItHint::CreateRemoval(
7273 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007274}
7275
7276void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00007277 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00007278 const analyze_printf::OptionalFlag &ignoredFlag,
7279 const analyze_printf::OptionalFlag &flag,
7280 const char *startSpecifier,
7281 unsigned specifierLen) {
7282 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00007283 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7284 << ignoredFlag.toString() << flag.toString(),
7285 getLocationOfByte(ignoredFlag.getPosition()),
7286 /*IsStringLocation*/true,
7287 getSpecifierRange(startSpecifier, specifierLen),
7288 FixItHint::CreateRemoval(
7289 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00007290}
7291
Ted Kremenek2b417712015-07-02 05:39:16 +00007292void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7293 unsigned flagLen) {
7294 // Warn about an empty flag.
7295 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7296 getLocationOfByte(startFlag),
7297 /*IsStringLocation*/true,
7298 getSpecifierRange(startFlag, flagLen));
7299}
7300
7301void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7302 unsigned flagLen) {
7303 // Warn about an invalid flag.
7304 auto Range = getSpecifierRange(startFlag, flagLen);
7305 StringRef flag(startFlag, flagLen);
7306 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7307 getLocationOfByte(startFlag),
7308 /*IsStringLocation*/true,
7309 Range, FixItHint::CreateRemoval(Range));
7310}
7311
7312void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7313 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7314 // Warn about using '[...]' without a '@' conversion.
7315 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7316 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7317 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7318 getLocationOfByte(conversionPosition),
7319 /*IsStringLocation*/true,
7320 Range, FixItHint::CreateRemoval(Range));
7321}
7322
Richard Smith55ce3522012-06-25 20:30:08 +00007323// Determines if the specified is a C++ class or struct containing
7324// a member with the specified name and kind (e.g. a CXXMethodDecl named
7325// "c_str()").
7326template<typename MemberKind>
7327static llvm::SmallPtrSet<MemberKind*, 1>
7328CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7329 const RecordType *RT = Ty->getAs<RecordType>();
7330 llvm::SmallPtrSet<MemberKind*, 1> Results;
7331
7332 if (!RT)
7333 return Results;
7334 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00007335 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00007336 return Results;
7337
Alp Tokerb6cc5922014-05-03 03:45:55 +00007338 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00007339 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00007340 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00007341
7342 // We just need to include all members of the right kind turned up by the
7343 // filter, at this point.
7344 if (S.LookupQualifiedName(R, RT->getDecl()))
7345 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7346 NamedDecl *decl = (*I)->getUnderlyingDecl();
7347 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7348 Results.insert(FK);
7349 }
7350 return Results;
7351}
7352
Richard Smith2868a732014-02-28 01:36:39 +00007353/// Check if we could call '.c_str()' on an object.
7354///
7355/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7356/// allow the call, or if it would be ambiguous).
7357bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007358 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7359
Richard Smith2868a732014-02-28 01:36:39 +00007360 MethodSet Results =
7361 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7362 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7363 MI != ME; ++MI)
7364 if ((*MI)->getMinRequiredArguments() == 0)
7365 return true;
7366 return false;
7367}
7368
Richard Smith55ce3522012-06-25 20:30:08 +00007369// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00007370// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00007371// Returns true when a c_str() conversion method is found.
7372bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00007373 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007374 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00007375
7376 MethodSet Results =
7377 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7378
7379 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7380 MI != ME; ++MI) {
7381 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00007382 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00007383 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00007384 // FIXME: Suggest parens if the expression needs them.
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007385 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007386 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7387 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
Richard Smith55ce3522012-06-25 20:30:08 +00007388 return true;
7389 }
7390 }
7391
7392 return false;
7393}
7394
Ted Kremenekab278de2010-01-28 23:39:18 +00007395bool
Ted Kremenek02087932010-07-16 02:11:22 +00007396CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00007397 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00007398 const char *startSpecifier,
7399 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007400 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007401 using namespace analyze_printf;
7402
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007403 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00007404
Ted Kremenek6cd69422010-07-19 22:01:06 +00007405 if (FS.consumesDataArgument()) {
7406 if (atFirstArg) {
7407 atFirstArg = false;
7408 usesPositionalArgs = FS.usesPositionalArg();
7409 }
7410 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007411 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7412 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007413 return false;
7414 }
Ted Kremenek5739de72010-01-29 01:06:55 +00007415 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007416
Ted Kremenekd1668192010-02-27 01:41:03 +00007417 // First check if the field width, precision, and conversion specifier
7418 // have matching data arguments.
7419 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7420 startSpecifier, specifierLen)) {
7421 return false;
7422 }
7423
7424 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7425 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00007426 return false;
7427 }
7428
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007429 if (!CS.consumesDataArgument()) {
7430 // FIXME: Technically specifying a precision or field width here
7431 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00007432 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00007433 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007434
Ted Kremenek4a49d982010-02-26 19:18:41 +00007435 // Consume the argument.
7436 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00007437 if (argIndex < NumDataArgs) {
7438 // The check to see if the argIndex is valid will come later.
7439 // We set the bit here because we may exit early from this
7440 // function if we encounter some other error.
7441 CoveredArgs.set(argIndex);
7442 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00007443
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007444 // FreeBSD kernel extensions.
7445 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7446 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7447 // We need at least two arguments.
7448 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7449 return false;
7450
7451 // Claim the second argument.
7452 CoveredArgs.set(argIndex + 1);
7453
7454 // Type check the first argument (int for %b, pointer for %D)
7455 const Expr *Ex = getDataArg(argIndex);
7456 const analyze_printf::ArgType &AT =
7457 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7458 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7459 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7460 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007461 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7462 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7463 << false << Ex->getSourceRange(),
7464 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7465 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007466
7467 // Type check the second argument (char * for both %b and %D)
7468 Ex = getDataArg(argIndex + 1);
7469 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7470 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7471 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007472 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7473 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7474 << false << Ex->getSourceRange(),
7475 Ex->getBeginLoc(), /*IsStringLocation*/ false,
7476 getSpecifierRange(startSpecifier, specifierLen));
Dimitry Andric6b5ed342015-02-19 22:32:33 +00007477
7478 return true;
7479 }
7480
Ted Kremenek4a49d982010-02-26 19:18:41 +00007481 // Check for using an Objective-C specific conversion specifier
7482 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00007483 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00007484 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7485 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00007486 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007487
Mehdi Amini06d367c2016-10-24 20:39:34 +00007488 // %P can only be used with os_log.
7489 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7490 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7491 specifierLen);
7492 }
7493
7494 // %n is not allowed with os_log.
7495 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7496 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7497 getLocationOfByte(CS.getStart()),
7498 /*IsStringLocation*/ false,
7499 getSpecifierRange(startSpecifier, specifierLen));
7500
7501 return true;
7502 }
7503
7504 // Only scalars are allowed for os_trace.
7505 if (FSType == Sema::FST_OSTrace &&
7506 (CS.getKind() == ConversionSpecifier::PArg ||
7507 CS.getKind() == ConversionSpecifier::sArg ||
7508 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7509 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7510 specifierLen);
7511 }
7512
7513 // Check for use of public/private annotation outside of os_log().
7514 if (FSType != Sema::FST_OSLog) {
7515 if (FS.isPublic().isSet()) {
7516 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7517 << "public",
7518 getLocationOfByte(FS.isPublic().getPosition()),
7519 /*IsStringLocation*/ false,
7520 getSpecifierRange(startSpecifier, specifierLen));
7521 }
7522 if (FS.isPrivate().isSet()) {
7523 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7524 << "private",
7525 getLocationOfByte(FS.isPrivate().getPosition()),
7526 /*IsStringLocation*/ false,
7527 getSpecifierRange(startSpecifier, specifierLen));
7528 }
7529 }
7530
Tom Careb49ec692010-06-17 19:00:27 +00007531 // Check for invalid use of field width
7532 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00007533 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00007534 startSpecifier, specifierLen);
7535 }
7536
7537 // Check for invalid use of precision
7538 if (!FS.hasValidPrecision()) {
7539 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7540 startSpecifier, specifierLen);
7541 }
7542
Mehdi Amini06d367c2016-10-24 20:39:34 +00007543 // Precision is mandatory for %P specifier.
7544 if (CS.getKind() == ConversionSpecifier::PArg &&
7545 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7546 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7547 getLocationOfByte(startSpecifier),
7548 /*IsStringLocation*/ false,
7549 getSpecifierRange(startSpecifier, specifierLen));
7550 }
7551
Tom Careb49ec692010-06-17 19:00:27 +00007552 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00007553 if (!FS.hasValidThousandsGroupingPrefix())
7554 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007555 if (!FS.hasValidLeadingZeros())
7556 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7557 if (!FS.hasValidPlusPrefix())
7558 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00007559 if (!FS.hasValidSpacePrefix())
7560 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007561 if (!FS.hasValidAlternativeForm())
7562 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7563 if (!FS.hasValidLeftJustified())
7564 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7565
7566 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00007567 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7568 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7569 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00007570 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7571 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7572 startSpecifier, specifierLen);
7573
7574 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00007575 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007576 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7577 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007578 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007579 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007580 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007581 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7582 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00007583
Jordan Rose92303592012-09-08 04:00:03 +00007584 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7585 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7586
Ted Kremenek9fcd8302010-01-29 01:43:31 +00007587 // The remaining checks depend on the data arguments.
7588 if (HasVAListArg)
7589 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007590
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007591 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00007592 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00007593
Jordan Rose58bbe422012-07-19 18:10:08 +00007594 const Expr *Arg = getDataArg(argIndex);
7595 if (!Arg)
7596 return true;
7597
7598 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00007599}
7600
Jordan Roseaee34382012-09-05 22:56:26 +00007601static bool requiresParensToAddCast(const Expr *E) {
7602 // FIXME: We should have a general way to reason about operator
7603 // precedence and whether parens are actually needed here.
7604 // Take care of a few common cases where they aren't.
7605 const Expr *Inside = E->IgnoreImpCasts();
7606 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7607 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7608
7609 switch (Inside->getStmtClass()) {
7610 case Stmt::ArraySubscriptExprClass:
7611 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007612 case Stmt::CharacterLiteralClass:
7613 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007614 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007615 case Stmt::FloatingLiteralClass:
7616 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007617 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007618 case Stmt::ObjCArrayLiteralClass:
7619 case Stmt::ObjCBoolLiteralExprClass:
7620 case Stmt::ObjCBoxedExprClass:
7621 case Stmt::ObjCDictionaryLiteralClass:
7622 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007623 case Stmt::ObjCIvarRefExprClass:
7624 case Stmt::ObjCMessageExprClass:
7625 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007626 case Stmt::ObjCStringLiteralClass:
7627 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007628 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00007629 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00007630 case Stmt::UnaryOperatorClass:
7631 return false;
7632 default:
7633 return true;
7634 }
7635}
7636
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007637static std::pair<QualType, StringRef>
7638shouldNotPrintDirectly(const ASTContext &Context,
7639 QualType IntendedTy,
7640 const Expr *E) {
7641 // Use a 'while' to peel off layers of typedefs.
7642 QualType TyTy = IntendedTy;
7643 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7644 StringRef Name = UserTy->getDecl()->getName();
7645 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00007646 .Case("CFIndex", Context.getNSIntegerType())
7647 .Case("NSInteger", Context.getNSIntegerType())
7648 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007649 .Case("SInt32", Context.IntTy)
7650 .Case("UInt32", Context.UnsignedIntTy)
7651 .Default(QualType());
7652
7653 if (!CastTy.isNull())
7654 return std::make_pair(CastTy, Name);
7655
7656 TyTy = UserTy->desugar();
7657 }
7658
7659 // Strip parens if necessary.
7660 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7661 return shouldNotPrintDirectly(Context,
7662 PE->getSubExpr()->getType(),
7663 PE->getSubExpr());
7664
7665 // If this is a conditional expression, then its result type is constructed
7666 // via usual arithmetic conversions and thus there might be no necessary
7667 // typedef sugar there. Recurse to operands to check for NSInteger &
7668 // Co. usage condition.
7669 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7670 QualType TrueTy, FalseTy;
7671 StringRef TrueName, FalseName;
7672
7673 std::tie(TrueTy, TrueName) =
7674 shouldNotPrintDirectly(Context,
7675 CO->getTrueExpr()->getType(),
7676 CO->getTrueExpr());
7677 std::tie(FalseTy, FalseName) =
7678 shouldNotPrintDirectly(Context,
7679 CO->getFalseExpr()->getType(),
7680 CO->getFalseExpr());
7681
7682 if (TrueTy == FalseTy)
7683 return std::make_pair(TrueTy, TrueName);
7684 else if (TrueTy.isNull())
7685 return std::make_pair(FalseTy, FalseName);
7686 else if (FalseTy.isNull())
7687 return std::make_pair(TrueTy, TrueName);
7688 }
7689
7690 return std::make_pair(QualType(), StringRef());
7691}
7692
Richard Smith55ce3522012-06-25 20:30:08 +00007693bool
7694CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7695 const char *StartSpecifier,
7696 unsigned SpecifierLen,
7697 const Expr *E) {
7698 using namespace analyze_format_string;
7699 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007700
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007701 // Now type check the data expression that matches the
7702 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00007703 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00007704 if (!AT.isValid())
7705 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00007706
Jordan Rose598ec092012-12-05 18:44:40 +00007707 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00007708 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7709 ExprTy = TET->getUnderlyingExpr()->getType();
7710 }
7711
JF Bastienec7d7f32018-06-22 21:54:40 +00007712 const analyze_printf::ArgType::MatchKind Match =
7713 AT.matchesType(S.Context, ExprTy);
7714 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7715 if (Match == analyze_printf::ArgType::Match)
Jordan Rose22b74712012-09-05 22:56:19 +00007716 return true;
Jordan Rose98709982012-06-04 22:48:57 +00007717
Jordan Rose22b74712012-09-05 22:56:19 +00007718 // Look through argument promotions for our error message's reported type.
7719 // This includes the integral and floating promotions, but excludes array
7720 // and function pointer decay; seeing that an argument intended to be a
7721 // string has type 'char [6]' is probably more confusing than 'char *'.
7722 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7723 if (ICE->getCastKind() == CK_IntegralCast ||
7724 ICE->getCastKind() == CK_FloatingCast) {
7725 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00007726 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00007727
7728 // Check if we didn't match because of an implicit cast from a 'char'
7729 // or 'short' to an 'int'. This is done because printf is a varargs
7730 // function.
7731 if (ICE->getType() == S.Context.IntTy ||
7732 ICE->getType() == S.Context.UnsignedIntTy) {
7733 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00007734 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00007735 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00007736 }
Jordan Rose98709982012-06-04 22:48:57 +00007737 }
Jordan Rose598ec092012-12-05 18:44:40 +00007738 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7739 // Special case for 'a', which has type 'int' in C.
7740 // Note, however, that we do /not/ want to treat multibyte constants like
7741 // 'MooV' as characters! This form is deprecated but still exists.
7742 if (ExprTy == S.Context.IntTy)
7743 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7744 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00007745 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007746
Jordan Rosebc53ed12014-05-31 04:12:14 +00007747 // Look through enums to their underlying type.
7748 bool IsEnum = false;
7749 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7750 ExprTy = EnumTy->getDecl()->getIntegerType();
7751 IsEnum = true;
7752 }
7753
Jordan Rose0e5badd2012-12-05 18:44:49 +00007754 // %C in an Objective-C context prints a unichar, not a wchar_t.
7755 // If the argument is an integer of some kind, believe the %C and suggest
7756 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00007757 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00007758 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00007759 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7760 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7761 !ExprTy->isCharType()) {
7762 // 'unichar' is defined as a typedef of unsigned short, but we should
7763 // prefer using the typedef if it is visible.
7764 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00007765
7766 // While we are here, check if the value is an IntegerLiteral that happens
7767 // to be within the valid range.
7768 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7769 const llvm::APInt &V = IL->getValue();
7770 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7771 return true;
7772 }
7773
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007774 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
Jordan Rose0e5badd2012-12-05 18:44:49 +00007775 Sema::LookupOrdinaryName);
7776 if (S.LookupName(Result, S.getCurScope())) {
7777 NamedDecl *ND = Result.getFoundDecl();
7778 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7779 if (TD->getUnderlyingType() == IntendedTy)
7780 IntendedTy = S.Context.getTypedefType(TD);
7781 }
7782 }
7783 }
7784
7785 // Special-case some of Darwin's platform-independence types by suggesting
7786 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007787 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00007788 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007789 QualType CastTy;
7790 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7791 if (!CastTy.isNull()) {
Alex Lorenzb2043ac2018-07-05 22:51:11 +00007792 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
JF Bastienec7d7f32018-06-22 21:54:40 +00007793 // (long in ASTContext). Only complain to pedants.
7794 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
Alex Lorenzb2043ac2018-07-05 22:51:11 +00007795 (AT.isSizeT() || AT.isPtrdiffT()) &&
7796 AT.matchesType(S.Context, CastTy))
JF Bastienec7d7f32018-06-22 21:54:40 +00007797 Pedantic = true;
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007798 IntendedTy = CastTy;
7799 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00007800 }
7801 }
7802
Jordan Rose22b74712012-09-05 22:56:19 +00007803 // We may be able to offer a FixItHint if it is a supported type.
7804 PrintfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00007805 bool Success =
Mehdi Amini06d367c2016-10-24 20:39:34 +00007806 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007807
JF Bastienec7d7f32018-06-22 21:54:40 +00007808 if (Success) {
Jordan Rose22b74712012-09-05 22:56:19 +00007809 // Get the fix string from the fixed format specifier
7810 SmallString<16> buf;
7811 llvm::raw_svector_ostream os(buf);
7812 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007813
Jordan Roseaee34382012-09-05 22:56:26 +00007814 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7815
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007816 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
JF Bastienec7d7f32018-06-22 21:54:40 +00007817 unsigned Diag =
7818 Pedantic
7819 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7820 : diag::warn_format_conversion_argument_type_mismatch;
Jordan Rose0e5badd2012-12-05 18:44:49 +00007821 // In this case, the specifier is wrong and should be changed to match
7822 // the argument.
JF Bastienec7d7f32018-06-22 21:54:40 +00007823 EmitFormatDiagnostic(S.PDiag(Diag)
Daniel Jasperad8d8492015-03-04 14:18:20 +00007824 << AT.getRepresentativeTypeName(S.Context)
7825 << IntendedTy << IsEnum << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007826 E->getBeginLoc(),
Daniel Jasperad8d8492015-03-04 14:18:20 +00007827 /*IsStringLocation*/ false, SpecRange,
7828 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00007829 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00007830 // The canonical type for formatting this value is different from the
7831 // actual type of the expression. (This occurs, for example, with Darwin's
7832 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7833 // should be printed as 'long' for 64-bit compatibility.)
7834 // Rather than emitting a normal format/argument mismatch, we want to
7835 // add a cast to the recommended type (and correct the format string
7836 // if necessary).
7837 SmallString<16> CastBuf;
7838 llvm::raw_svector_ostream CastFix(CastBuf);
7839 CastFix << "(";
7840 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7841 CastFix << ")";
7842
7843 SmallVector<FixItHint,4> Hints;
Fangrui Song6907ce22018-07-30 19:24:48 +00007844 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00007845 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7846
7847 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7848 // If there's already a cast present, just replace it.
7849 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7850 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7851
7852 } else if (!requiresParensToAddCast(E)) {
7853 // If the expression has high enough precedence,
7854 // just write the C-style cast.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007855 Hints.push_back(
7856 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00007857 } else {
7858 // Otherwise, add parens around the expression as well as the cast.
7859 CastFix << "(";
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007860 Hints.push_back(
7861 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
Jordan Roseaee34382012-09-05 22:56:26 +00007862
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007863 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
Jordan Roseaee34382012-09-05 22:56:26 +00007864 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7865 }
7866
Jordan Rose0e5badd2012-12-05 18:44:49 +00007867 if (ShouldNotPrintDirectly) {
7868 // The expression has a type that should not be printed directly.
7869 // We extract the name from the typedef because we don't want to show
7870 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00007871 StringRef Name;
7872 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
7873 Name = TypedefTy->getDecl()->getName();
7874 else
7875 Name = CastTyName;
JF Bastienec7d7f32018-06-22 21:54:40 +00007876 unsigned Diag = Pedantic
7877 ? diag::warn_format_argument_needs_cast_pedantic
7878 : diag::warn_format_argument_needs_cast;
7879 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7880 << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007881 E->getBeginLoc(), /*IsStringLocation=*/false,
Jordan Rose0e5badd2012-12-05 18:44:49 +00007882 SpecRange, Hints);
7883 } else {
7884 // In this case, the expression could be printed using a different
Fangrui Song6907ce22018-07-30 19:24:48 +00007885 // specifier, but we've decided that the specifier is probably correct
Jordan Rose0e5badd2012-12-05 18:44:49 +00007886 // and we should cast instead. Just use the normal warning message.
7887 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007888 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7889 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
7890 << E->getSourceRange(),
7891 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
Jordan Rose0e5badd2012-12-05 18:44:49 +00007892 }
Jordan Roseaee34382012-09-05 22:56:26 +00007893 }
Jordan Rose22b74712012-09-05 22:56:19 +00007894 } else {
7895 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
7896 SpecifierLen);
7897 // Since the warning for passing non-POD types to variadic functions
7898 // was deferred until now, we emit a warning for non-POD
7899 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00007900 switch (S.isValidVarArgType(ExprTy)) {
7901 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00007902 case Sema::VAK_ValidInCXX11: {
JF Bastienec7d7f32018-06-22 21:54:40 +00007903 unsigned Diag =
7904 Pedantic
7905 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7906 : diag::warn_format_conversion_argument_type_mismatch;
Richard Smithd7293d72013-08-05 18:49:43 +00007907
Seth Cantrellb4802962015-03-04 03:12:10 +00007908 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00007909 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
Seth Cantrellb4802962015-03-04 03:12:10 +00007910 << IsEnum << CSR << E->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007911 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Seth Cantrellb4802962015-03-04 03:12:10 +00007912 break;
7913 }
Richard Smithd7293d72013-08-05 18:49:43 +00007914 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00007915 case Sema::VAK_MSVCUndefined:
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007916 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7917 << S.getLangOpts().CPlusPlus11 << ExprTy
7918 << CallType
7919 << AT.getRepresentativeTypeName(S.Context) << CSR
7920 << E->getSourceRange(),
7921 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00007922 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00007923 break;
7924
7925 case Sema::VAK_Invalid:
7926 if (ExprTy->isObjCObjectType())
7927 EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007928 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7929 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7930 << AT.getRepresentativeTypeName(S.Context) << CSR
7931 << E->getSourceRange(),
7932 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00007933 else
7934 // FIXME: If this is an initializer list, suggest removing the braces
7935 // or inserting a cast to the target type.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007936 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
7937 << isa<InitListExpr>(E) << ExprTy << CallType
7938 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
Richard Smithd7293d72013-08-05 18:49:43 +00007939 break;
7940 }
7941
7942 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7943 "format string specifier index out of range");
7944 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007945 }
7946
Ted Kremenekab278de2010-01-28 23:39:18 +00007947 return true;
7948}
7949
Ted Kremenek02087932010-07-16 02:11:22 +00007950//===--- CHECK: Scanf format string checking ------------------------------===//
7951
Fangrui Song6907ce22018-07-30 19:24:48 +00007952namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007953
Ted Kremenek02087932010-07-16 02:11:22 +00007954class CheckScanfHandler : public CheckFormatHandler {
7955public:
Stephen Hines648c3692016-09-16 01:07:04 +00007956 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007957 const Expr *origFormatExpr, Sema::FormatStringType type,
7958 unsigned firstDataArg, unsigned numDataArgs,
7959 const char *beg, bool hasVAListArg,
7960 ArrayRef<const Expr *> Args, unsigned formatIdx,
7961 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007962 llvm::SmallBitVector &CheckedVarArgs,
7963 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007964 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7965 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7966 inFunctionCall, CallType, CheckedVarArgs,
7967 UncoveredArg) {}
7968
Ted Kremenek02087932010-07-16 02:11:22 +00007969 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7970 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007971 unsigned specifierLen) override;
Fangrui Song6907ce22018-07-30 19:24:48 +00007972
Ted Kremenekce815422010-07-19 21:25:57 +00007973 bool HandleInvalidScanfConversionSpecifier(
7974 const analyze_scanf::ScanfSpecifier &FS,
7975 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007976 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007977
Craig Toppere14c0f82014-03-12 04:55:44 +00007978 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00007979};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007980
7981} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00007982
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007983void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7984 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007985 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7986 getLocationOfByte(end), /*IsStringLocation*/true,
7987 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007988}
7989
Ted Kremenekce815422010-07-19 21:25:57 +00007990bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7991 const analyze_scanf::ScanfSpecifier &FS,
7992 const char *startSpecifier,
7993 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007994 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007995 FS.getConversionSpecifier();
7996
7997 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7998 getLocationOfByte(CS.getStart()),
7999 startSpecifier, specifierLen,
8000 CS.getStart(), CS.getLength());
8001}
8002
Ted Kremenek02087932010-07-16 02:11:22 +00008003bool CheckScanfHandler::HandleScanfSpecifier(
8004 const analyze_scanf::ScanfSpecifier &FS,
8005 const char *startSpecifier,
8006 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00008007 using namespace analyze_scanf;
Fangrui Song6907ce22018-07-30 19:24:48 +00008008 using namespace analyze_format_string;
Ted Kremenek02087932010-07-16 02:11:22 +00008009
Ted Kremenekf03e6d852010-07-20 20:04:27 +00008010 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00008011
Ted Kremenek6cd69422010-07-19 22:01:06 +00008012 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8013 // be used to decide if we are using positional arguments consistently.
8014 if (FS.consumesDataArgument()) {
8015 if (atFirstArg) {
8016 atFirstArg = false;
8017 usesPositionalArgs = FS.usesPositionalArg();
8018 }
8019 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008020 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8021 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00008022 return false;
8023 }
Ted Kremenek02087932010-07-16 02:11:22 +00008024 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008025
Ted Kremenek02087932010-07-16 02:11:22 +00008026 // Check if the field with is non-zero.
8027 const OptionalAmount &Amt = FS.getFieldWidth();
8028 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8029 if (Amt.getConstantAmount() == 0) {
8030 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8031 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00008032 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8033 getLocationOfByte(Amt.getStart()),
8034 /*IsStringLocation*/true, R,
8035 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00008036 }
8037 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008038
Ted Kremenek02087932010-07-16 02:11:22 +00008039 if (!FS.consumesDataArgument()) {
8040 // FIXME: Technically specifying a precision or field width here
8041 // makes no sense. Worth issuing a warning at some point.
8042 return true;
8043 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008044
Ted Kremenek02087932010-07-16 02:11:22 +00008045 // Consume the argument.
8046 unsigned argIndex = FS.getArgIndex();
8047 if (argIndex < NumDataArgs) {
8048 // The check to see if the argIndex is valid will come later.
8049 // We set the bit here because we may exit early from this
8050 // function if we encounter some other error.
8051 CoveredArgs.set(argIndex);
8052 }
Seth Cantrellb4802962015-03-04 03:12:10 +00008053
Ted Kremenek4407ea42010-07-20 20:04:47 +00008054 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00008055 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00008056 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8057 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00008058 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008059 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00008060 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00008061 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8062 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00008063
Jordan Rose92303592012-09-08 04:00:03 +00008064 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8065 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8066
Ted Kremenek02087932010-07-16 02:11:22 +00008067 // The remaining checks depend on the data arguments.
8068 if (HasVAListArg)
8069 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008070
Ted Kremenek6adb7e32010-07-26 19:45:42 +00008071 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00008072 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00008073
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008074 // Check that the argument type matches the format specifier.
8075 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00008076 if (!Ex)
8077 return true;
8078
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00008079 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00008080
8081 if (!AT.isValid()) {
8082 return true;
8083 }
8084
JF Bastienec7d7f32018-06-22 21:54:40 +00008085 analyze_format_string::ArgType::MatchKind Match =
Seth Cantrellb4802962015-03-04 03:12:10 +00008086 AT.matchesType(S.Context, Ex->getType());
JF Bastienec7d7f32018-06-22 21:54:40 +00008087 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8088 if (Match == analyze_format_string::ArgType::Match)
Seth Cantrell79340072015-03-04 05:58:08 +00008089 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00008090
Seth Cantrell79340072015-03-04 05:58:08 +00008091 ScanfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00008092 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
Seth Cantrell79340072015-03-04 05:58:08 +00008093 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008094
JF Bastienec7d7f32018-06-22 21:54:40 +00008095 unsigned Diag =
8096 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8097 : diag::warn_format_conversion_argument_type_mismatch;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008098
JF Bastienec7d7f32018-06-22 21:54:40 +00008099 if (Success) {
Seth Cantrell79340072015-03-04 05:58:08 +00008100 // Get the fix string from the fixed format specifier.
8101 SmallString<128> buf;
8102 llvm::raw_svector_ostream os(buf);
8103 fixedFS.toString(os);
8104
8105 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00008106 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
Seth Cantrell79340072015-03-04 05:58:08 +00008107 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008108 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008109 /*IsStringLocation*/ false,
8110 getSpecifierRange(startSpecifier, specifierLen),
8111 FixItHint::CreateReplacement(
8112 getSpecifierRange(startSpecifier, specifierLen), os.str()));
8113 } else {
JF Bastienec7d7f32018-06-22 21:54:40 +00008114 EmitFormatDiagnostic(S.PDiag(Diag)
Seth Cantrell79340072015-03-04 05:58:08 +00008115 << AT.getRepresentativeTypeName(S.Context)
8116 << Ex->getType() << false << Ex->getSourceRange(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008117 Ex->getBeginLoc(),
Seth Cantrell79340072015-03-04 05:58:08 +00008118 /*IsStringLocation*/ false,
8119 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00008120 }
8121
Ted Kremenek02087932010-07-16 02:11:22 +00008122 return true;
8123}
8124
Stephen Hines648c3692016-09-16 01:07:04 +00008125static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008126 const Expr *OrigFormatExpr,
8127 ArrayRef<const Expr *> Args,
8128 bool HasVAListArg, unsigned format_idx,
8129 unsigned firstDataArg,
8130 Sema::FormatStringType Type,
8131 bool inFunctionCall,
8132 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00008133 llvm::SmallBitVector &CheckedVarArgs,
8134 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00008135 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00008136 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008137 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008138 S, inFunctionCall, Args[format_idx],
8139 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8140 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008141 return;
8142 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008143
Ted Kremenekab278de2010-01-28 23:39:18 +00008144 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008145 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00008146 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008147 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008148 const ConstantArrayType *T =
8149 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008150 assert(T && "String literal not of constant array type!");
8151 size_t TypeSize = T->getSize().getZExtValue();
8152 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00008153 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008154
8155 // Emit a warning if the string literal is truncated and does not contain an
8156 // embedded null character.
8157 if (TypeSize <= StrRef.size() &&
8158 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8159 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008160 S, inFunctionCall, Args[format_idx],
8161 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008162 FExpr->getBeginLoc(),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00008163 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8164 return;
8165 }
8166
Ted Kremenekab278de2010-01-28 23:39:18 +00008167 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00008168 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00008169 CheckFormatHandler::EmitFormatDiagnostic(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008170 S, inFunctionCall, Args[format_idx],
8171 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8172 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00008173 return;
8174 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008175
8176 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00008177 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8178 Type == Sema::FST_OSTrace) {
8179 CheckPrintfHandler H(
8180 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8181 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8182 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8183 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008184
Hans Wennborg23926bd2011-12-15 10:25:47 +00008185 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008186 S.getLangOpts(),
8187 S.Context.getTargetInfo(),
8188 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00008189 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008190 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00008191 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8192 numDataArgs, Str, HasVAListArg, Args, format_idx,
8193 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008194
Hans Wennborg23926bd2011-12-15 10:25:47 +00008195 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00008196 S.getLangOpts(),
8197 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00008198 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00008199 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00008200}
8201
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00008202bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8203 // Str - The format string. NOTE: this is NOT null-terminated!
8204 StringRef StrRef = FExpr->getString();
8205 const char *Str = StrRef.data();
8206 // Account for cases where the string literal is truncated in a declaration.
8207 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8208 assert(T && "String literal not of constant array type!");
8209 size_t TypeSize = T->getSize().getZExtValue();
8210 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8211 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8212 getLangOpts(),
8213 Context.getTargetInfo());
8214}
8215
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008216//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8217
8218// Returns the related absolute value function that is larger, of 0 if one
8219// does not exist.
8220static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8221 switch (AbsFunction) {
8222 default:
8223 return 0;
8224
8225 case Builtin::BI__builtin_abs:
8226 return Builtin::BI__builtin_labs;
8227 case Builtin::BI__builtin_labs:
8228 return Builtin::BI__builtin_llabs;
8229 case Builtin::BI__builtin_llabs:
8230 return 0;
8231
8232 case Builtin::BI__builtin_fabsf:
8233 return Builtin::BI__builtin_fabs;
8234 case Builtin::BI__builtin_fabs:
8235 return Builtin::BI__builtin_fabsl;
8236 case Builtin::BI__builtin_fabsl:
8237 return 0;
8238
8239 case Builtin::BI__builtin_cabsf:
8240 return Builtin::BI__builtin_cabs;
8241 case Builtin::BI__builtin_cabs:
8242 return Builtin::BI__builtin_cabsl;
8243 case Builtin::BI__builtin_cabsl:
8244 return 0;
8245
8246 case Builtin::BIabs:
8247 return Builtin::BIlabs;
8248 case Builtin::BIlabs:
8249 return Builtin::BIllabs;
8250 case Builtin::BIllabs:
8251 return 0;
8252
8253 case Builtin::BIfabsf:
8254 return Builtin::BIfabs;
8255 case Builtin::BIfabs:
8256 return Builtin::BIfabsl;
8257 case Builtin::BIfabsl:
8258 return 0;
8259
8260 case Builtin::BIcabsf:
8261 return Builtin::BIcabs;
8262 case Builtin::BIcabs:
8263 return Builtin::BIcabsl;
8264 case Builtin::BIcabsl:
8265 return 0;
8266 }
8267}
8268
8269// Returns the argument type of the absolute value function.
8270static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8271 unsigned AbsType) {
8272 if (AbsType == 0)
8273 return QualType();
8274
8275 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8276 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8277 if (Error != ASTContext::GE_None)
8278 return QualType();
8279
8280 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8281 if (!FT)
8282 return QualType();
8283
8284 if (FT->getNumParams() != 1)
8285 return QualType();
8286
8287 return FT->getParamType(0);
8288}
8289
8290// Returns the best absolute value function, or zero, based on type and
8291// current absolute value function.
8292static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8293 unsigned AbsFunctionKind) {
8294 unsigned BestKind = 0;
8295 uint64_t ArgSize = Context.getTypeSize(ArgType);
8296 for (unsigned Kind = AbsFunctionKind; Kind != 0;
8297 Kind = getLargerAbsoluteValueFunction(Kind)) {
8298 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8299 if (Context.getTypeSize(ParamType) >= ArgSize) {
8300 if (BestKind == 0)
8301 BestKind = Kind;
8302 else if (Context.hasSameType(ParamType, ArgType)) {
8303 BestKind = Kind;
8304 break;
8305 }
8306 }
8307 }
8308 return BestKind;
8309}
8310
8311enum AbsoluteValueKind {
8312 AVK_Integer,
8313 AVK_Floating,
8314 AVK_Complex
8315};
8316
8317static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8318 if (T->isIntegralOrEnumerationType())
8319 return AVK_Integer;
8320 if (T->isRealFloatingType())
8321 return AVK_Floating;
8322 if (T->isAnyComplexType())
8323 return AVK_Complex;
8324
8325 llvm_unreachable("Type not integer, floating, or complex");
8326}
8327
8328// Changes the absolute value function to a different type. Preserves whether
8329// the function is a builtin.
8330static unsigned changeAbsFunction(unsigned AbsKind,
8331 AbsoluteValueKind ValueKind) {
8332 switch (ValueKind) {
8333 case AVK_Integer:
8334 switch (AbsKind) {
8335 default:
8336 return 0;
8337 case Builtin::BI__builtin_fabsf:
8338 case Builtin::BI__builtin_fabs:
8339 case Builtin::BI__builtin_fabsl:
8340 case Builtin::BI__builtin_cabsf:
8341 case Builtin::BI__builtin_cabs:
8342 case Builtin::BI__builtin_cabsl:
8343 return Builtin::BI__builtin_abs;
8344 case Builtin::BIfabsf:
8345 case Builtin::BIfabs:
8346 case Builtin::BIfabsl:
8347 case Builtin::BIcabsf:
8348 case Builtin::BIcabs:
8349 case Builtin::BIcabsl:
8350 return Builtin::BIabs;
8351 }
8352 case AVK_Floating:
8353 switch (AbsKind) {
8354 default:
8355 return 0;
8356 case Builtin::BI__builtin_abs:
8357 case Builtin::BI__builtin_labs:
8358 case Builtin::BI__builtin_llabs:
8359 case Builtin::BI__builtin_cabsf:
8360 case Builtin::BI__builtin_cabs:
8361 case Builtin::BI__builtin_cabsl:
8362 return Builtin::BI__builtin_fabsf;
8363 case Builtin::BIabs:
8364 case Builtin::BIlabs:
8365 case Builtin::BIllabs:
8366 case Builtin::BIcabsf:
8367 case Builtin::BIcabs:
8368 case Builtin::BIcabsl:
8369 return Builtin::BIfabsf;
8370 }
8371 case AVK_Complex:
8372 switch (AbsKind) {
8373 default:
8374 return 0;
8375 case Builtin::BI__builtin_abs:
8376 case Builtin::BI__builtin_labs:
8377 case Builtin::BI__builtin_llabs:
8378 case Builtin::BI__builtin_fabsf:
8379 case Builtin::BI__builtin_fabs:
8380 case Builtin::BI__builtin_fabsl:
8381 return Builtin::BI__builtin_cabsf;
8382 case Builtin::BIabs:
8383 case Builtin::BIlabs:
8384 case Builtin::BIllabs:
8385 case Builtin::BIfabsf:
8386 case Builtin::BIfabs:
8387 case Builtin::BIfabsl:
8388 return Builtin::BIcabsf;
8389 }
8390 }
8391 llvm_unreachable("Unable to convert function");
8392}
8393
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00008394static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008395 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8396 if (!FnInfo)
8397 return 0;
8398
8399 switch (FDecl->getBuiltinID()) {
8400 default:
8401 return 0;
8402 case Builtin::BI__builtin_abs:
8403 case Builtin::BI__builtin_fabs:
8404 case Builtin::BI__builtin_fabsf:
8405 case Builtin::BI__builtin_fabsl:
8406 case Builtin::BI__builtin_labs:
8407 case Builtin::BI__builtin_llabs:
8408 case Builtin::BI__builtin_cabs:
8409 case Builtin::BI__builtin_cabsf:
8410 case Builtin::BI__builtin_cabsl:
8411 case Builtin::BIabs:
8412 case Builtin::BIlabs:
8413 case Builtin::BIllabs:
8414 case Builtin::BIfabs:
8415 case Builtin::BIfabsf:
8416 case Builtin::BIfabsl:
8417 case Builtin::BIcabs:
8418 case Builtin::BIcabsf:
8419 case Builtin::BIcabsl:
8420 return FDecl->getBuiltinID();
8421 }
8422 llvm_unreachable("Unknown Builtin type");
8423}
8424
8425// If the replacement is valid, emit a note with replacement function.
8426// Additionally, suggest including the proper header if not already included.
8427static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00008428 unsigned AbsKind, QualType ArgType) {
8429 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00008430 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00008431 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00008432 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8433 FunctionName = "std::abs";
8434 if (ArgType->isIntegralOrEnumerationType()) {
8435 HeaderName = "cstdlib";
8436 } else if (ArgType->isRealFloatingType()) {
8437 HeaderName = "cmath";
8438 } else {
8439 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008440 }
Richard Trieubeffb832014-04-15 23:47:53 +00008441
8442 // Lookup all std::abs
8443 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00008444 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00008445 R.suppressDiagnostics();
8446 S.LookupQualifiedName(R, Std);
8447
8448 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008449 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00008450 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8451 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8452 } else {
8453 FDecl = dyn_cast<FunctionDecl>(I);
8454 }
8455 if (!FDecl)
8456 continue;
8457
8458 // Found std::abs(), check that they are the right ones.
8459 if (FDecl->getNumParams() != 1)
8460 continue;
8461
8462 // Check that the parameter type can handle the argument.
8463 QualType ParamType = FDecl->getParamDecl(0)->getType();
8464 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8465 S.Context.getTypeSize(ArgType) <=
8466 S.Context.getTypeSize(ParamType)) {
8467 // Found a function, don't need the header hint.
8468 EmitHeaderHint = false;
8469 break;
8470 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008471 }
Richard Trieubeffb832014-04-15 23:47:53 +00008472 }
8473 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00008474 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00008475 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8476
8477 if (HeaderName) {
8478 DeclarationName DN(&S.Context.Idents.get(FunctionName));
8479 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8480 R.suppressDiagnostics();
8481 S.LookupName(R, S.getCurScope());
8482
8483 if (R.isSingleResult()) {
8484 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8485 if (FD && FD->getBuiltinID() == AbsKind) {
8486 EmitHeaderHint = false;
8487 } else {
8488 return;
8489 }
8490 } else if (!R.empty()) {
8491 return;
8492 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008493 }
8494 }
8495
8496 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00008497 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008498
Richard Trieubeffb832014-04-15 23:47:53 +00008499 if (!HeaderName)
8500 return;
8501
8502 if (!EmitHeaderHint)
8503 return;
8504
Alp Toker5d96e0a2014-07-11 20:53:51 +00008505 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8506 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00008507}
8508
Richard Trieua7f30b12016-12-06 01:42:28 +00008509template <std::size_t StrLen>
8510static bool IsStdFunction(const FunctionDecl *FDecl,
8511 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00008512 if (!FDecl)
8513 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00008514 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00008515 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00008516 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00008517 return false;
8518
8519 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008520}
8521
8522// Warn when using the wrong abs() function.
8523void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00008524 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008525 if (Call->getNumArgs() != 1)
8526 return;
8527
8528 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00008529 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00008530 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008531 return;
8532
8533 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8534 QualType ParamType = Call->getArg(0)->getType();
8535
Alp Toker5d96e0a2014-07-11 20:53:51 +00008536 // Unsigned types cannot be negative. Suggest removing the absolute value
8537 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008538 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00008539 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00008540 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008541 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8542 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00008543 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008544 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8545 return;
8546 }
8547
David Majnemer7f77eb92015-11-15 03:04:34 +00008548 // Taking the absolute value of a pointer is very suspicious, they probably
8549 // wanted to index into an array, dereference a pointer, call a function, etc.
8550 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8551 unsigned DiagType = 0;
8552 if (ArgType->isFunctionType())
8553 DiagType = 1;
8554 else if (ArgType->isArrayType())
8555 DiagType = 2;
8556
8557 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8558 return;
8559 }
8560
Richard Trieubeffb832014-04-15 23:47:53 +00008561 // std::abs has overloads which prevent most of the absolute value problems
8562 // from occurring.
8563 if (IsStdAbs)
8564 return;
8565
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008566 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8567 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8568
8569 // The argument and parameter are the same kind. Check if they are the right
8570 // size.
8571 if (ArgValueKind == ParamValueKind) {
8572 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8573 return;
8574
8575 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8576 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8577 << FDecl << ArgType << ParamType;
8578
8579 if (NewAbsKind == 0)
8580 return;
8581
8582 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00008583 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008584 return;
8585 }
8586
8587 // ArgValueKind != ParamValueKind
8588 // The wrong type of absolute value function was used. Attempt to find the
8589 // proper one.
8590 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8591 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8592 if (NewAbsKind == 0)
8593 return;
8594
8595 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8596 << FDecl << ParamValueKind << ArgValueKind;
8597
8598 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00008599 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008600}
8601
Richard Trieu67c00712016-12-05 23:41:46 +00008602//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00008603void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8604 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00008605 if (!Call || !FDecl) return;
8606
8607 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00008608 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00008609 if (Call->getExprLoc().isMacroID()) return;
8610
8611 // Only care about the one template argument, two function parameter std::max
8612 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00008613 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00008614 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8615 if (!ArgList) return;
8616 if (ArgList->size() != 1) return;
8617
8618 // Check that template type argument is unsigned integer.
8619 const auto& TA = ArgList->get(0);
8620 if (TA.getKind() != TemplateArgument::Type) return;
8621 QualType ArgType = TA.getAsType();
8622 if (!ArgType->isUnsignedIntegerType()) return;
8623
8624 // See if either argument is a literal zero.
8625 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8626 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8627 if (!MTE) return false;
8628 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8629 if (!Num) return false;
8630 if (Num->getValue() != 0) return false;
8631 return true;
8632 };
8633
8634 const Expr *FirstArg = Call->getArg(0);
8635 const Expr *SecondArg = Call->getArg(1);
8636 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8637 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8638
8639 // Only warn when exactly one argument is zero.
8640 if (IsFirstArgZero == IsSecondArgZero) return;
8641
8642 SourceRange FirstRange = FirstArg->getSourceRange();
8643 SourceRange SecondRange = SecondArg->getSourceRange();
8644
8645 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8646
8647 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8648 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8649
8650 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8651 SourceRange RemovalRange;
8652 if (IsFirstArgZero) {
8653 RemovalRange = SourceRange(FirstRange.getBegin(),
8654 SecondRange.getBegin().getLocWithOffset(-1));
8655 } else {
8656 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8657 SecondRange.getEnd());
8658 }
8659
8660 Diag(Call->getExprLoc(), diag::note_remove_max_call)
8661 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8662 << FixItHint::CreateRemoval(RemovalRange);
8663}
8664
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008665//===--- CHECK: Standard memory functions ---------------------------------===//
8666
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008667/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00008668/// such as memcmp, strncat, etc and warns if it's a comparison.
8669///
8670/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8671static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8672 IdentifierInfo *FnName,
8673 SourceLocation FnLoc,
8674 SourceLocation RParenLoc) {
8675 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8676 if (!Size)
8677 return false;
8678
Richard Smithc70f1d62017-12-14 15:16:18 +00008679 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8680 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00008681 return false;
8682
Nico Weber0e6daef2013-12-26 23:38:39 +00008683 SourceRange SizeRange = Size->getSourceRange();
8684 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8685 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00008686 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008687 << FnName
8688 << FixItHint::CreateInsertion(
8689 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00008690 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00008691 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00008692 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00008693 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8694 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00008695
8696 return true;
8697}
8698
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008699/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00008700/// (e.g., whether it has a vtable).
8701static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8702 bool &IsContained) {
8703 // Look through array types while ignoring qualifiers.
8704 const Type *Ty = T->getBaseElementTypeUnsafe();
8705 IsContained = false;
8706
8707 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8708 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00008709 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00008710 return nullptr;
8711
8712 if (RD->isDynamicClass())
8713 return RD;
8714
8715 // Check all the fields. If any bases were dynamic, the class is dynamic.
8716 // It's impossible for a class to transitively contain itself by value, so
8717 // infinite recursion is impossible.
8718 for (auto *FD : RD->fields()) {
8719 bool SubContained;
8720 if (const CXXRecordDecl *ContainedRD =
8721 getContainedDynamicClass(FD->getType(), SubContained)) {
8722 IsContained = true;
8723 return ContainedRD;
8724 }
8725 }
8726
8727 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00008728}
8729
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008730static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8731 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8732 if (Unary->getKind() == UETT_SizeOf)
8733 return Unary;
8734 return nullptr;
8735}
8736
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008737/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008738/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00008739static const Expr *getSizeOfExprArg(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008740 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8741 if (!SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008742 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Craig Topperc3ec1492014-05-26 06:22:03 +00008743 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008744}
8745
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008746/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00008747static QualType getSizeOfArgType(const Expr *E) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008748 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8749 return SizeOf->getTypeOfArgument();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008750 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00008751}
8752
Akira Hatanaka2be04412018-04-17 19:13:41 +00008753namespace {
8754
8755struct SearchNonTrivialToInitializeField
8756 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8757 using Super =
8758 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8759
8760 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8761
8762 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8763 SourceLocation SL) {
8764 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8765 asDerived().visitArray(PDIK, AT, SL);
8766 return;
8767 }
8768
8769 Super::visitWithKind(PDIK, FT, SL);
8770 }
8771
8772 void visitARCStrong(QualType FT, SourceLocation SL) {
8773 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8774 }
8775 void visitARCWeak(QualType FT, SourceLocation SL) {
8776 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8777 }
8778 void visitStruct(QualType FT, SourceLocation SL) {
8779 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8780 visit(FD->getType(), FD->getLocation());
8781 }
8782 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8783 const ArrayType *AT, SourceLocation SL) {
8784 visit(getContext().getBaseElementType(AT), SL);
8785 }
8786 void visitTrivial(QualType FT, SourceLocation SL) {}
8787
8788 static void diag(QualType RT, const Expr *E, Sema &S) {
8789 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8790 }
8791
8792 ASTContext &getContext() { return S.getASTContext(); }
8793
8794 const Expr *E;
8795 Sema &S;
8796};
8797
8798struct SearchNonTrivialToCopyField
8799 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8800 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8801
8802 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8803
8804 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8805 SourceLocation SL) {
8806 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8807 asDerived().visitArray(PCK, AT, SL);
8808 return;
8809 }
8810
8811 Super::visitWithKind(PCK, FT, SL);
8812 }
8813
8814 void visitARCStrong(QualType FT, SourceLocation SL) {
8815 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8816 }
8817 void visitARCWeak(QualType FT, SourceLocation SL) {
8818 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8819 }
8820 void visitStruct(QualType FT, SourceLocation SL) {
8821 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8822 visit(FD->getType(), FD->getLocation());
8823 }
8824 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8825 SourceLocation SL) {
8826 visit(getContext().getBaseElementType(AT), SL);
8827 }
8828 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8829 SourceLocation SL) {}
8830 void visitTrivial(QualType FT, SourceLocation SL) {}
8831 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8832
8833 static void diag(QualType RT, const Expr *E, Sema &S) {
8834 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8835 }
8836
8837 ASTContext &getContext() { return S.getASTContext(); }
8838
8839 const Expr *E;
8840 Sema &S;
8841};
8842
8843}
8844
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008845/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8846static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8847 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8848
8849 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8850 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8851 return false;
8852
8853 return doesExprLikelyComputeSize(BO->getLHS()) ||
8854 doesExprLikelyComputeSize(BO->getRHS());
8855 }
8856
8857 return getAsSizeOfExpr(SizeofExpr) != nullptr;
8858}
8859
8860/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8861///
8862/// \code
8863/// #define MACRO 0
8864/// foo(MACRO);
8865/// foo(0);
8866/// \endcode
8867///
8868/// This should return true for the first call to foo, but not for the second
8869/// (regardless of whether foo is a macro or function).
8870static bool isArgumentExpandedFromMacro(SourceManager &SM,
8871 SourceLocation CallLoc,
8872 SourceLocation ArgLoc) {
8873 if (!CallLoc.isMacroID())
8874 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8875
8876 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8877 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8878}
8879
8880/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8881/// last two arguments transposed.
8882static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8883 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8884 return;
8885
8886 const Expr *SizeArg =
8887 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8888
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00008889 auto isLiteralZero = [](const Expr *E) {
8890 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
8891 };
8892
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008893 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
8894 SourceLocation CallLoc = Call->getRParenLoc();
8895 SourceManager &SM = S.getSourceManager();
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00008896 if (isLiteralZero(SizeArg) &&
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008897 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
8898
8899 SourceLocation DiagLoc = SizeArg->getExprLoc();
8900
8901 // Some platforms #define bzero to __builtin_memset. See if this is the
8902 // case, and if so, emit a better diagnostic.
8903 if (BId == Builtin::BIbzero ||
8904 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
8905 CallLoc, SM, S.getLangOpts()) == "bzero")) {
8906 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
8907 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
Erik Pilkingtonc79b8812018-07-23 16:24:14 +00008908 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008909 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
8910 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
8911 }
8912 return;
8913 }
8914
8915 // If the second argument to a memset is a sizeof expression and the third
8916 // isn't, this is also likely an error. This should catch
8917 // 'memset(buf, sizeof(buf), 0xff)'.
8918 if (BId == Builtin::BImemset &&
8919 doesExprLikelyComputeSize(Call->getArg(1)) &&
8920 !doesExprLikelyComputeSize(Call->getArg(2))) {
8921 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
8922 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
8923 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
8924 return;
8925 }
8926}
8927
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008928/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008929///
Chandler Carruthac687262011-06-03 06:23:57 +00008930/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00008931/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
8932/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008933///
8934/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00008935void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00008936 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00008937 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00008938 assert(BId != 0);
8939
Ted Kremenekb5fabb22011-04-28 01:38:02 +00008940 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00008941 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00008942 unsigned ExpectedNumArgs =
8943 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00008944 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00008945 return;
8946
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00008947 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00008948 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00008949 unsigned LenArg =
8950 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00008951 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008952
Nico Weber0e6daef2013-12-26 23:38:39 +00008953 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008954 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00008955 return;
8956
Erik Pilkingtond1cf2762018-07-19 16:46:15 +00008957 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
8958 CheckMemaccessSize(*this, BId, Call);
8959
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008960 // We have special checking when the length is a sizeof expression.
8961 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
8962 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
8963 llvm::FoldingSetNodeID SizeOfArgID;
8964
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00008965 // Although widely used, 'bzero' is not a standard function. Be more strict
8966 // with the argument types before allowing diagnostics and only allow the
8967 // form bzero(ptr, sizeof(...)).
8968 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8969 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
8970 return;
8971
Douglas Gregor3bb2a812011-05-03 20:37:33 +00008972 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
8973 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00008974 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008975
Douglas Gregor3bb2a812011-05-03 20:37:33 +00008976 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00008977 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00008978 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00008979 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00008980
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008981 // Never warn about void type pointers. This can be used to suppress
8982 // false positives.
8983 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00008984 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008985
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008986 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
8987 // actually comparing the expressions for equality. Because computing the
8988 // expression IDs can be expensive, we only do this if the diagnostic is
8989 // enabled.
8990 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008991 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
8992 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008993 // We only compute IDs for expressions if the warning is enabled, and
8994 // cache the sizeof arg's ID.
8995 if (SizeOfArgID == llvm::FoldingSetNodeID())
8996 SizeOfArg->Profile(SizeOfArgID, Context, true);
8997 llvm::FoldingSetNodeID DestID;
8998 Dest->Profile(DestID, Context, true);
8999 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00009000 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9001 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009002 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00009003 StringRef ReadableName = FnName->getName();
9004
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009005 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00009006 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009007 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00009008 if (!PointeeTy->isIncompleteType() &&
9009 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009010 ActionIdx = 2; // If the pointee's size is sizeof(char),
9011 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00009012
9013 // If the function is defined as a builtin macro, do not show macro
9014 // expansion.
9015 SourceLocation SL = SizeOfArg->getExprLoc();
9016 SourceRange DSR = Dest->getSourceRange();
9017 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009018 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00009019
9020 if (SM.isMacroArgExpansion(SL)) {
9021 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9022 SL = SM.getSpellingLoc(SL);
9023 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9024 SM.getSpellingLoc(DSR.getEnd()));
9025 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9026 SM.getSpellingLoc(SSR.getEnd()));
9027 }
9028
Anna Zaksd08d9152012-05-30 23:14:52 +00009029 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009030 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00009031 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00009032 << PointeeTy
9033 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00009034 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00009035 << SSR);
9036 DiagRuntimeBehavior(SL, SizeOfArg,
9037 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9038 << ActionIdx
9039 << SSR);
9040
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00009041 break;
9042 }
9043 }
9044
9045 // Also check for cases where the sizeof argument is the exact same
9046 // type as the memory argument, and where it points to a user-defined
9047 // record type.
9048 if (SizeOfArgTy != QualType()) {
9049 if (PointeeTy->isRecordType() &&
9050 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9051 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9052 PDiag(diag::warn_sizeof_pointer_type_memaccess)
9053 << FnName << SizeOfArgTy << ArgIdx
9054 << PointeeTy << Dest->getSourceRange()
9055 << LenExpr->getSourceRange());
9056 break;
9057 }
Nico Weberc5e73862011-06-14 16:14:58 +00009058 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00009059 } else if (DestTy->isArrayType()) {
9060 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00009061 }
Nico Weberc5e73862011-06-14 16:14:58 +00009062
Nico Weberc44b35e2015-03-21 17:37:46 +00009063 if (PointeeTy == QualType())
9064 continue;
Anna Zaks22122702012-01-17 00:37:07 +00009065
Nico Weberc44b35e2015-03-21 17:37:46 +00009066 // Always complain about dynamic classes.
9067 bool IsContained;
9068 if (const CXXRecordDecl *ContainedRD =
9069 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00009070
Nico Weberc44b35e2015-03-21 17:37:46 +00009071 unsigned OperationType = 0;
9072 // "overwritten" if we're warning about the destination for any call
9073 // but memcmp; otherwise a verb appropriate to the call.
9074 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
9075 if (BId == Builtin::BImemcpy)
9076 OperationType = 1;
9077 else if(BId == Builtin::BImemmove)
9078 OperationType = 2;
9079 else if (BId == Builtin::BImemcmp)
9080 OperationType = 3;
9081 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009082
John McCall31168b02011-06-15 23:02:42 +00009083 DiagRuntimeBehavior(
9084 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00009085 PDiag(diag::warn_dyn_class_memaccess)
9086 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
9087 << FnName << IsContained << ContainedRD << OperationType
9088 << Call->getCallee()->getSourceRange());
9089 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9090 BId != Builtin::BImemset)
9091 DiagRuntimeBehavior(
9092 Dest->getExprLoc(), Dest,
9093 PDiag(diag::warn_arc_object_memaccess)
9094 << ArgIdx << FnName << PointeeTy
9095 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00009096 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9097 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9098 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9099 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9100 PDiag(diag::warn_cstruct_memaccess)
9101 << ArgIdx << FnName << PointeeTy << 0);
9102 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9103 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9104 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9105 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9106 PDiag(diag::warn_cstruct_memaccess)
9107 << ArgIdx << FnName << PointeeTy << 1);
9108 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9109 } else {
9110 continue;
9111 }
9112 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00009113 continue;
9114
9115 DiagRuntimeBehavior(
9116 Dest->getExprLoc(), Dest,
9117 PDiag(diag::note_bad_memaccess_silence)
9118 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9119 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00009120 }
9121}
9122
Ted Kremenek6865f772011-08-18 20:55:45 +00009123// A little helper routine: ignore addition and subtraction of integer literals.
9124// This intentionally does not ignore all integer constant expressions because
9125// we don't want to remove sizeof().
9126static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9127 Ex = Ex->IgnoreParenCasts();
9128
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009129 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00009130 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9131 if (!BO || !BO->isAdditiveOp())
9132 break;
9133
9134 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9135 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
Fangrui Song6907ce22018-07-30 19:24:48 +00009136
Ted Kremenek6865f772011-08-18 20:55:45 +00009137 if (isa<IntegerLiteral>(RHS))
9138 Ex = LHS;
9139 else if (isa<IntegerLiteral>(LHS))
9140 Ex = RHS;
9141 else
9142 break;
9143 }
9144
9145 return Ex;
9146}
9147
Anna Zaks13b08572012-08-08 21:42:23 +00009148static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9149 ASTContext &Context) {
9150 // Only handle constant-sized or VLAs, but not flexible members.
9151 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9152 // Only issue the FIXIT for arrays of size > 1.
9153 if (CAT->getSize().getSExtValue() <= 1)
9154 return false;
9155 } else if (!Ty->isVariableArrayType()) {
9156 return false;
9157 }
9158 return true;
9159}
9160
Ted Kremenek6865f772011-08-18 20:55:45 +00009161// Warn if the user has made the 'size' argument to strlcpy or strlcat
9162// be the size of the source, instead of the destination.
9163void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9164 IdentifierInfo *FnName) {
9165
9166 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00009167 unsigned NumArgs = Call->getNumArgs();
9168 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00009169 return;
9170
9171 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9172 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00009173 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00009174
9175 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009176 Call->getBeginLoc(), Call->getRParenLoc()))
Nico Weber0e6daef2013-12-26 23:38:39 +00009177 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009178
Ted Kremenek6865f772011-08-18 20:55:45 +00009179 // Look for 'strlcpy(dst, x, sizeof(x))'
9180 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9181 CompareWithSrc = Ex;
9182 else {
9183 // Look for 'strlcpy(dst, x, strlen(x))'
9184 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00009185 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9186 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00009187 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9188 }
9189 }
9190
9191 if (!CompareWithSrc)
9192 return;
9193
9194 // Determine if the argument to sizeof/strlen is equal to the source
9195 // argument. In principle there's all kinds of things you could do
9196 // here, for instance creating an == expression and evaluating it with
9197 // EvaluateAsBooleanCondition, but this uses a more direct technique:
9198 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9199 if (!SrcArgDRE)
9200 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009201
Ted Kremenek6865f772011-08-18 20:55:45 +00009202 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
Fangrui Song6907ce22018-07-30 19:24:48 +00009203 if (!CompareWithSrcDRE ||
Ted Kremenek6865f772011-08-18 20:55:45 +00009204 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9205 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00009206
Ted Kremenek6865f772011-08-18 20:55:45 +00009207 const Expr *OriginalSizeArg = Call->getArg(2);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009208 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9209 << OriginalSizeArg->getSourceRange() << FnName;
Fangrui Song6907ce22018-07-30 19:24:48 +00009210
Ted Kremenek6865f772011-08-18 20:55:45 +00009211 // Output a FIXIT hint if the destination is an array (rather than a
9212 // pointer to an array). This could be enhanced to handle some
9213 // pointers if we know the actual size, like if DstArg is 'array+2'
9214 // we could say 'sizeof(array)-2'.
9215 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00009216 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00009217 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009218
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009219 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00009220 llvm::raw_svector_ostream OS(sizeString);
9221 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009222 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00009223 OS << ")";
Fangrui Song6907ce22018-07-30 19:24:48 +00009224
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009225 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9226 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9227 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00009228}
9229
Anna Zaks314cd092012-02-01 19:08:57 +00009230/// Check if two expressions refer to the same declaration.
9231static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9232 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9233 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9234 return D1->getDecl() == D2->getDecl();
9235 return false;
9236}
9237
9238static const Expr *getStrlenExprArg(const Expr *E) {
9239 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9240 const FunctionDecl *FD = CE->getDirectCallee();
9241 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00009242 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009243 return CE->getArg(0)->IgnoreParenCasts();
9244 }
Craig Topperc3ec1492014-05-26 06:22:03 +00009245 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00009246}
9247
9248// Warn on anti-patterns as the 'size' argument to strncat.
9249// The correct size argument should look like following:
9250// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9251void Sema::CheckStrncatArguments(const CallExpr *CE,
9252 IdentifierInfo *FnName) {
9253 // Don't crash if the user has the wrong number of arguments.
9254 if (CE->getNumArgs() < 3)
9255 return;
9256 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9257 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9258 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9259
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009260 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
Nico Weber0e6daef2013-12-26 23:38:39 +00009261 CE->getRParenLoc()))
9262 return;
9263
Anna Zaks314cd092012-02-01 19:08:57 +00009264 // Identify common expressions, which are wrongly used as the size argument
9265 // to strncat and may lead to buffer overflows.
9266 unsigned PatternType = 0;
9267 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9268 // - sizeof(dst)
9269 if (referToTheSameDecl(SizeOfArg, DstArg))
9270 PatternType = 1;
9271 // - sizeof(src)
9272 else if (referToTheSameDecl(SizeOfArg, SrcArg))
9273 PatternType = 2;
9274 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9275 if (BE->getOpcode() == BO_Sub) {
9276 const Expr *L = BE->getLHS()->IgnoreParenCasts();
9277 const Expr *R = BE->getRHS()->IgnoreParenCasts();
9278 // - sizeof(dst) - strlen(dst)
9279 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9280 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9281 PatternType = 1;
9282 // - sizeof(src) - (anything)
9283 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9284 PatternType = 2;
9285 }
9286 }
9287
9288 if (PatternType == 0)
9289 return;
9290
Anna Zaks5069aa32012-02-03 01:27:37 +00009291 // Generate the diagnostic.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009292 SourceLocation SL = LenArg->getBeginLoc();
Anna Zaks5069aa32012-02-03 01:27:37 +00009293 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00009294 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00009295
9296 // If the function is defined as a builtin macro, do not show macro expansion.
9297 if (SM.isMacroArgExpansion(SL)) {
9298 SL = SM.getSpellingLoc(SL);
9299 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9300 SM.getSpellingLoc(SR.getEnd()));
9301 }
9302
Anna Zaks13b08572012-08-08 21:42:23 +00009303 // Check if the destination is an array (rather than a pointer to an array).
9304 QualType DstTy = DstArg->getType();
9305 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9306 Context);
9307 if (!isKnownSizeArray) {
9308 if (PatternType == 1)
9309 Diag(SL, diag::warn_strncat_wrong_size) << SR;
9310 else
9311 Diag(SL, diag::warn_strncat_src_size) << SR;
9312 return;
9313 }
9314
Anna Zaks314cd092012-02-01 19:08:57 +00009315 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00009316 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009317 else
Anna Zaks5069aa32012-02-03 01:27:37 +00009318 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00009319
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00009320 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00009321 llvm::raw_svector_ostream OS(sizeString);
9322 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009323 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009324 OS << ") - ";
9325 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00009326 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00009327 OS << ") - 1";
9328
Anna Zaks5069aa32012-02-03 01:27:37 +00009329 Diag(SL, diag::note_strncat_wrong_size)
9330 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00009331}
9332
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009333void
9334Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9335 SourceLocation ReturnLoc,
9336 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00009337 const AttrVec *Attrs,
9338 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009339 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00009340 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9341 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00009342 CheckNonNullExpr(*this, RetValExp))
9343 Diag(ReturnLoc, diag::warn_null_ret)
9344 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00009345
9346 // C++11 [basic.stc.dynamic.allocation]p4:
9347 // If an allocation function declared with a non-throwing
9348 // exception-specification fails to allocate storage, it shall return
9349 // a null pointer. Any other allocation function that fails to allocate
9350 // storage shall indicate failure only by throwing an exception [...]
9351 if (FD) {
9352 OverloadedOperatorKind Op = FD->getOverloadedOperator();
9353 if (Op == OO_New || Op == OO_Array_New) {
9354 const FunctionProtoType *Proto
9355 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00009356 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00009357 CheckNonNullExpr(*this, RetValExp))
9358 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9359 << FD << getLangOpts().CPlusPlus11;
9360 }
9361 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00009362}
9363
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009364//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9365
9366/// Check for comparisons of floating point operands using != and ==.
9367/// Issue a warning if these are no self-comparisons, as they are not likely
9368/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00009369void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00009370 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9371 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009372
9373 // Special case: check for x == x (which is OK).
9374 // Do not emit warnings for such cases.
9375 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9376 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9377 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00009378 return;
Mike Stump11289f42009-09-09 15:08:12 +00009379
Ted Kremenekeda40e22007-11-29 00:59:04 +00009380 // Special case: check for comparisons against literals that can be exactly
9381 // represented by APFloat. In such cases, do not emit a warning. This
9382 // is a heuristic: often comparison against such literals are used to
9383 // detect if a value in a variable has not changed. This clearly can
9384 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00009385 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9386 if (FLL->isExact())
9387 return;
9388 } else
9389 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9390 if (FLR->isExact())
9391 return;
Mike Stump11289f42009-09-09 15:08:12 +00009392
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009393 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00009394 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00009395 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00009396 return;
Mike Stump11289f42009-09-09 15:08:12 +00009397
David Blaikie1f4ff152012-07-16 20:47:22 +00009398 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00009399 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00009400 return;
Mike Stump11289f42009-09-09 15:08:12 +00009401
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009402 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00009403 Diag(Loc, diag::warn_floatingpoint_eq)
9404 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00009405}
John McCallca01b222010-01-04 23:21:16 +00009406
John McCall70aa5392010-01-06 05:24:50 +00009407//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9408//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00009409
John McCall70aa5392010-01-06 05:24:50 +00009410namespace {
John McCallca01b222010-01-04 23:21:16 +00009411
John McCall70aa5392010-01-06 05:24:50 +00009412/// Structure recording the 'active' range of an integer-valued
9413/// expression.
9414struct IntRange {
9415 /// The number of bits active in the int.
9416 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00009417
John McCall70aa5392010-01-06 05:24:50 +00009418 /// True if the int is known not to have negative values.
9419 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00009420
John McCall70aa5392010-01-06 05:24:50 +00009421 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009422 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00009423
John McCall817d4af2010-11-10 23:38:19 +00009424 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00009425 static IntRange forBoolType() {
9426 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00009427 }
9428
John McCall817d4af2010-11-10 23:38:19 +00009429 /// Returns the range of an opaque value of the given integral type.
9430 static IntRange forValueOfType(ASTContext &C, QualType T) {
9431 return forValueOfCanonicalType(C,
9432 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00009433 }
9434
John McCall817d4af2010-11-10 23:38:19 +00009435 /// Returns the range of an opaque value of a canonical integral type.
9436 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00009437 assert(T->isCanonicalUnqualified());
9438
9439 if (const VectorType *VT = dyn_cast<VectorType>(T))
9440 T = VT->getElementType().getTypePtr();
9441 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9442 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00009443 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9444 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00009445
Roman Lebedevca1aaac2017-10-21 16:44:03 +00009446 if (!C.getLangOpts().CPlusPlus) {
9447 // For enum types in C code, use the underlying datatype.
9448 if (const EnumType *ET = dyn_cast<EnumType>(T))
9449 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9450 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9451 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00009452 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00009453 // In C++11, enums can have a fixed underlying type. Use this type to
9454 // compute the range.
9455 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00009456 return IntRange(C.getIntWidth(QualType(T, 0)),
9457 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00009458 }
John McCall18a2c2c2010-11-09 22:22:12 +00009459
David Majnemer6a426652013-06-07 22:07:20 +00009460 unsigned NumPositive = Enum->getNumPositiveBits();
9461 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00009462
David Majnemer6a426652013-06-07 22:07:20 +00009463 if (NumNegative == 0)
9464 return IntRange(NumPositive, true/*NonNegative*/);
9465 else
9466 return IntRange(std::max(NumPositive + 1, NumNegative),
9467 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00009468 }
John McCall70aa5392010-01-06 05:24:50 +00009469
9470 const BuiltinType *BT = cast<BuiltinType>(T);
9471 assert(BT->isInteger());
9472
9473 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9474 }
9475
John McCall817d4af2010-11-10 23:38:19 +00009476 /// Returns the "target" range of a canonical integral type, i.e.
9477 /// the range of values expressible in the type.
9478 ///
9479 /// This matches forValueOfCanonicalType except that enums have the
9480 /// full range of their type, not the range of their enumerators.
9481 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9482 assert(T->isCanonicalUnqualified());
9483
9484 if (const VectorType *VT = dyn_cast<VectorType>(T))
9485 T = VT->getElementType().getTypePtr();
9486 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9487 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00009488 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9489 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00009490 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00009491 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00009492
9493 const BuiltinType *BT = cast<BuiltinType>(T);
9494 assert(BT->isInteger());
9495
9496 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9497 }
9498
9499 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00009500 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00009501 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00009502 L.NonNegative && R.NonNegative);
9503 }
9504
John McCall817d4af2010-11-10 23:38:19 +00009505 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00009506 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00009507 return IntRange(std::min(L.Width, R.Width),
9508 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00009509 }
9510};
9511
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009512} // namespace
9513
9514static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9515 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009516 if (value.isSigned() && value.isNegative())
9517 return IntRange(value.getMinSignedBits(), false);
9518
9519 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00009520 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00009521
9522 // isNonNegative() just checks the sign bit without considering
9523 // signedness.
9524 return IntRange(value.getActiveBits(), true);
9525}
9526
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009527static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9528 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009529 if (result.isInt())
9530 return GetValueRange(C, result.getInt(), MaxWidth);
9531
9532 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00009533 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9534 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9535 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9536 R = IntRange::join(R, El);
9537 }
John McCall70aa5392010-01-06 05:24:50 +00009538 return R;
9539 }
9540
9541 if (result.isComplexInt()) {
9542 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9543 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9544 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00009545 }
9546
9547 // This can happen with lossless casts to intptr_t of "based" lvalues.
9548 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00009549 // FIXME: The only reason we need to pass the type in here is to get
9550 // the sign right on this one case. It would be nice if APValue
9551 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00009552 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00009553 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00009554}
John McCall70aa5392010-01-06 05:24:50 +00009555
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009556static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009557 QualType Ty = E->getType();
9558 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9559 Ty = AtomicRHS->getValueType();
9560 return Ty;
9561}
9562
John McCall70aa5392010-01-06 05:24:50 +00009563/// Pseudo-evaluate the given integer expression, estimating the
9564/// range of values it might take.
9565///
9566/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009567static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00009568 E = E->IgnoreParens();
9569
9570 // Try a full evaluation first.
9571 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009572 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00009573 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00009574
9575 // I think we only want to look through implicit casts here; if the
9576 // user has an explicit widening cast, we should treat the value as
9577 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009578 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00009579 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00009580 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9581
Eli Friedmane6d33952013-07-08 20:20:06 +00009582 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00009583
George Burgess IVdf1ed002016-01-13 01:52:39 +00009584 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9585 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00009586
John McCall70aa5392010-01-06 05:24:50 +00009587 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00009588 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00009589 return OutputTypeRange;
9590
9591 IntRange SubRange
9592 = GetExprRange(C, CE->getSubExpr(),
9593 std::min(MaxWidth, OutputTypeRange.Width));
9594
9595 // Bail out if the subexpr's range is as wide as the cast type.
9596 if (SubRange.Width >= OutputTypeRange.Width)
9597 return OutputTypeRange;
9598
9599 // Otherwise, we take the smaller width, and we're non-negative if
9600 // either the output type or the subexpr is.
9601 return IntRange(SubRange.Width,
9602 SubRange.NonNegative || OutputTypeRange.NonNegative);
9603 }
9604
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009605 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009606 // If we can fold the condition, just take that operand.
9607 bool CondResult;
9608 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9609 return GetExprRange(C, CondResult ? CO->getTrueExpr()
9610 : CO->getFalseExpr(),
9611 MaxWidth);
9612
9613 // Otherwise, conservatively merge.
9614 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9615 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9616 return IntRange::join(L, R);
9617 }
9618
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009619 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009620 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00009621 case BO_Cmp:
9622 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00009623
9624 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00009625 case BO_LAnd:
9626 case BO_LOr:
9627 case BO_LT:
9628 case BO_GT:
9629 case BO_LE:
9630 case BO_GE:
9631 case BO_EQ:
9632 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00009633 return IntRange::forBoolType();
9634
John McCallc3688382011-07-13 06:35:24 +00009635 // The type of the assignments is the type of the LHS, so the RHS
9636 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00009637 case BO_MulAssign:
9638 case BO_DivAssign:
9639 case BO_RemAssign:
9640 case BO_AddAssign:
9641 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00009642 case BO_XorAssign:
9643 case BO_OrAssign:
9644 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00009645 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00009646
John McCallc3688382011-07-13 06:35:24 +00009647 // Simple assignments just pass through the RHS, which will have
9648 // been coerced to the LHS type.
9649 case BO_Assign:
9650 // TODO: bitfields?
9651 return GetExprRange(C, BO->getRHS(), MaxWidth);
9652
John McCall70aa5392010-01-06 05:24:50 +00009653 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009654 case BO_PtrMemD:
9655 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00009656 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009657
John McCall2ce81ad2010-01-06 22:07:33 +00009658 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00009659 case BO_And:
9660 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00009661 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9662 GetExprRange(C, BO->getRHS(), MaxWidth));
9663
John McCall70aa5392010-01-06 05:24:50 +00009664 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00009665 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00009666 // ...except that we want to treat '1 << (blah)' as logically
9667 // positive. It's an important idiom.
9668 if (IntegerLiteral *I
9669 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9670 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009671 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00009672 return IntRange(R.Width, /*NonNegative*/ true);
9673 }
9674 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009675 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00009676
John McCalle3027922010-08-25 11:45:40 +00009677 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00009678 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009679
John McCall2ce81ad2010-01-06 22:07:33 +00009680 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00009681 case BO_Shr:
9682 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00009683 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9684
9685 // If the shift amount is a positive constant, drop the width by
9686 // that much.
9687 llvm::APSInt shift;
9688 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9689 shift.isNonNegative()) {
9690 unsigned zext = shift.getZExtValue();
9691 if (zext >= L.Width)
9692 L.Width = (L.NonNegative ? 0 : 1);
9693 else
9694 L.Width -= zext;
9695 }
9696
9697 return L;
9698 }
9699
9700 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009701 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009702 return GetExprRange(C, BO->getRHS(), MaxWidth);
9703
John McCall2ce81ad2010-01-06 22:07:33 +00009704 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009705 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009706 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009707 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009708 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009709
John McCall51431812011-07-14 22:39:48 +00009710 // The width of a division result is mostly determined by the size
9711 // of the LHS.
9712 case BO_Div: {
9713 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009714 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009715 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9716
9717 // If the divisor is constant, use that.
9718 llvm::APSInt divisor;
9719 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9720 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9721 if (log2 >= L.Width)
9722 L.Width = (L.NonNegative ? 0 : 1);
9723 else
9724 L.Width = std::min(L.Width - log2, MaxWidth);
9725 return L;
9726 }
9727
9728 // Otherwise, just use the LHS's width.
9729 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9730 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9731 }
9732
9733 // The result of a remainder can't be larger than the result of
9734 // either side.
9735 case BO_Rem: {
9736 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009737 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009738 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9739 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9740
9741 IntRange meet = IntRange::meet(L, R);
9742 meet.Width = std::min(meet.Width, MaxWidth);
9743 return meet;
9744 }
9745
9746 // The default behavior is okay for these.
9747 case BO_Mul:
9748 case BO_Add:
9749 case BO_Xor:
9750 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009751 break;
9752 }
9753
John McCall51431812011-07-14 22:39:48 +00009754 // The default case is to treat the operation as if it were closed
9755 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009756 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9757 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9758 return IntRange::join(L, R);
9759 }
9760
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009761 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009762 switch (UO->getOpcode()) {
9763 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009764 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009765 return IntRange::forBoolType();
9766
9767 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009768 case UO_Deref:
9769 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009770 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009771
9772 default:
9773 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9774 }
9775 }
9776
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009777 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009778 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9779
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009780 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009781 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009782 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009783
Eli Friedmane6d33952013-07-08 20:20:06 +00009784 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009785}
John McCall263a48b2010-01-04 23:31:57 +00009786
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009787static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009788 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009789}
9790
John McCall263a48b2010-01-04 23:31:57 +00009791/// Checks whether the given value, which currently has the given
9792/// source semantics, has the same value when coerced through the
9793/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009794static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9795 const llvm::fltSemantics &Src,
9796 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009797 llvm::APFloat truncated = value;
9798
9799 bool ignored;
9800 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9801 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9802
9803 return truncated.bitwiseIsEqual(value);
9804}
9805
9806/// Checks whether the given value, which currently has the given
9807/// source semantics, has the same value when coerced through the
9808/// target semantics.
9809///
9810/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009811static bool IsSameFloatAfterCast(const APValue &value,
9812 const llvm::fltSemantics &Src,
9813 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009814 if (value.isFloat())
9815 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9816
9817 if (value.isVector()) {
9818 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9819 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9820 return false;
9821 return true;
9822 }
9823
9824 assert(value.isComplexFloat());
9825 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9826 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9827}
9828
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009829static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009830
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009831static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009832 // Suppress cases where we are comparing against an enum constant.
9833 if (const DeclRefExpr *DR =
9834 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9835 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009836 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009837
9838 // Suppress cases where the '0' value is expanded from a macro.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009839 if (E->getBeginLoc().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009840 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009841
Roman Lebedev6de129e2017-10-15 20:13:17 +00009842 return false;
9843}
9844
Richard Smith692f66ab2017-12-06 19:23:19 +00009845static bool isKnownToHaveUnsignedValue(Expr *E) {
9846 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009847 (!E->getType()->isSignedIntegerType() ||
9848 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9849}
9850
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009851namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009852/// The promoted range of values of a type. In general this has the
9853/// following structure:
9854///
9855/// |-----------| . . . |-----------|
9856/// ^ ^ ^ ^
9857/// Min HoleMin HoleMax Max
9858///
9859/// ... where there is only a hole if a signed type is promoted to unsigned
9860/// (in which case Min and Max are the smallest and largest representable
9861/// values).
9862struct PromotedRange {
9863 // Min, or HoleMax if there is a hole.
9864 llvm::APSInt PromotedMin;
9865 // Max, or HoleMin if there is a hole.
9866 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009867
Richard Smitha5370fb2017-12-08 22:57:11 +00009868 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9869 if (R.Width == 0)
9870 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9871 else if (R.Width >= BitWidth && !Unsigned) {
9872 // Promotion made the type *narrower*. This happens when promoting
9873 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9874 // Treat all values of 'signed int' as being in range for now.
9875 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9876 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9877 } else {
9878 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9879 .extOrTrunc(BitWidth);
9880 PromotedMin.setIsUnsigned(Unsigned);
9881
9882 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9883 .extOrTrunc(BitWidth);
9884 PromotedMax.setIsUnsigned(Unsigned);
9885 }
9886 }
9887
9888 // Determine whether this range is contiguous (has no hole).
9889 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9890
9891 // Where a constant value is within the range.
9892 enum ComparisonResult {
9893 LT = 0x1,
9894 LE = 0x2,
9895 GT = 0x4,
9896 GE = 0x8,
9897 EQ = 0x10,
9898 NE = 0x20,
9899 InRangeFlag = 0x40,
9900
9901 Less = LE | LT | NE,
9902 Min = LE | InRangeFlag,
9903 InRange = InRangeFlag,
9904 Max = GE | InRangeFlag,
9905 Greater = GE | GT | NE,
9906
9907 OnlyValue = LE | GE | EQ | InRangeFlag,
9908 InHole = NE
9909 };
9910
9911 ComparisonResult compare(const llvm::APSInt &Value) const {
9912 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9913 Value.isUnsigned() == PromotedMin.isUnsigned());
9914 if (!isContiguous()) {
9915 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9916 if (Value.isMinValue()) return Min;
9917 if (Value.isMaxValue()) return Max;
9918 if (Value >= PromotedMin) return InRange;
9919 if (Value <= PromotedMax) return InRange;
9920 return InHole;
9921 }
9922
9923 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9924 case -1: return Less;
9925 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9926 case 1:
9927 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9928 case -1: return InRange;
9929 case 0: return Max;
9930 case 1: return Greater;
9931 }
9932 }
9933
9934 llvm_unreachable("impossible compare result");
9935 }
9936
Richard Smithc70f1d62017-12-14 15:16:18 +00009937 static llvm::Optional<StringRef>
9938 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9939 if (Op == BO_Cmp) {
9940 ComparisonResult LTFlag = LT, GTFlag = GT;
9941 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9942
9943 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9944 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9945 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9946 return llvm::None;
9947 }
9948
Richard Smitha5370fb2017-12-08 22:57:11 +00009949 ComparisonResult TrueFlag, FalseFlag;
9950 if (Op == BO_EQ) {
9951 TrueFlag = EQ;
9952 FalseFlag = NE;
9953 } else if (Op == BO_NE) {
9954 TrueFlag = NE;
9955 FalseFlag = EQ;
9956 } else {
9957 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9958 TrueFlag = LT;
9959 FalseFlag = GE;
9960 } else {
9961 TrueFlag = GT;
9962 FalseFlag = LE;
9963 }
9964 if (Op == BO_GE || Op == BO_LE)
9965 std::swap(TrueFlag, FalseFlag);
9966 }
9967 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009968 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009969 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009970 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009971 return llvm::None;
9972 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009973};
John McCallcc7e5bf2010-05-06 08:58:33 +00009974}
9975
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009976static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009977 // Strip off implicit integral promotions.
9978 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009979 if (ICE->getCastKind() != CK_IntegralCast &&
9980 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009981 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009982 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009983 }
9984
9985 return E->getType()->isEnumeralType();
9986}
9987
Richard Smith692f66ab2017-12-06 19:23:19 +00009988static int classifyConstantValue(Expr *Constant) {
9989 // The values of this enumeration are used in the diagnostics
9990 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9991 enum ConstantValueKind {
9992 Miscellaneous = 0,
9993 LiteralTrue,
9994 LiteralFalse
9995 };
9996 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9997 return BL->getValue() ? ConstantValueKind::LiteralTrue
9998 : ConstantValueKind::LiteralFalse;
9999 return ConstantValueKind::Miscellaneous;
10000}
10001
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010002static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10003 Expr *Constant, Expr *Other,
10004 const llvm::APSInt &Value,
10005 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010006 if (S.inTemplateInstantiation())
10007 return false;
10008
Richard Smitha5370fb2017-12-08 22:57:11 +000010009 Expr *OriginalOther = Other;
10010
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010011 Constant = Constant->IgnoreParenImpCasts();
10012 Other = Other->IgnoreParenImpCasts();
10013
Richard Smitha5370fb2017-12-08 22:57:11 +000010014 // Suppress warnings on tautological comparisons between values of the same
10015 // enumeration type. There are only two ways we could warn on this:
10016 // - If the constant is outside the range of representable values of
10017 // the enumeration. In such a case, we should warn about the cast
10018 // to enumeration type, not about the comparison.
10019 // - If the constant is the maximum / minimum in-range value. For an
10020 // enumeratin type, such comparisons can be meaningful and useful.
10021 if (Constant->getType()->isEnumeralType() &&
10022 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10023 return false;
10024
Hans Wennborg5bb88e02017-12-08 05:19:12 +000010025 // TODO: Investigate using GetExprRange() to get tighter bounds
10026 // on the bit ranges.
10027 QualType OtherT = Other->getType();
10028 if (const auto *AT = OtherT->getAs<AtomicType>())
10029 OtherT = AT->getValueType();
10030 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10031
10032 // Whether we're treating Other as being a bool because of the form of
10033 // expression despite it having another type (typically 'int' in C).
10034 bool OtherIsBooleanDespiteType =
10035 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10036 if (OtherIsBooleanDespiteType)
10037 OtherRange = IntRange::forBoolType();
10038
Richard Smitha5370fb2017-12-08 22:57:11 +000010039 // Determine the promoted range of the other type and see if a comparison of
10040 // the constant against that range is tautological.
10041 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10042 Value.isUnsigned());
10043 auto Cmp = OtherPromotedRange.compare(Value);
10044 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10045 if (!Result)
10046 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +000010047
Richard Smitha5370fb2017-12-08 22:57:11 +000010048 // Suppress the diagnostic for an in-range comparison if the constant comes
10049 // from a macro or enumerator. We don't want to diagnose
10050 //
10051 // some_long_value <= INT_MAX
10052 //
10053 // when sizeof(int) == sizeof(long).
10054 bool InRange = Cmp & PromotedRange::InRangeFlag;
10055 if (InRange && IsEnumConstOrFromMacro(S, Constant))
10056 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010057
10058 // If this is a comparison to an enum constant, include that
10059 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +000010060 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010061 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10062 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10063
Richard Smitha5370fb2017-12-08 22:57:11 +000010064 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010065 SmallString<64> PrettySourceValue;
10066 llvm::raw_svector_ostream OS(PrettySourceValue);
10067 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +000010068 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +000010069 else
10070 OS << Value;
10071
Richard Smitha5370fb2017-12-08 22:57:11 +000010072 // FIXME: We use a somewhat different formatting for the in-range cases and
10073 // cases involving boolean values for historical reasons. We should pick a
10074 // consistent way of presenting these diagnostics.
10075 if (!InRange || Other->isKnownToHaveBooleanValue()) {
10076 S.DiagRuntimeBehavior(
10077 E->getOperatorLoc(), E,
10078 S.PDiag(!InRange ? diag::warn_out_of_range_compare
10079 : diag::warn_tautological_bool_compare)
10080 << OS.str() << classifyConstantValue(Constant)
10081 << OtherT << OtherIsBooleanDespiteType << *Result
10082 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10083 } else {
10084 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10085 ? (HasEnumType(OriginalOther)
10086 ? diag::warn_unsigned_enum_always_true_comparison
10087 : diag::warn_unsigned_always_true_comparison)
10088 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +000010089
Richard Smitha5370fb2017-12-08 22:57:11 +000010090 S.Diag(E->getOperatorLoc(), Diag)
10091 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10092 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10093 }
10094
10095 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010096}
10097
John McCallcc7e5bf2010-05-06 08:58:33 +000010098/// Analyze the operands of the given comparison. Implements the
10099/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010100static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +000010101 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10102 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010103}
John McCall263a48b2010-01-04 23:31:57 +000010104
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010105/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +000010106///
Richard Trieu82402a02011-09-15 21:56:47 +000010107/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010108static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010109 // The type the comparison is being performed in.
10110 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +000010111
10112 // Only analyze comparison operators where both sides have been converted to
10113 // the same type.
10114 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10115 return AnalyzeImpConvsInComparison(S, E);
10116
10117 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +000010118 if (E->isValueDependent())
10119 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010120
Roman Lebedev6de129e2017-10-15 20:13:17 +000010121 Expr *LHS = E->getLHS();
10122 Expr *RHS = E->getRHS();
10123
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010124 if (T->isIntegralType(S.Context)) {
10125 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +000010126 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010127
Roman Lebedev6de129e2017-10-15 20:13:17 +000010128 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10129 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +000010130
Roman Lebedev6de129e2017-10-15 20:13:17 +000010131 // We don't care about expressions whose result is a constant.
10132 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10133 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +000010134
Roman Lebedev6de129e2017-10-15 20:13:17 +000010135 // We only care about expressions where just one side is literal
10136 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10137 // Is the constant on the RHS or LHS?
10138 const bool RhsConstant = IsRHSIntegralLiteral;
10139 Expr *Const = RhsConstant ? RHS : LHS;
10140 Expr *Other = RhsConstant ? LHS : RHS;
10141 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10142
10143 // Check whether an integer constant comparison results in a value
10144 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +000010145 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10146 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010147 }
10148 }
10149
10150 if (!T->hasUnsignedIntegerRepresentation()) {
10151 // We don't do anything special if this isn't an unsigned integral
10152 // comparison: we're only interested in integral comparisons, and
10153 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +000010154 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +000010155 }
10156
10157 LHS = LHS->IgnoreParenImpCasts();
10158 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010159
Alex Lorenzb57409f2018-02-07 20:45:39 +000010160 if (!S.getLangOpts().CPlusPlus) {
10161 // Avoid warning about comparison of integers with different signs when
10162 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10163 // the type of `E`.
10164 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10165 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10166 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10167 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10168 }
10169
John McCallcc7e5bf2010-05-06 08:58:33 +000010170 // Check to see if one of the (unmodified) operands is of different
10171 // signedness.
10172 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +000010173 if (LHS->getType()->hasSignedIntegerRepresentation()) {
10174 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +000010175 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +000010176 signedOperand = LHS;
10177 unsignedOperand = RHS;
10178 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10179 signedOperand = RHS;
10180 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +000010181 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +000010182 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +000010183 }
10184
John McCallcc7e5bf2010-05-06 08:58:33 +000010185 // Otherwise, calculate the effective range of the signed operand.
10186 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +000010187
John McCallcc7e5bf2010-05-06 08:58:33 +000010188 // Go ahead and analyze implicit conversions in the operands. Note
10189 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +000010190 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10191 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +000010192
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010193 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +000010194 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +000010195 return;
John McCallca01b222010-01-04 23:21:16 +000010196
10197 // For (in)equality comparisons, if the unsigned operand is a
10198 // constant which cannot collide with a overflowed signed operand,
10199 // then reinterpreting the signed operand as unsigned will not
10200 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +000010201 if (E->isEqualityOp()) {
10202 unsigned comparisonWidth = S.Context.getIntWidth(T);
10203 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +000010204
John McCallcc7e5bf2010-05-06 08:58:33 +000010205 // We should never be unable to prove that the unsigned operand is
10206 // non-negative.
10207 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10208
10209 if (unsignedRange.Width < comparisonWidth)
10210 return;
10211 }
10212
Douglas Gregorbfb4a212012-05-01 01:53:49 +000010213 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10214 S.PDiag(diag::warn_mixed_sign_comparison)
10215 << LHS->getType() << RHS->getType()
10216 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +000010217}
10218
John McCall1f425642010-11-11 03:21:53 +000010219/// Analyzes an attempt to assign the given value to a bitfield.
10220///
10221/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010222static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10223 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +000010224 assert(Bitfield->isBitField());
10225 if (Bitfield->isInvalidDecl())
10226 return false;
10227
John McCalldeebbcf2010-11-11 05:33:51 +000010228 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +000010229 QualType BitfieldType = Bitfield->getType();
10230 if (BitfieldType->isBooleanType())
10231 return false;
10232
10233 if (BitfieldType->isEnumeralType()) {
10234 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10235 // If the underlying enum type was not explicitly specified as an unsigned
10236 // type and the enum contain only positive values, MSVC++ will cause an
10237 // inconsistency by storing this as a signed type.
10238 if (S.getLangOpts().CPlusPlus11 &&
10239 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10240 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10241 BitfieldEnumDecl->getNumNegativeBits() == 0) {
10242 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10243 << BitfieldEnumDecl->getNameAsString();
10244 }
10245 }
10246
John McCalldeebbcf2010-11-11 05:33:51 +000010247 if (Bitfield->getType()->isBooleanType())
10248 return false;
10249
Douglas Gregor789adec2011-02-04 13:09:01 +000010250 // Ignore value- or type-dependent expressions.
10251 if (Bitfield->getBitWidth()->isValueDependent() ||
10252 Bitfield->getBitWidth()->isTypeDependent() ||
10253 Init->isValueDependent() ||
10254 Init->isTypeDependent())
10255 return false;
10256
John McCall1f425642010-11-11 03:21:53 +000010257 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +000010258 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +000010259
Richard Smith5fab0c92011-12-28 19:48:30 +000010260 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +000010261 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
10262 Expr::SE_AllowSideEffects)) {
10263 // The RHS is not constant. If the RHS has an enum type, make sure the
10264 // bitfield is wide enough to hold all the values of the enum without
10265 // truncation.
10266 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10267 EnumDecl *ED = EnumTy->getDecl();
10268 bool SignedBitfield = BitfieldType->isSignedIntegerType();
10269
10270 // Enum types are implicitly signed on Windows, so check if there are any
10271 // negative enumerators to see if the enum was intended to be signed or
10272 // not.
10273 bool SignedEnum = ED->getNumNegativeBits() > 0;
10274
10275 // Check for surprising sign changes when assigning enum values to a
10276 // bitfield of different signedness. If the bitfield is signed and we
10277 // have exactly the right number of bits to store this unsigned enum,
10278 // suggest changing the enum to an unsigned type. This typically happens
10279 // on Windows where unfixed enums always use an underlying type of 'int'.
10280 unsigned DiagID = 0;
10281 if (SignedEnum && !SignedBitfield) {
10282 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10283 } else if (SignedBitfield && !SignedEnum &&
10284 ED->getNumPositiveBits() == FieldWidth) {
10285 DiagID = diag::warn_signed_bitfield_enum_conversion;
10286 }
10287
10288 if (DiagID) {
10289 S.Diag(InitLoc, DiagID) << Bitfield << ED;
10290 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10291 SourceRange TypeRange =
10292 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10293 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10294 << SignedEnum << TypeRange;
10295 }
10296
10297 // Compute the required bitwidth. If the enum has negative values, we need
10298 // one more bit than the normal number of positive bits to represent the
10299 // sign bit.
10300 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10301 ED->getNumNegativeBits())
10302 : ED->getNumPositiveBits();
10303
10304 // Check the bitwidth.
10305 if (BitsNeeded > FieldWidth) {
10306 Expr *WidthExpr = Bitfield->getBitWidth();
10307 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10308 << Bitfield << ED;
10309 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10310 << BitsNeeded << ED << WidthExpr->getSourceRange();
10311 }
10312 }
10313
John McCall1f425642010-11-11 03:21:53 +000010314 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +000010315 }
John McCall1f425642010-11-11 03:21:53 +000010316
John McCall1f425642010-11-11 03:21:53 +000010317 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +000010318
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010319 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +000010320 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +000010321 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10322 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +000010323
John McCall1f425642010-11-11 03:21:53 +000010324 if (OriginalWidth <= FieldWidth)
10325 return false;
10326
Eli Friedmanc267a322012-01-26 23:11:39 +000010327 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +000010328 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +000010329 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +000010330
Eli Friedmanc267a322012-01-26 23:11:39 +000010331 // Check whether the stored value is equal to the original value.
10332 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +000010333 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +000010334 return false;
10335
Eli Friedmanc267a322012-01-26 23:11:39 +000010336 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +000010337 // therefore don't strictly fit into a signed bitfield of width 1.
10338 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +000010339 return false;
10340
John McCall1f425642010-11-11 03:21:53 +000010341 std::string PrettyValue = Value.toString(10);
10342 std::string PrettyTrunc = TruncatedValue.toString(10);
10343
10344 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10345 << PrettyValue << PrettyTrunc << OriginalInit->getType()
10346 << Init->getSourceRange();
10347
10348 return true;
10349}
10350
John McCalld2a53122010-11-09 23:24:47 +000010351/// Analyze the given simple or compound assignment for warning-worthy
10352/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010353static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +000010354 // Just recurse on the LHS.
10355 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10356
10357 // We want to recurse on the RHS as normal unless we're assigning to
10358 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +000010359 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010360 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +000010361 E->getOperatorLoc())) {
10362 // Recurse, ignoring any implicit conversions on the RHS.
10363 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10364 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +000010365 }
10366 }
10367
10368 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
Richard Smith6822bd72018-10-26 19:26:45 +000010369
JF Bastiene77b48b2018-09-10 20:42:56 +000010370 // Diagnose implicitly sequentially-consistent atomic assignment.
10371 if (E->getLHS()->getType()->isAtomicType())
10372 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
John McCalld2a53122010-11-09 23:24:47 +000010373}
10374
John McCall263a48b2010-01-04 23:31:57 +000010375/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Fangrui Song6907ce22018-07-30 19:24:48 +000010376static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010377 SourceLocation CContext, unsigned diag,
10378 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000010379 if (pruneControlFlow) {
10380 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10381 S.PDiag(diag)
10382 << SourceType << T << E->getSourceRange()
10383 << SourceRange(CContext));
10384 return;
10385 }
Douglas Gregor364f7db2011-03-12 00:14:31 +000010386 S.Diag(E->getExprLoc(), diag)
10387 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10388}
10389
Chandler Carruth7f3654f2011-04-05 06:47:57 +000010390/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010391static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10392 SourceLocation CContext,
10393 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +000010394 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +000010395}
10396
Richard Trieube234c32016-04-21 21:04:55 +000010397/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010398static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10399 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +000010400 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +000010401 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +000010402
10403 Expr *InnerE = E->IgnoreParenImpCasts();
10404 // We also want to warn on, e.g., "int i = -1.234"
10405 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10406 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10407 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10408
10409 const bool IsLiteral =
10410 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10411
10412 llvm::APFloat Value(0.0);
10413 bool IsConstant =
10414 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10415 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +000010416 return DiagnoseImpCast(S, E, T, CContext,
10417 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +000010418 }
10419
Chandler Carruth016ef402011-04-10 08:36:24 +000010420 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +000010421
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +000010422 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10423 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +000010424 llvm::APFloat::opStatus Result = Value.convertToInteger(
10425 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10426
10427 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +000010428 if (IsLiteral) return;
10429 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10430 PruneWarnings);
10431 }
10432
Erich Keanea4c48c62018-05-08 21:26:21 +000010433 // Conversion of a floating-point value to a non-bool integer where the
10434 // integral part cannot be represented by the integer type is undefined.
10435 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10436 return DiagnoseImpCast(
10437 S, E, T, CContext,
10438 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +000010439 : diag::warn_impcast_float_to_integer_out_of_range,
10440 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +000010441
Richard Trieube234c32016-04-21 21:04:55 +000010442 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +000010443 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +000010444 // Warn on floating point literal to integer.
10445 DiagID = diag::warn_impcast_literal_float_to_integer;
10446 } else if (IntegerValue == 0) {
10447 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
10448 return DiagnoseImpCast(S, E, T, CContext,
10449 diag::warn_impcast_float_integer, PruneWarnings);
10450 }
10451 // Warn on non-zero to zero conversion.
10452 DiagID = diag::warn_impcast_float_to_integer_zero;
10453 } else {
10454 if (IntegerValue.isUnsigned()) {
10455 if (!IntegerValue.isMaxValue()) {
10456 return DiagnoseImpCast(S, E, T, CContext,
10457 diag::warn_impcast_float_integer, PruneWarnings);
10458 }
10459 } else { // IntegerValue.isSigned()
10460 if (!IntegerValue.isMaxSignedValue() &&
10461 !IntegerValue.isMinSignedValue()) {
10462 return DiagnoseImpCast(S, E, T, CContext,
10463 diag::warn_impcast_float_integer, PruneWarnings);
10464 }
10465 }
10466 // Warn on evaluatable floating point expression to integer conversion.
10467 DiagID = diag::warn_impcast_float_to_integer;
10468 }
Chandler Carruth016ef402011-04-10 08:36:24 +000010469
Eli Friedman07185912013-08-29 23:44:43 +000010470 // FIXME: Force the precision of the source value down so we don't print
10471 // digits which are usually useless (we don't really care here if we
10472 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
10473 // would automatically print the shortest representation, but it's a bit
10474 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +000010475 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +000010476 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10477 precision = (precision * 59 + 195) / 196;
10478 Value.toString(PrettySourceValue, precision);
10479
David Blaikie9b88cc02012-05-15 17:18:27 +000010480 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +000010481 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +000010482 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +000010483 else
David Blaikie9b88cc02012-05-15 17:18:27 +000010484 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +000010485
Richard Trieube234c32016-04-21 21:04:55 +000010486 if (PruneWarnings) {
10487 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10488 S.PDiag(DiagID)
10489 << E->getType() << T.getUnqualifiedType()
10490 << PrettySourceValue << PrettyTargetValue
10491 << E->getSourceRange() << SourceRange(CContext));
10492 } else {
10493 S.Diag(E->getExprLoc(), DiagID)
10494 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10495 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10496 }
Chandler Carruth016ef402011-04-10 08:36:24 +000010497}
10498
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010499/// Analyze the given compound assignment for the possible losing of
10500/// floating-point precision.
10501static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10502 assert(isa<CompoundAssignOperator>(E) &&
10503 "Must be compound assignment operation");
10504 // Recurse on the LHS and RHS in here
10505 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10506 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10507
JF Bastiene77b48b2018-09-10 20:42:56 +000010508 if (E->getLHS()->getType()->isAtomicType())
10509 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10510
Nick Desaulniers1aaf5242018-08-13 16:38:07 +000010511 // Now check the outermost expression
10512 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10513 const auto *RBT = cast<CompoundAssignOperator>(E)
10514 ->getComputationResultType()
10515 ->getAs<BuiltinType>();
10516
10517 // The below checks assume source is floating point.
10518 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10519
10520 // If source is floating point but target is not.
10521 if (!ResultBT->isFloatingPoint())
10522 return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(),
10523 E->getExprLoc());
10524
10525 // If both source and target are floating points.
10526 // Builtin FP kinds are ordered by increasing FP rank.
10527 if (ResultBT->getKind() < RBT->getKind() &&
10528 // We don't want to warn for system macro.
10529 !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10530 // warn about dropping FP rank.
10531 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10532 diag::warn_impcast_float_result_precision);
10533}
10534
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010535static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10536 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +000010537 if (!Range.Width) return "0";
10538
10539 llvm::APSInt ValueInRange = Value;
10540 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +000010541 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +000010542 return ValueInRange.toString(10);
10543}
10544
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010545static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010546 if (!isa<ImplicitCastExpr>(Ex))
10547 return false;
10548
10549 Expr *InnerE = Ex->IgnoreParenImpCasts();
10550 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10551 const Type *Source =
10552 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10553 if (Target->isDependentType())
10554 return false;
10555
10556 const BuiltinType *FloatCandidateBT =
10557 dyn_cast<BuiltinType>(ToBool ? Source : Target);
10558 const Type *BoolCandidateType = ToBool ? Target : Source;
10559
10560 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10561 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10562}
10563
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010564static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10565 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010566 unsigned NumArgs = TheCall->getNumArgs();
10567 for (unsigned i = 0; i < NumArgs; ++i) {
10568 Expr *CurrA = TheCall->getArg(i);
10569 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10570 continue;
10571
10572 bool IsSwapped = ((i > 0) &&
10573 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10574 IsSwapped |= ((i < (NumArgs - 1)) &&
10575 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10576 if (IsSwapped) {
10577 // Warn on this floating-point to bool conversion.
10578 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10579 CurrA->getType(), CC,
10580 diag::warn_impcast_floating_point_to_bool);
10581 }
10582 }
10583}
10584
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010585static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10586 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +000010587 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10588 E->getExprLoc()))
10589 return;
10590
Richard Trieu09d6b802016-01-08 23:35:06 +000010591 // Don't warn on functions which have return type nullptr_t.
10592 if (isa<CallExpr>(E))
10593 return;
10594
Richard Trieu5b993502014-10-15 03:42:06 +000010595 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10596 const Expr::NullPointerConstantKind NullKind =
10597 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10598 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10599 return;
10600
10601 // Return if target type is a safe conversion.
10602 if (T->isAnyPointerType() || T->isBlockPointerType() ||
10603 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10604 return;
10605
10606 SourceLocation Loc = E->getSourceRange().getBegin();
10607
Richard Trieu0a5e1662016-02-13 00:58:53 +000010608 // Venture through the macro stacks to get to the source of macro arguments.
10609 // The new location is a better location than the complete location that was
10610 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +000010611 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10612 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +000010613
Richard Trieu5b993502014-10-15 03:42:06 +000010614 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +000010615 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10616 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10617 Loc, S.SourceMgr, S.getLangOpts());
10618 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +000010619 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +000010620 }
10621
10622 // Only warn if the null and context location are in the same macro expansion.
10623 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10624 return;
10625
10626 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010627 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +000010628 << FixItHint::CreateReplacement(Loc,
10629 S.getFixItZeroLiteralForType(T, Loc));
10630}
10631
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010632static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10633 ObjCArrayLiteral *ArrayLiteral);
10634
10635static void
10636checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10637 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000010638
10639/// Check a single element within a collection literal against the
10640/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010641static void checkObjCCollectionLiteralElement(Sema &S,
10642 QualType TargetElementType,
10643 Expr *Element,
10644 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010645 // Skip a bitcast to 'id' or qualified 'id'.
10646 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10647 if (ICE->getCastKind() == CK_BitCast &&
10648 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10649 Element = ICE->getSubExpr();
10650 }
10651
10652 QualType ElementType = Element->getType();
10653 ExprResult ElementResult(Element);
10654 if (ElementType->getAs<ObjCObjectPointerType>() &&
10655 S.CheckSingleAssignmentConstraints(TargetElementType,
10656 ElementResult,
10657 false, false)
10658 != Sema::Compatible) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010659 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10660 << ElementType << ElementKind << TargetElementType
10661 << Element->getSourceRange();
Douglas Gregor5054cb02015-07-07 03:58:22 +000010662 }
10663
10664 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10665 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10666 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10667 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10668}
10669
10670/// Check an Objective-C array literal being converted to the given
10671/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010672static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10673 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010674 if (!S.NSArrayDecl)
10675 return;
10676
10677 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10678 if (!TargetObjCPtr)
10679 return;
10680
10681 if (TargetObjCPtr->isUnspecialized() ||
10682 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10683 != S.NSArrayDecl->getCanonicalDecl())
10684 return;
10685
10686 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10687 if (TypeArgs.size() != 1)
10688 return;
10689
10690 QualType TargetElementType = TypeArgs[0];
10691 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10692 checkObjCCollectionLiteralElement(S, TargetElementType,
10693 ArrayLiteral->getElement(I),
10694 0);
10695 }
10696}
10697
10698/// Check an Objective-C dictionary literal being converted to the given
10699/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010700static void
10701checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10702 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010703 if (!S.NSDictionaryDecl)
10704 return;
10705
10706 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10707 if (!TargetObjCPtr)
10708 return;
10709
10710 if (TargetObjCPtr->isUnspecialized() ||
10711 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10712 != S.NSDictionaryDecl->getCanonicalDecl())
10713 return;
10714
10715 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10716 if (TypeArgs.size() != 2)
10717 return;
10718
10719 QualType TargetKeyType = TypeArgs[0];
10720 QualType TargetObjectType = TypeArgs[1];
10721 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10722 auto Element = DictionaryLiteral->getKeyValueElement(I);
10723 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10724 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10725 }
10726}
10727
Richard Trieufc404c72016-02-05 23:02:38 +000010728// Helper function to filter out cases for constant width constant conversion.
10729// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010730static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10731 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010732 // If initializing from a constant, and the constant starts with '0',
10733 // then it is a binary, octal, or hexadecimal. Allow these constants
10734 // to fill all the bits, even if there is a sign change.
10735 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10736 const char FirstLiteralCharacter =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010737 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
Richard Trieufc404c72016-02-05 23:02:38 +000010738 if (FirstLiteralCharacter == '0')
10739 return false;
10740 }
10741
10742 // If the CC location points to a '{', and the type is char, then assume
10743 // assume it is an array initialization.
10744 if (CC.isValid() && T->isCharType()) {
10745 const char FirstContextCharacter =
10746 S.getSourceManager().getCharacterData(CC)[0];
10747 if (FirstContextCharacter == '{')
10748 return false;
10749 }
10750
10751 return true;
10752}
10753
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010754static void
10755CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10756 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010757 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010758
John McCallcc7e5bf2010-05-06 08:58:33 +000010759 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10760 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10761 if (Source == Target) return;
10762 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010763
Chandler Carruthc22845a2011-07-26 05:40:03 +000010764 // If the conversion context location is invalid don't complain. We also
10765 // don't want to emit a warning if the issue occurs from the expansion of
10766 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10767 // delay this check as long as possible. Once we detect we are in that
10768 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010769 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010770 return;
10771
JF Bastiene77b48b2018-09-10 20:42:56 +000010772 if (Source->isAtomicType())
10773 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10774
Richard Trieu021baa32011-09-23 20:10:00 +000010775 // Diagnose implicit casts to bool.
10776 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10777 if (isa<StringLiteral>(E))
10778 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010779 // and expressions, for instance, assert(0 && "error here"), are
10780 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010781 return DiagnoseImpCast(S, E, T, CC,
10782 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010783 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10784 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10785 // This covers the literal expressions that evaluate to Objective-C
10786 // objects.
10787 return DiagnoseImpCast(S, E, T, CC,
10788 diag::warn_impcast_objective_c_literal_to_bool);
10789 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010790 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10791 // Warn on pointer to bool conversion that is always true.
10792 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10793 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010794 }
Richard Trieu021baa32011-09-23 20:10:00 +000010795 }
John McCall263a48b2010-01-04 23:31:57 +000010796
Douglas Gregor5054cb02015-07-07 03:58:22 +000010797 // Check implicit casts from Objective-C collection literals to specialized
10798 // collection types, e.g., NSArray<NSString *> *.
10799 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10800 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10801 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10802 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10803
John McCall263a48b2010-01-04 23:31:57 +000010804 // Strip vector types.
10805 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010806 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010807 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010808 return;
John McCallacf0ee52010-10-08 02:01:28 +000010809 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010810 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010811
Chris Lattneree7286f2011-06-14 04:51:15 +000010812 // If the vector cast is cast between two vectors of the same size, it is
10813 // a bitcast, not a conversion.
10814 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10815 return;
John McCall263a48b2010-01-04 23:31:57 +000010816
10817 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10818 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10819 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010820 if (auto VecTy = dyn_cast<VectorType>(Target))
10821 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010822
10823 // Strip complex types.
10824 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010825 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010826 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010827 return;
10828
Tim Northover02416372017-08-08 23:18:05 +000010829 return DiagnoseImpCast(S, E, T, CC,
10830 S.getLangOpts().CPlusPlus
10831 ? diag::err_impcast_complex_scalar
10832 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010833 }
John McCall263a48b2010-01-04 23:31:57 +000010834
10835 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10836 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10837 }
10838
10839 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10840 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10841
10842 // If the source is floating point...
10843 if (SourceBT && SourceBT->isFloatingPoint()) {
10844 // ...and the target is floating point...
10845 if (TargetBT && TargetBT->isFloatingPoint()) {
10846 // ...then warn if we're dropping FP rank.
10847
10848 // Builtin FP kinds are ordered by increasing FP rank.
10849 if (SourceBT->getKind() > TargetBT->getKind()) {
10850 // Don't warn about float constants that are precisely
10851 // representable in the target type.
10852 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010853 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010854 // Value might be a float, a float vector, or a float complex.
10855 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010856 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10857 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010858 return;
10859 }
10860
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010861 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010862 return;
10863
John McCallacf0ee52010-10-08 02:01:28 +000010864 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010865 }
10866 // ... or possibly if we're increasing rank, too
10867 else if (TargetBT->getKind() > SourceBT->getKind()) {
10868 if (S.SourceMgr.isInSystemMacro(CC))
10869 return;
10870
10871 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010872 }
10873 return;
10874 }
10875
Richard Trieube234c32016-04-21 21:04:55 +000010876 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010877 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010878 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010879 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010880
Richard Trieube234c32016-04-21 21:04:55 +000010881 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010882 }
John McCall263a48b2010-01-04 23:31:57 +000010883
Richard Smith54894fd2015-12-30 01:06:52 +000010884 // Detect the case where a call result is converted from floating-point to
10885 // to bool, and the final argument to the call is converted from bool, to
10886 // discover this typo:
10887 //
10888 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10889 //
10890 // FIXME: This is an incredibly special case; is there some more general
10891 // way to detect this class of misplaced-parentheses bug?
10892 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010893 // Check last argument of function call to see if it is an
10894 // implicit cast from a type matching the type the result
10895 // is being cast to.
10896 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010897 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010898 Expr *LastA = CEx->getArg(NumArgs - 1);
10899 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010900 if (isa<ImplicitCastExpr>(LastA) &&
10901 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010902 // Warn on this floating-point to bool conversion
10903 DiagnoseImpCast(S, E, T, CC,
10904 diag::warn_impcast_floating_point_to_bool);
10905 }
10906 }
10907 }
John McCall263a48b2010-01-04 23:31:57 +000010908 return;
10909 }
10910
Richard Trieu5b993502014-10-15 03:42:06 +000010911 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010912
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010913 S.DiscardMisalignedMemberAddress(Target, E);
10914
David Blaikie9366d2b2012-06-19 21:19:06 +000010915 if (!Source->isIntegerType() || !Target->isIntegerType())
10916 return;
10917
David Blaikie7555b6a2012-05-15 16:56:36 +000010918 // TODO: remove this early return once the false positives for constant->bool
10919 // in templates, macros, etc, are reduced or removed.
10920 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10921 return;
10922
John McCallcc7e5bf2010-05-06 08:58:33 +000010923 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010924 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010925
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010926 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010927 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010928 // TODO: this should happen for bitfield stores, too.
10929 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010930 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010931 if (S.SourceMgr.isInSystemMacro(CC))
10932 return;
10933
John McCall18a2c2c2010-11-09 22:22:12 +000010934 std::string PrettySourceValue = Value.toString(10);
10935 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010936
Ted Kremenek33ba9952011-10-22 02:37:33 +000010937 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10938 S.PDiag(diag::warn_impcast_integer_precision_constant)
10939 << PrettySourceValue << PrettyTargetValue
10940 << E->getType() << T << E->getSourceRange()
10941 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010942 return;
10943 }
10944
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010945 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10946 if (S.SourceMgr.isInSystemMacro(CC))
10947 return;
10948
David Blaikie9455da02012-04-12 22:40:54 +000010949 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010950 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10951 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010952 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010953 }
10954
David Bolvanskycf7d2252018-10-02 06:02:30 +000010955 if (TargetRange.Width > SourceRange.Width) {
10956 if (auto *UO = dyn_cast<UnaryOperator>(E))
10957 if (UO->getOpcode() == UO_Minus)
10958 if (Source->isUnsignedIntegerType()) {
10959 if (Target->isUnsignedIntegerType())
10960 return DiagnoseImpCast(S, E, T, CC,
10961 diag::warn_impcast_high_order_zero_bits);
10962 if (Target->isSignedIntegerType())
10963 return DiagnoseImpCast(S, E, T, CC,
10964 diag::warn_impcast_nonnegative_result);
10965 }
10966 }
10967
Richard Trieudcb55572016-01-29 23:51:16 +000010968 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10969 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10970 // Warn when doing a signed to signed conversion, warn if the positive
10971 // source value is exactly the width of the target type, which will
10972 // cause a negative value to be stored.
10973
10974 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010975 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10976 !S.SourceMgr.isInSystemMacro(CC)) {
10977 if (isSameWidthConstantConversion(S, E, T, CC)) {
10978 std::string PrettySourceValue = Value.toString(10);
10979 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010980
Richard Trieufc404c72016-02-05 23:02:38 +000010981 S.DiagRuntimeBehavior(
10982 E->getExprLoc(), E,
10983 S.PDiag(diag::warn_impcast_integer_precision_constant)
10984 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10985 << E->getSourceRange() << clang::SourceRange(CC));
10986 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010987 }
10988 }
Richard Trieufc404c72016-02-05 23:02:38 +000010989
Richard Trieudcb55572016-01-29 23:51:16 +000010990 // Fall through for non-constants to give a sign conversion warning.
10991 }
10992
John McCallcc7e5bf2010-05-06 08:58:33 +000010993 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10994 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10995 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010996 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010997 return;
10998
John McCallcc7e5bf2010-05-06 08:58:33 +000010999 unsigned DiagID = diag::warn_impcast_integer_sign;
11000
11001 // Traditionally, gcc has warned about this under -Wsign-compare.
11002 // We also want to warn about it in -Wconversion.
11003 // So if -Wconversion is off, use a completely identical diagnostic
11004 // in the sign-compare group.
Fangrui Song6907ce22018-07-30 19:24:48 +000011005 // The conditional-checking code will
John McCallcc7e5bf2010-05-06 08:58:33 +000011006 if (ICContext) {
11007 DiagID = diag::warn_impcast_integer_sign_conditional;
11008 *ICContext = true;
11009 }
11010
John McCallacf0ee52010-10-08 02:01:28 +000011011 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000011012 }
11013
Douglas Gregora78f1932011-02-22 02:45:07 +000011014 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000011015 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11016 // type, to give us better diagnostics.
11017 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000011018 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000011019 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11020 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11021 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11022 SourceType = S.Context.getTypeDeclType(Enum);
11023 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11024 }
11025 }
Fangrui Song6907ce22018-07-30 19:24:48 +000011026
Douglas Gregora78f1932011-02-22 02:45:07 +000011027 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11028 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000011029 if (SourceEnum->getDecl()->hasNameForLinkage() &&
11030 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011031 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000011032 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011033 return;
11034
Fangrui Song6907ce22018-07-30 19:24:48 +000011035 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000011036 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000011037 }
John McCall263a48b2010-01-04 23:31:57 +000011038}
11039
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011040static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11041 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011042
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011043static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11044 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011045 E = E->IgnoreParenImpCasts();
11046
11047 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000011048 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011049
John McCallacf0ee52010-10-08 02:01:28 +000011050 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011051 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000011052 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000011053}
11054
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011055static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11056 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000011057 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000011058
11059 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000011060 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11061 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000011062
11063 // If -Wconversion would have warned about either of the candidates
11064 // for a signedness conversion to the context type...
11065 if (!Suspicious) return;
11066
11067 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011068 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000011069 return;
11070
John McCallcc7e5bf2010-05-06 08:58:33 +000011071 // ...then check whether it would have warned about either of the
11072 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000011073 if (E->getType() == T) return;
Fangrui Song6907ce22018-07-30 19:24:48 +000011074
Richard Trieubb43dec2011-07-21 02:46:28 +000011075 Suspicious = false;
11076 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11077 E->getType(), CC, &Suspicious);
11078 if (!Suspicious)
11079 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000011080 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000011081}
11082
JF Bastiene77b48b2018-09-10 20:42:56 +000011083/// Check conversion of given expression to boolean.
Richard Trieu65724892014-11-15 06:37:39 +000011084/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011085static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000011086 if (S.getLangOpts().Bool)
11087 return;
JF Bastiene77b48b2018-09-10 20:42:56 +000011088 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11089 return;
Richard Trieu65724892014-11-15 06:37:39 +000011090 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11091}
11092
John McCallcc7e5bf2010-05-06 08:58:33 +000011093/// AnalyzeImplicitConversions - Find and report any interesting
11094/// implicit conversions in the given expression. There are a couple
11095/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011096static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11097 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000011098 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000011099 Expr *E = OrigE->IgnoreParenImpCasts();
11100
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000011101 if (E->isTypeDependent() || E->isValueDependent())
11102 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011103
John McCallcc7e5bf2010-05-06 08:58:33 +000011104 // For conditional operators, we analyze the arguments as if they
11105 // were being fed directly into the output.
11106 if (isa<ConditionalOperator>(E)) {
11107 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000011108 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000011109 return;
11110 }
11111
Hans Wennborgf4ad2322012-08-28 15:44:30 +000011112 // Check implicit argument conversions for function calls.
11113 if (CallExpr *Call = dyn_cast<CallExpr>(E))
11114 CheckImplicitArgumentConversions(S, Call, CC);
11115
John McCallcc7e5bf2010-05-06 08:58:33 +000011116 // Go ahead and check any implicit conversions we might have skipped.
11117 // The non-canonical typecheck is just an optimization;
11118 // CheckImplicitConversion will filter out dead implicit conversions.
11119 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000011120 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011121
11122 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000011123
11124 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11125 // The bound subexpressions in a PseudoObjectExpr are not reachable
11126 // as transitive children.
11127 // FIXME: Use a more uniform representation for this.
11128 for (auto *SE : POE->semantics())
11129 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11130 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000011131 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000011132
John McCallcc7e5bf2010-05-06 08:58:33 +000011133 // Skip past explicit casts.
JF Bastiene77b48b2018-09-10 20:42:56 +000011134 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11135 E = CE->getSubExpr()->IgnoreParenImpCasts();
11136 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11137 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
John McCallacf0ee52010-10-08 02:01:28 +000011138 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011139 }
11140
John McCalld2a53122010-11-09 23:24:47 +000011141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11142 // Do a somewhat different check with comparison operators.
11143 if (BO->isComparisonOp())
11144 return AnalyzeComparison(S, BO);
11145
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000011146 // And with simple assignments.
11147 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000011148 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000011149 // And with compound assignments.
11150 if (BO->isAssignmentOp())
11151 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000011152 }
John McCallcc7e5bf2010-05-06 08:58:33 +000011153
11154 // These break the otherwise-useful invariant below. Fortunately,
11155 // we don't really need to recurse into them, because any internal
11156 // expressions should have been analyzed already when they were
11157 // built into statements.
11158 if (isa<StmtExpr>(E)) return;
11159
11160 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000011161 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000011162
11163 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000011164 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000011165 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000011166 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000011167 for (Stmt *SubStmt : E->children()) {
11168 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000011169 if (!ChildExpr)
11170 continue;
11171
Richard Trieu955231d2014-01-25 01:10:35 +000011172 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000011173 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000011174 // Ignore checking string literals that are in logical and operators.
11175 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000011176 continue;
11177 AnalyzeImplicitConversions(S, ChildExpr, CC);
11178 }
Richard Trieu791b86e2014-11-19 06:08:18 +000011179
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000011180 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000011181 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11182 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000011183 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000011184
11185 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11186 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000011187 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000011188 }
Richard Trieu791b86e2014-11-19 06:08:18 +000011189
JF Bastiene77b48b2018-09-10 20:42:56 +000011190 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11191 if (U->getOpcode() == UO_LNot) {
Richard Trieu65724892014-11-15 06:37:39 +000011192 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
JF Bastiene77b48b2018-09-10 20:42:56 +000011193 } else if (U->getOpcode() != UO_AddrOf) {
11194 if (U->getSubExpr()->getType()->isAtomicType())
11195 S.Diag(U->getSubExpr()->getBeginLoc(),
11196 diag::warn_atomic_implicit_seq_cst);
11197 }
11198 }
John McCallcc7e5bf2010-05-06 08:58:33 +000011199}
11200
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011201/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011202static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11203 // Taking into account implicit conversions,
11204 // allow any integer.
11205 if (!E->getType()->isIntegerType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011206 S.Diag(E->getBeginLoc(),
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011207 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11208 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011209 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011210 // Potentially emit standard warnings for implicit conversions if enabled
11211 // using -Wconversion.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011212 CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000011213 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011214}
11215
Richard Trieuc1888e02014-06-28 23:25:37 +000011216// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11217// Returns true when emitting a warning about taking the address of a reference.
11218static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000011219 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000011220 E = E->IgnoreParenImpCasts();
11221
11222 const FunctionDecl *FD = nullptr;
11223
11224 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11225 if (!DRE->getDecl()->getType()->isReferenceType())
11226 return false;
11227 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11228 if (!M->getMemberDecl()->getType()->isReferenceType())
11229 return false;
11230 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000011231 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000011232 return false;
11233 FD = Call->getDirectCallee();
11234 } else {
11235 return false;
11236 }
11237
11238 SemaRef.Diag(E->getExprLoc(), PD);
11239
11240 // If possible, point to location of function.
11241 if (FD) {
11242 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11243 }
11244
11245 return true;
11246}
11247
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011248// Returns true if the SourceLocation is expanded from any macro body.
11249// Returns false if the SourceLocation is invalid, is from not in a macro
11250// expansion, or is from expanded from a top-level macro argument.
11251static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11252 if (Loc.isInvalid())
11253 return false;
11254
11255 while (Loc.isMacroID()) {
11256 if (SM.isMacroBodyExpansion(Loc))
11257 return true;
11258 Loc = SM.getImmediateMacroCallerLoc(Loc);
11259 }
11260
11261 return false;
11262}
11263
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011264/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000011265/// \param E the expression containing the pointer
11266/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11267/// compared to a null pointer
11268/// \param IsEqual True when the comparison is equal to a null pointer
11269/// \param Range Extra SourceRange to highlight in the diagnostic
11270void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11271 Expr::NullPointerConstantKind NullKind,
11272 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000011273 if (!E)
11274 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011275
11276 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011277 if (E->getExprLoc().isMacroID()) {
11278 const SourceManager &SM = getSourceManager();
11279 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11280 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000011281 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000011282 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000011283 E = E->IgnoreImpCasts();
11284
11285 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11286
Richard Trieuf7432752014-06-06 21:39:26 +000011287 if (isa<CXXThisExpr>(E)) {
11288 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11289 : diag::warn_this_bool_conversion;
11290 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11291 return;
11292 }
11293
Richard Trieu3bb8b562014-02-26 02:36:06 +000011294 bool IsAddressOf = false;
11295
11296 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11297 if (UO->getOpcode() != UO_AddrOf)
11298 return;
11299 IsAddressOf = true;
11300 E = UO->getSubExpr();
11301 }
11302
Richard Trieuc1888e02014-06-28 23:25:37 +000011303 if (IsAddressOf) {
11304 unsigned DiagID = IsCompare
11305 ? diag::warn_address_of_reference_null_compare
11306 : diag::warn_address_of_reference_bool_conversion;
11307 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11308 << IsEqual;
11309 if (CheckForReference(*this, E, PD)) {
11310 return;
11311 }
11312 }
11313
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011314 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11315 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000011316 std::string Str;
11317 llvm::raw_string_ostream S(Str);
11318 E->printPretty(S, nullptr, getPrintingPolicy());
11319 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11320 : diag::warn_cast_nonnull_to_bool;
11321 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11322 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011323 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000011324 };
11325
11326 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11327 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11328 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011329 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11330 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000011331 return;
11332 }
11333 }
11334 }
11335
Richard Trieu3bb8b562014-02-26 02:36:06 +000011336 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000011337 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011338 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11339 D = R->getDecl();
11340 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11341 D = M->getMemberDecl();
11342 }
11343
11344 // Weak Decls can be null.
11345 if (!D || D->isWeak())
11346 return;
George Burgess IV850269a2015-12-08 22:02:00 +000011347
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011348 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000011349 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11350 if (getCurFunction() &&
11351 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011352 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11353 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000011354 return;
11355 }
11356
11357 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000011358 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000011359 assert(ParamIter != FD->param_end());
11360 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11361
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011362 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11363 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011364 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000011365 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011366 }
George Burgess IV850269a2015-12-08 22:02:00 +000011367
Joel E. Denny81508102018-03-13 14:51:22 +000011368 for (const ParamIdx &ArgNo : NonNull->args()) {
11369 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000011370 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011371 return;
11372 }
George Burgess IV850269a2015-12-08 22:02:00 +000011373 }
11374 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000011375 }
11376 }
George Burgess IV850269a2015-12-08 22:02:00 +000011377 }
11378
Richard Trieu3bb8b562014-02-26 02:36:06 +000011379 QualType T = D->getType();
11380 const bool IsArray = T->isArrayType();
11381 const bool IsFunction = T->isFunctionType();
11382
Richard Trieuc1888e02014-06-28 23:25:37 +000011383 // Address of function is used to silence the function warning.
11384 if (IsAddressOf && IsFunction) {
11385 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011386 }
11387
11388 // Found nothing.
11389 if (!IsAddressOf && !IsFunction && !IsArray)
11390 return;
11391
11392 // Pretty print the expression for the diagnostic.
11393 std::string Str;
11394 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000011395 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000011396
11397 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11398 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000011399 enum {
11400 AddressOf,
11401 FunctionPointer,
11402 ArrayPointer
11403 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000011404 if (IsAddressOf)
11405 DiagType = AddressOf;
11406 else if (IsFunction)
11407 DiagType = FunctionPointer;
11408 else if (IsArray)
11409 DiagType = ArrayPointer;
11410 else
11411 llvm_unreachable("Could not determine diagnostic.");
11412 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11413 << Range << IsEqual;
11414
11415 if (!IsFunction)
11416 return;
11417
11418 // Suggest '&' to silence the function warning.
11419 Diag(E->getExprLoc(), diag::note_function_warning_silence)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011420 << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
Richard Trieu3bb8b562014-02-26 02:36:06 +000011421
11422 // Check to see if '()' fixit should be emitted.
11423 QualType ReturnType;
11424 UnresolvedSet<4> NonTemplateOverloads;
11425 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11426 if (ReturnType.isNull())
11427 return;
11428
11429 if (IsCompare) {
11430 // There are two cases here. If there is null constant, the only suggest
11431 // for a pointer return type. If the null is 0, then suggest if the return
11432 // type is a pointer or an integer type.
11433 if (!ReturnType->isPointerType()) {
11434 if (NullKind == Expr::NPCK_ZeroExpression ||
11435 NullKind == Expr::NPCK_ZeroLiteral) {
11436 if (!ReturnType->isIntegerType())
11437 return;
11438 } else {
11439 return;
11440 }
11441 }
11442 } else { // !IsCompare
11443 // For function to bool, only suggest if the function pointer has bool
11444 // return type.
11445 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11446 return;
11447 }
11448 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Kelly1c301dc2018-08-09 21:09:38 +000011449 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000011450}
11451
John McCallcc7e5bf2010-05-06 08:58:33 +000011452/// Diagnoses "dangerous" implicit conversions within the given
11453/// expression (which is a full expression). Implements -Wconversion
11454/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000011455///
11456/// \param CC the "context" location of the implicit conversion, i.e.
11457/// the most location of the syntactic entity requiring the implicit
11458/// conversion
11459void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000011460 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000011461 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000011462 return;
11463
11464 // Don't diagnose for value- or type-dependent expressions.
11465 if (E->isTypeDependent() || E->isValueDependent())
11466 return;
11467
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011468 // Check for array bounds violations in cases where the check isn't triggered
11469 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11470 // ArraySubscriptExpr is on the RHS of a variable initialization.
11471 CheckArrayAccess(E);
11472
John McCallacf0ee52010-10-08 02:01:28 +000011473 // This is not the right CC for (e.g.) a variable initialization.
11474 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000011475}
11476
Richard Trieu65724892014-11-15 06:37:39 +000011477/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11478/// Input argument E is a logical expression.
11479void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11480 ::CheckBoolLikeConversion(*this, E, CC);
11481}
11482
Richard Smith9f7df0c2017-06-26 23:19:32 +000011483/// Diagnose when expression is an integer constant expression and its evaluation
11484/// results in integer overflow
11485void Sema::CheckForIntOverflow (Expr *E) {
11486 // Use a work list to deal with nested struct initializers.
11487 SmallVector<Expr *, 2> Exprs(1, E);
11488
11489 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011490 Expr *OriginalE = Exprs.pop_back_val();
11491 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000011492
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011493 if (isa<BinaryOperator>(E)) {
11494 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000011495 continue;
11496 }
11497
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011498 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000011499 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000011500 else if (isa<ObjCBoxedExpr>(OriginalE))
11501 E->EvaluateForOverflow(Context);
11502 else if (auto Call = dyn_cast<CallExpr>(E))
11503 Exprs.append(Call->arg_begin(), Call->arg_end());
11504 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11505 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000011506 } while (!Exprs.empty());
11507}
11508
Richard Smithc406cb72013-01-17 01:17:56 +000011509namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011510
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011511/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000011512/// same object.
11513class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011514 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000011515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011516 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000011517 /// unsequenced if one is an ancestor or a descendent of the other. When we
11518 /// finish processing an expression with sequencing, such as a comma
11519 /// expression, we fold its tree nodes into its parent, since they are
11520 /// unsequenced with respect to nodes we will visit later.
11521 class SequenceTree {
11522 struct Value {
11523 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11524 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000011525 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000011526 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011527 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000011528
11529 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011530 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000011531 /// to some other region.
11532 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000011533 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011534
11535 unsigned Index = 0;
11536
11537 explicit Seq(unsigned N) : Index(N) {}
11538
Richard Smithc406cb72013-01-17 01:17:56 +000011539 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011540 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000011541 };
11542
11543 SequenceTree() { Values.push_back(Value(0)); }
11544 Seq root() const { return Seq(0); }
11545
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011546 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000011547 /// subset of \p Parent. This sequence of operations is sequenced with
11548 /// respect to other children of \p Parent.
11549 Seq allocate(Seq Parent) {
11550 Values.push_back(Value(Parent.Index));
11551 return Seq(Values.size() - 1);
11552 }
11553
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011554 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000011555 void merge(Seq S) {
11556 Values[S.Index].Merged = true;
11557 }
11558
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011559 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000011560 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11561 /// should have been merged into its parent as appropriate.
11562 bool isUnsequenced(Seq Cur, Seq Old) {
11563 unsigned C = representative(Cur.Index);
11564 unsigned Target = representative(Old.Index);
11565 while (C >= Target) {
11566 if (C == Target)
11567 return true;
11568 C = Values[C].Parent;
11569 }
11570 return false;
11571 }
11572
11573 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011574 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000011575 unsigned representative(unsigned K) {
11576 if (Values[K].Merged)
11577 // Perform path compression as we go.
11578 return Values[K].Parent = representative(Values[K].Parent);
11579 return K;
11580 }
11581 };
11582
11583 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011584 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000011585
11586 /// Different flavors of object usage which we track. We only track the
11587 /// least-sequenced usage of each kind.
11588 enum UsageKind {
11589 /// A read of an object. Multiple unsequenced reads are OK.
11590 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011591
Richard Smithc406cb72013-01-17 01:17:56 +000011592 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000011593 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000011594 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011595
Richard Smithc406cb72013-01-17 01:17:56 +000011596 /// A modification of an object which is not sequenced before the value
11597 /// computation of the expression, such as n++.
11598 UK_ModAsSideEffect,
11599
11600 UK_Count = UK_ModAsSideEffect + 1
11601 };
11602
11603 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011604 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011605 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011606
11607 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000011608 };
11609
11610 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000011611 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011612
Richard Smithc406cb72013-01-17 01:17:56 +000011613 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011614 bool Diagnosed = false;
11615
11616 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000011617 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011618 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000011619
11620 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011621
Richard Smithc406cb72013-01-17 01:17:56 +000011622 /// Sequenced regions within the expression.
11623 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011624
Richard Smithc406cb72013-01-17 01:17:56 +000011625 /// Declaration modifications and references which we have seen.
11626 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011627
Richard Smithc406cb72013-01-17 01:17:56 +000011628 /// The region we are currently within.
11629 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011630
Richard Smithc406cb72013-01-17 01:17:56 +000011631 /// Filled in with declarations which were modified as a side-effect
11632 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011633 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11634
Richard Smithd33f5202013-01-17 23:18:09 +000011635 /// Expressions to check later. We defer checking these to reduce
11636 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011637 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000011638
11639 /// RAII object wrapping the visitation of a sequenced subexpression of an
11640 /// expression. At the end of this process, the side-effects of the evaluation
11641 /// become sequenced with respect to the value computation of the result, so
11642 /// we downgrade any UK_ModAsSideEffect within the evaluation to
11643 /// UK_ModAsValue.
11644 struct SequencedSubexpression {
11645 SequencedSubexpression(SequenceChecker &Self)
11646 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11647 Self.ModAsSideEffect = &ModAsSideEffect;
11648 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011649
Richard Smithc406cb72013-01-17 01:17:56 +000011650 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000011651 for (auto &M : llvm::reverse(ModAsSideEffect)) {
11652 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000011653 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000011654 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11655 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000011656 }
11657 Self.ModAsSideEffect = OldModAsSideEffect;
11658 }
11659
11660 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011661 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011662 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000011663 };
11664
Richard Smith40238f02013-06-20 22:21:56 +000011665 /// RAII object wrapping the visitation of a subexpression which we might
11666 /// choose to evaluate as a constant. If any subexpression is evaluated and
11667 /// found to be non-constant, this allows us to suppress the evaluation of
11668 /// the outer expression.
11669 class EvaluationTracker {
11670 public:
11671 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011672 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000011673 Self.EvalTracker = this;
11674 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011675
Richard Smith40238f02013-06-20 22:21:56 +000011676 ~EvaluationTracker() {
11677 Self.EvalTracker = Prev;
11678 if (Prev)
11679 Prev->EvalOK &= EvalOK;
11680 }
11681
11682 bool evaluate(const Expr *E, bool &Result) {
11683 if (!EvalOK || E->isValueDependent())
11684 return false;
11685 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11686 return EvalOK;
11687 }
11688
11689 private:
11690 SequenceChecker &Self;
11691 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011692 bool EvalOK = true;
11693 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000011694
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011695 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000011696 /// if any.
11697 Object getObject(Expr *E, bool Mod) const {
11698 E = E->IgnoreParenCasts();
11699 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11700 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11701 return getObject(UO->getSubExpr(), Mod);
11702 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11703 if (BO->getOpcode() == BO_Comma)
11704 return getObject(BO->getRHS(), Mod);
11705 if (Mod && BO->isAssignmentOp())
11706 return getObject(BO->getLHS(), Mod);
11707 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11708 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11709 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11710 return ME->getMemberDecl();
11711 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11712 // FIXME: If this is a reference, map through to its value.
11713 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000011714 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011715 }
11716
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011717 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000011718 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11719 Usage &U = UI.Uses[UK];
11720 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11721 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11722 ModAsSideEffect->push_back(std::make_pair(O, U));
11723 U.Use = Ref;
11724 U.Seq = Region;
11725 }
11726 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011727
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011728 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000011729 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11730 bool IsModMod) {
11731 if (UI.Diagnosed)
11732 return;
11733
11734 const Usage &U = UI.Uses[OtherKind];
11735 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11736 return;
11737
11738 Expr *Mod = U.Use;
11739 Expr *ModOrUse = Ref;
11740 if (OtherKind == UK_Use)
11741 std::swap(Mod, ModOrUse);
11742
11743 SemaRef.Diag(Mod->getExprLoc(),
11744 IsModMod ? diag::warn_unsequenced_mod_mod
11745 : diag::warn_unsequenced_mod_use)
11746 << O << SourceRange(ModOrUse->getExprLoc());
11747 UI.Diagnosed = true;
11748 }
11749
11750 void notePreUse(Object O, Expr *Use) {
11751 UsageInfo &U = UsageMap[O];
11752 // Uses conflict with other modifications.
11753 checkUsage(O, U, Use, UK_ModAsValue, false);
11754 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011755
Richard Smithc406cb72013-01-17 01:17:56 +000011756 void notePostUse(Object O, Expr *Use) {
11757 UsageInfo &U = UsageMap[O];
11758 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11759 addUsage(U, O, Use, UK_Use);
11760 }
11761
11762 void notePreMod(Object O, Expr *Mod) {
11763 UsageInfo &U = UsageMap[O];
11764 // Modifications conflict with other modifications and with uses.
11765 checkUsage(O, U, Mod, UK_ModAsValue, true);
11766 checkUsage(O, U, Mod, UK_Use, false);
11767 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011768
Richard Smithc406cb72013-01-17 01:17:56 +000011769 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11770 UsageInfo &U = UsageMap[O];
11771 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11772 addUsage(U, O, Use, UK);
11773 }
11774
11775public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011776 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011777 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011778 Visit(E);
11779 }
11780
11781 void VisitStmt(Stmt *S) {
11782 // Skip all statements which aren't expressions for now.
11783 }
11784
11785 void VisitExpr(Expr *E) {
11786 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011787 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011788 }
11789
11790 void VisitCastExpr(CastExpr *E) {
11791 Object O = Object();
11792 if (E->getCastKind() == CK_LValueToRValue)
11793 O = getObject(E->getSubExpr(), false);
11794
11795 if (O)
11796 notePreUse(O, E);
11797 VisitExpr(E);
11798 if (O)
11799 notePostUse(O, E);
11800 }
11801
11802 void VisitBinComma(BinaryOperator *BO) {
11803 // C++11 [expr.comma]p1:
11804 // Every value computation and side effect associated with the left
11805 // expression is sequenced before every value computation and side
11806 // effect associated with the right expression.
11807 SequenceTree::Seq LHS = Tree.allocate(Region);
11808 SequenceTree::Seq RHS = Tree.allocate(Region);
11809 SequenceTree::Seq OldRegion = Region;
11810
11811 {
11812 SequencedSubexpression SeqLHS(*this);
11813 Region = LHS;
11814 Visit(BO->getLHS());
11815 }
11816
11817 Region = RHS;
11818 Visit(BO->getRHS());
11819
11820 Region = OldRegion;
11821
11822 // Forget that LHS and RHS are sequenced. They are both unsequenced
11823 // with respect to other stuff.
11824 Tree.merge(LHS);
11825 Tree.merge(RHS);
11826 }
11827
11828 void VisitBinAssign(BinaryOperator *BO) {
11829 // The modification is sequenced after the value computation of the LHS
11830 // and RHS, so check it before inspecting the operands and update the
11831 // map afterwards.
11832 Object O = getObject(BO->getLHS(), true);
11833 if (!O)
11834 return VisitExpr(BO);
11835
11836 notePreMod(O, BO);
11837
11838 // C++11 [expr.ass]p7:
11839 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11840 // only once.
11841 //
11842 // Therefore, for a compound assignment operator, O is considered used
11843 // everywhere except within the evaluation of E1 itself.
11844 if (isa<CompoundAssignOperator>(BO))
11845 notePreUse(O, BO);
11846
11847 Visit(BO->getLHS());
11848
11849 if (isa<CompoundAssignOperator>(BO))
11850 notePostUse(O, BO);
11851
11852 Visit(BO->getRHS());
11853
Richard Smith83e37bee2013-06-26 23:16:51 +000011854 // C++11 [expr.ass]p1:
11855 // the assignment is sequenced [...] before the value computation of the
11856 // assignment expression.
11857 // C11 6.5.16/3 has no such rule.
11858 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11859 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011860 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011861
Richard Smithc406cb72013-01-17 01:17:56 +000011862 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11863 VisitBinAssign(CAO);
11864 }
11865
11866 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11867 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11868 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11869 Object O = getObject(UO->getSubExpr(), true);
11870 if (!O)
11871 return VisitExpr(UO);
11872
11873 notePreMod(O, UO);
11874 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011875 // C++11 [expr.pre.incr]p1:
11876 // the expression ++x is equivalent to x+=1
11877 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11878 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011879 }
11880
11881 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11882 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11883 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11884 Object O = getObject(UO->getSubExpr(), true);
11885 if (!O)
11886 return VisitExpr(UO);
11887
11888 notePreMod(O, UO);
11889 Visit(UO->getSubExpr());
11890 notePostMod(O, UO, UK_ModAsSideEffect);
11891 }
11892
11893 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11894 void VisitBinLOr(BinaryOperator *BO) {
11895 // The side-effects of the LHS of an '&&' are sequenced before the
11896 // value computation of the RHS, and hence before the value computation
11897 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11898 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011899 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011900 {
11901 SequencedSubexpression Sequenced(*this);
11902 Visit(BO->getLHS());
11903 }
11904
11905 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011906 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011907 if (!Result)
11908 Visit(BO->getRHS());
11909 } else {
11910 // Check for unsequenced operations in the RHS, treating it as an
11911 // entirely separate evaluation.
11912 //
11913 // FIXME: If there are operations in the RHS which are unsequenced
11914 // with respect to operations outside the RHS, and those operations
11915 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011916 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011917 }
Richard Smithc406cb72013-01-17 01:17:56 +000011918 }
11919 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011920 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011921 {
11922 SequencedSubexpression Sequenced(*this);
11923 Visit(BO->getLHS());
11924 }
11925
11926 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011927 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011928 if (Result)
11929 Visit(BO->getRHS());
11930 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011931 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011932 }
Richard Smithc406cb72013-01-17 01:17:56 +000011933 }
11934
11935 // Only visit the condition, unless we can be sure which subexpression will
11936 // be chosen.
11937 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011938 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011939 {
11940 SequencedSubexpression Sequenced(*this);
11941 Visit(CO->getCond());
11942 }
Richard Smithc406cb72013-01-17 01:17:56 +000011943
11944 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011945 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011946 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011947 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011948 WorkList.push_back(CO->getTrueExpr());
11949 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011950 }
Richard Smithc406cb72013-01-17 01:17:56 +000011951 }
11952
Richard Smithe3dbfe02013-06-30 10:40:20 +000011953 void VisitCallExpr(CallExpr *CE) {
11954 // C++11 [intro.execution]p15:
11955 // When calling a function [...], every value computation and side effect
11956 // associated with any argument expression, or with the postfix expression
11957 // designating the called function, is sequenced before execution of every
11958 // expression or statement in the body of the function [and thus before
11959 // the value computation of its result].
11960 SequencedSubexpression Sequenced(*this);
11961 Base::VisitCallExpr(CE);
11962
11963 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11964 }
11965
Richard Smithc406cb72013-01-17 01:17:56 +000011966 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011967 // This is a call, so all subexpressions are sequenced before the result.
11968 SequencedSubexpression Sequenced(*this);
11969
Richard Smithc406cb72013-01-17 01:17:56 +000011970 if (!CCE->isListInitialization())
11971 return VisitExpr(CCE);
11972
11973 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011974 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011975 SequenceTree::Seq Parent = Region;
11976 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11977 E = CCE->arg_end();
11978 I != E; ++I) {
11979 Region = Tree.allocate(Parent);
11980 Elts.push_back(Region);
11981 Visit(*I);
11982 }
11983
11984 // Forget that the initializers are sequenced.
11985 Region = Parent;
11986 for (unsigned I = 0; I < Elts.size(); ++I)
11987 Tree.merge(Elts[I]);
11988 }
11989
11990 void VisitInitListExpr(InitListExpr *ILE) {
11991 if (!SemaRef.getLangOpts().CPlusPlus11)
11992 return VisitExpr(ILE);
11993
11994 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011995 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011996 SequenceTree::Seq Parent = Region;
11997 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11998 Expr *E = ILE->getInit(I);
11999 if (!E) continue;
12000 Region = Tree.allocate(Parent);
12001 Elts.push_back(Region);
12002 Visit(E);
12003 }
12004
12005 // Forget that the initializers are sequenced.
12006 Region = Parent;
12007 for (unsigned I = 0; I < Elts.size(); ++I)
12008 Tree.merge(Elts[I]);
12009 }
12010};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012011
12012} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000012013
12014void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000012015 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000012016 WorkList.push_back(E);
12017 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000012018 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000012019 SequenceChecker(*this, Item, WorkList);
12020 }
Richard Smithc406cb72013-01-17 01:17:56 +000012021}
12022
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012023void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12024 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000012025 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000012026 if (!E->isInstantiationDependent())
12027 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000012028 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000012029 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012030 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000012031}
12032
John McCall1f425642010-11-11 03:21:53 +000012033void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12034 FieldDecl *BitField,
12035 Expr *Init) {
12036 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12037}
12038
David Majnemer61a5bbf2015-04-07 22:08:51 +000012039static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12040 SourceLocation Loc) {
12041 if (!PType->isVariablyModifiedType())
12042 return;
12043 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12044 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12045 return;
12046 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000012047 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12048 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12049 return;
12050 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000012051 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12052 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12053 return;
12054 }
12055
12056 const ArrayType *AT = S.Context.getAsArrayType(PType);
12057 if (!AT)
12058 return;
12059
12060 if (AT->getSizeModifier() != ArrayType::Star) {
12061 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12062 return;
12063 }
12064
12065 S.Diag(Loc, diag::err_array_star_in_function_definition);
12066}
12067
Mike Stump0c2ec772010-01-21 03:59:47 +000012068/// CheckParmsForFunctionDef - Check that the parameters of the given
12069/// function are appropriate for the definition of a function. This
12070/// takes care of any checks that cannot be performed on the
12071/// declaration itself, e.g., that the types of each of the function
12072/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000012073bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000012074 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012075 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000012076 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012077 // C99 6.7.5.3p4: the parameters in a parameter type list in a
12078 // function declarator that is part of a function definition of
12079 // that function shall not have incomplete type.
12080 //
12081 // This is also C++ [dcl.fct]p6.
12082 if (!Param->isInvalidDecl() &&
12083 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012084 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000012085 Param->setInvalidDecl();
12086 HasInvalidParm = true;
12087 }
12088
12089 // C99 6.9.1p5: If the declarator includes a parameter type list, the
12090 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000012091 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000012092 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000012093 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000012094 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000012095 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000012096
12097 // C99 6.7.5.3p12:
12098 // If the function declarator is not part of a definition of that
12099 // function, parameters may have incomplete type and may use the [*]
12100 // notation in their sequences of declarator specifiers to specify
12101 // variable length array types.
12102 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000012103 // FIXME: This diagnostic should point the '[*]' if source-location
12104 // information is added for it.
12105 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000012106
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012107 // If the parameter is a c++ class type and it has to be destructed in the
12108 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000012109 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012110 if (!Param->isInvalidDecl()) {
12111 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12112 if (!ClassDecl->isInvalidDecl() &&
12113 !ClassDecl->hasIrrelevantDestructor() &&
12114 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000012115 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000012116 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12117 MarkFunctionReferenced(Param->getLocation(), Destructor);
12118 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000012119 }
12120 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000012121 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000012122
12123 // Parameters with the pass_object_size attribute only need to be marked
12124 // constant at function definitions. Because we lack information about
12125 // whether we're on a declaration or definition when we're instantiating the
12126 // attribute, we need to check for constness here.
12127 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12128 if (!Param->getType().isConstQualified())
12129 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12130 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000012131 }
12132
12133 return HasInvalidParm;
12134}
John McCall2b5c1b22010-08-12 21:44:57 +000012135
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000012136/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12137/// or MemberExpr.
12138static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12139 ASTContext &Context) {
12140 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12141 return Context.getDeclAlign(DRE->getDecl());
12142
12143 if (const auto *ME = dyn_cast<MemberExpr>(E))
12144 return Context.getDeclAlign(ME->getMemberDecl());
12145
12146 return TypeAlign;
12147}
12148
John McCall2b5c1b22010-08-12 21:44:57 +000012149/// CheckCastAlign - Implements -Wcast-align, which warns when a
12150/// pointer cast increases the alignment requirements.
12151void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12152 // This is actually a lot of work to potentially be doing on every
12153 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012154 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000012155 return;
12156
12157 // Ignore dependent types.
12158 if (T->isDependentType() || Op->getType()->isDependentType())
12159 return;
12160
12161 // Require that the destination be a pointer type.
12162 const PointerType *DestPtr = T->getAs<PointerType>();
12163 if (!DestPtr) return;
12164
12165 // If the destination has alignment 1, we're done.
12166 QualType DestPointee = DestPtr->getPointeeType();
12167 if (DestPointee->isIncompleteType()) return;
12168 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12169 if (DestAlign.isOne()) return;
12170
12171 // Require that the source be a pointer type.
12172 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12173 if (!SrcPtr) return;
12174 QualType SrcPointee = SrcPtr->getPointeeType();
12175
12176 // Whitelist casts from cv void*. We already implicitly
12177 // whitelisted casts to cv void*, since they have alignment 1.
12178 // Also whitelist casts involving incomplete types, which implicitly
12179 // includes 'void'.
12180 if (SrcPointee->isIncompleteType()) return;
12181
12182 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000012183
12184 if (auto *CE = dyn_cast<CastExpr>(Op)) {
12185 if (CE->getCastKind() == CK_ArrayToPointerDecay)
12186 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12187 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12188 if (UO->getOpcode() == UO_AddrOf)
12189 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12190 }
12191
John McCall2b5c1b22010-08-12 21:44:57 +000012192 if (SrcAlign >= DestAlign) return;
12193
12194 Diag(TRange.getBegin(), diag::warn_cast_align)
12195 << Op->getType() << T
12196 << static_cast<unsigned>(SrcAlign.getQuantity())
12197 << static_cast<unsigned>(DestAlign.getQuantity())
12198 << TRange << Op->getSourceRange();
12199}
12200
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012201/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000012202/// array member of a struct.
12203///
12204/// We avoid emitting out-of-bounds access warnings for such arrays as they are
12205/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000012206static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000012207 const NamedDecl *ND) {
12208 if (Size != 1 || !ND) return false;
12209
12210 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12211 if (!FD) return false;
12212
12213 // Don't consider sizes resulting from macro expansions or template argument
12214 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000012215
12216 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012217 while (TInfo) {
12218 TypeLoc TL = TInfo->getTypeLoc();
12219 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000012220 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12221 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012222 TInfo = TDL->getTypeSourceInfo();
12223 continue;
12224 }
David Blaikie6adc78e2013-02-18 22:06:02 +000012225 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12226 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000012227 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12228 return false;
12229 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000012230 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000012231 }
Chandler Carruth28389f02011-08-05 09:10:50 +000012232
12233 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000012234 if (!RD) return false;
12235 if (RD->isUnion()) return false;
12236 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12237 if (!CRD->isStandardLayout()) return false;
12238 }
Chandler Carruth28389f02011-08-05 09:10:50 +000012239
Benjamin Kramer8c543672011-08-06 03:04:42 +000012240 // See if this is the last field decl in the record.
12241 const Decl *D = FD;
12242 while ((D = D->getNextDeclInContext()))
12243 if (isa<FieldDecl>(D))
12244 return false;
12245 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000012246}
12247
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012248void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012249 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000012250 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012251 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012252 if (IndexExpr->isValueDependent())
12253 return;
12254
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000012255 const Type *EffectiveType =
12256 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012257 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012258 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012259 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012260 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000012261 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000012262
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012263 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000012264 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000012265 return;
Richard Smith13f67182011-12-16 19:31:14 +000012266 if (IndexNegated)
12267 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000012268
Craig Topperc3ec1492014-05-26 06:22:03 +000012269 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000012270 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012271 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000012272 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012273 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000012274
Ted Kremeneke4b316c2011-02-23 23:06:04 +000012275 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012276 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000012277 if (!size.isStrictlyPositive())
12278 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012279
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000012280 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000012281 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012282 // Make sure we're comparing apples to apples when comparing index to size
12283 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12284 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000012285 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000012286 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012287 if (ptrarith_typesize != array_typesize) {
12288 // There's a cast to a different size type involved
12289 uint64_t ratio = array_typesize / ptrarith_typesize;
12290 // TODO: Be smarter about handling cases where array_typesize is not a
12291 // multiple of ptrarith_typesize
12292 if (ptrarith_typesize * ratio == array_typesize)
12293 size *= llvm::APInt(size.getBitWidth(), ratio);
12294 }
12295 }
12296
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012297 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012298 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012299 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012300 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000012301
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012302 // For array subscripting the index must be less than size, but for pointer
12303 // arithmetic also allow the index (offset) to be equal to size since
12304 // computing the next address after the end of the array is legal and
12305 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000012306 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000012307 return;
12308
12309 // Also don't warn for arrays of size 1 which are members of some
12310 // structure. These are often used to approximate flexible arrays in C89
12311 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012312 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000012313 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012314
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012315 // Suppress the warning if the subscript expression (as identified by the
12316 // ']' location) and the index expression are both from macro expansions
12317 // within a system header.
12318 if (ASE) {
12319 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12320 ASE->getRBracketLoc());
12321 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012322 SourceLocation IndexLoc =
12323 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
Eli Friedman5ba37d52013-08-22 00:27:10 +000012324 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012325 return;
12326 }
12327 }
12328
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012329 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012330 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012331 DiagID = diag::warn_array_index_exceeds_bounds;
12332
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012333 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012334 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012335 << size.toString(10, true)
12336 << (unsigned)size.getLimitedValue(~0U)
12337 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000012338 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012339 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012340 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012341 DiagID = diag::warn_ptr_arith_precedes_bounds;
12342 if (index.isNegative()) index = -index;
12343 }
12344
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012345 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012346 PDiag(DiagID) << index.toString(10, true)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012347 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000012348 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000012349
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012350 if (!ND) {
12351 // Try harder to find a NamedDecl to point at in the note.
12352 while (const ArraySubscriptExpr *ASE =
12353 dyn_cast<ArraySubscriptExpr>(BaseExpr))
12354 BaseExpr = ASE->getBase()->IgnoreParenCasts();
12355 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012356 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012357 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000012358 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000012359 }
12360
Chandler Carruth1af88f12011-02-17 21:10:52 +000012361 if (ND)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012362 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012363 PDiag(diag::note_array_index_out_of_bounds)
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012364 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000012365}
12366
Ted Kremenekdf26df72011-03-01 18:41:00 +000012367void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012368 int AllowOnePastEnd = 0;
12369 while (expr) {
12370 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000012371 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012372 case Stmt::ArraySubscriptExprClass: {
12373 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000012374 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012375 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000012376 expr = ASE->getBase();
12377 break;
12378 }
12379 case Stmt::MemberExprClass: {
12380 expr = cast<MemberExpr>(expr)->getBase();
12381 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012382 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000012383 case Stmt::OMPArraySectionExprClass: {
12384 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12385 if (ASE->getLowerBound())
12386 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12387 /*ASE=*/nullptr, AllowOnePastEnd > 0);
12388 return;
12389 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000012390 case Stmt::UnaryOperatorClass: {
12391 // Only unwrap the * and & unary operators
12392 const UnaryOperator *UO = cast<UnaryOperator>(expr);
12393 expr = UO->getSubExpr();
12394 switch (UO->getOpcode()) {
12395 case UO_AddrOf:
12396 AllowOnePastEnd++;
12397 break;
12398 case UO_Deref:
12399 AllowOnePastEnd--;
12400 break;
12401 default:
12402 return;
12403 }
12404 break;
12405 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012406 case Stmt::ConditionalOperatorClass: {
12407 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12408 if (const Expr *lhs = cond->getLHS())
12409 CheckArrayAccess(lhs);
12410 if (const Expr *rhs = cond->getRHS())
12411 CheckArrayAccess(rhs);
12412 return;
12413 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000012414 case Stmt::CXXOperatorCallExprClass: {
12415 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12416 for (const auto *Arg : OCE->arguments())
12417 CheckArrayAccess(Arg);
12418 return;
12419 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012420 default:
12421 return;
12422 }
Peter Collingbourne91147592011-04-15 00:35:48 +000012423 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000012424}
John McCall31168b02011-06-15 23:02:42 +000012425
12426//===--- CHECK: Objective-C retain cycles ----------------------------------//
12427
12428namespace {
John McCall31168b02011-06-15 23:02:42 +000012429
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012430struct RetainCycleOwner {
12431 VarDecl *Variable = nullptr;
12432 SourceRange Range;
12433 SourceLocation Loc;
12434 bool Indirect = false;
12435
12436 RetainCycleOwner() = default;
12437
12438 void setLocsFrom(Expr *e) {
12439 Loc = e->getExprLoc();
12440 Range = e->getSourceRange();
12441 }
12442};
12443
12444} // namespace
John McCall31168b02011-06-15 23:02:42 +000012445
12446/// Consider whether capturing the given variable can possibly lead to
12447/// a retain cycle.
12448static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000012449 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000012450 // lifetime. In MRR, it's captured strongly if the variable is
12451 // __block and has an appropriate type.
12452 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12453 return false;
12454
12455 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012456 if (ref)
12457 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000012458 return true;
12459}
12460
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012461static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000012462 while (true) {
12463 e = e->IgnoreParens();
12464 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12465 switch (cast->getCastKind()) {
12466 case CK_BitCast:
12467 case CK_LValueBitCast:
12468 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000012469 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000012470 e = cast->getSubExpr();
12471 continue;
12472
John McCall31168b02011-06-15 23:02:42 +000012473 default:
12474 return false;
12475 }
12476 }
12477
12478 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12479 ObjCIvarDecl *ivar = ref->getDecl();
12480 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12481 return false;
12482
12483 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012484 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000012485 return false;
12486
12487 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12488 owner.Indirect = true;
12489 return true;
12490 }
12491
12492 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12493 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12494 if (!var) return false;
12495 return considerVariable(var, ref, owner);
12496 }
12497
John McCall31168b02011-06-15 23:02:42 +000012498 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12499 if (member->isArrow()) return false;
12500
12501 // Don't count this as an indirect ownership.
12502 e = member->getBase();
12503 continue;
12504 }
12505
John McCallfe96e0b2011-11-06 09:01:30 +000012506 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12507 // Only pay attention to pseudo-objects on property references.
12508 ObjCPropertyRefExpr *pre
12509 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12510 ->IgnoreParens());
12511 if (!pre) return false;
12512 if (pre->isImplicitProperty()) return false;
12513 ObjCPropertyDecl *property = pre->getExplicitProperty();
12514 if (!property->isRetaining() &&
12515 !(property->getPropertyIvarDecl() &&
12516 property->getPropertyIvarDecl()->getType()
12517 .getObjCLifetime() == Qualifiers::OCL_Strong))
12518 return false;
12519
12520 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012521 if (pre->isSuperReceiver()) {
12522 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12523 if (!owner.Variable)
12524 return false;
12525 owner.Loc = pre->getLocation();
12526 owner.Range = pre->getSourceRange();
12527 return true;
12528 }
John McCallfe96e0b2011-11-06 09:01:30 +000012529 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12530 ->getSourceExpr());
12531 continue;
12532 }
12533
John McCall31168b02011-06-15 23:02:42 +000012534 // Array ivars?
12535
12536 return false;
12537 }
12538}
12539
12540namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012541
John McCall31168b02011-06-15 23:02:42 +000012542 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012543 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000012544 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012545 Expr *Capturer = nullptr;
12546 bool VarWillBeReased = false;
12547
12548 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12549 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12550 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000012551
12552 void VisitDeclRefExpr(DeclRefExpr *ref) {
12553 if (ref->getDecl() == Variable && !Capturer)
12554 Capturer = ref;
12555 }
12556
John McCall31168b02011-06-15 23:02:42 +000012557 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12558 if (Capturer) return;
12559 Visit(ref->getBase());
12560 if (Capturer && ref->isFreeIvar())
12561 Capturer = ref;
12562 }
12563
12564 void VisitBlockExpr(BlockExpr *block) {
Fangrui Song6907ce22018-07-30 19:24:48 +000012565 // Look inside nested blocks
John McCall31168b02011-06-15 23:02:42 +000012566 if (block->getBlockDecl()->capturesVariable(Variable))
12567 Visit(block->getBlockDecl()->getBody());
12568 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012569
Fariborz Jahanian0e337542012-08-31 20:04:47 +000012570 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12571 if (Capturer) return;
12572 if (OVE->getSourceExpr())
12573 Visit(OVE->getSourceExpr());
12574 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012575
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012576 void VisitBinaryOperator(BinaryOperator *BinOp) {
12577 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12578 return;
12579 Expr *LHS = BinOp->getLHS();
12580 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12581 if (DRE->getDecl() != Variable)
12582 return;
12583 if (Expr *RHS = BinOp->getRHS()) {
12584 RHS = RHS->IgnoreParenCasts();
12585 llvm::APSInt Value;
12586 VarWillBeReased =
12587 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12588 }
12589 }
12590 }
John McCall31168b02011-06-15 23:02:42 +000012591 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012592
12593} // namespace
John McCall31168b02011-06-15 23:02:42 +000012594
12595/// Check whether the given argument is a block which captures a
12596/// variable.
12597static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12598 assert(owner.Variable && owner.Loc.isValid());
12599
12600 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000012601
12602 // Look through [^{...} copy] and Block_copy(^{...}).
12603 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12604 Selector Cmd = ME->getSelector();
12605 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12606 e = ME->getInstanceReceiver();
12607 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000012608 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000012609 e = e->IgnoreParenCasts();
12610 }
12611 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12612 if (CE->getNumArgs() == 1) {
12613 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000012614 if (Fn) {
12615 const IdentifierInfo *FnI = Fn->getIdentifier();
12616 if (FnI && FnI->isStr("_Block_copy")) {
12617 e = CE->getArg(0)->IgnoreParenCasts();
12618 }
12619 }
Jordan Rose67e887c2012-09-17 17:54:30 +000012620 }
12621 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012622
John McCall31168b02011-06-15 23:02:42 +000012623 BlockExpr *block = dyn_cast<BlockExpr>(e);
12624 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000012625 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000012626
12627 FindCaptureVisitor visitor(S.Context, owner.Variable);
12628 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012629 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000012630}
12631
12632static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12633 RetainCycleOwner &owner) {
12634 assert(capturer);
12635 assert(owner.Variable && owner.Loc.isValid());
12636
12637 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12638 << owner.Variable << capturer->getSourceRange();
12639 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12640 << owner.Indirect << owner.Range;
12641}
12642
12643/// Check for a keyword selector that starts with the word 'add' or
12644/// 'set'.
12645static bool isSetterLikeSelector(Selector sel) {
12646 if (sel.isUnarySelector()) return false;
12647
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012648 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000012649 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012650 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000012651 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012652 else if (str.startswith("add")) {
12653 // Specially whitelist 'addOperationWithBlock:'.
12654 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12655 return false;
12656 str = str.substr(3);
12657 }
John McCall31168b02011-06-15 23:02:42 +000012658 else
12659 return false;
12660
12661 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000012662 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000012663}
12664
Benjamin Kramer3a743452015-03-09 15:03:32 +000012665static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12666 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012667 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12668 Message->getReceiverInterface(),
12669 NSAPI::ClassId_NSMutableArray);
12670 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012671 return None;
12672 }
12673
12674 Selector Sel = Message->getSelector();
12675
12676 Optional<NSAPI::NSArrayMethodKind> MKOpt =
12677 S.NSAPIObj->getNSArrayMethodKind(Sel);
12678 if (!MKOpt) {
12679 return None;
12680 }
12681
12682 NSAPI::NSArrayMethodKind MK = *MKOpt;
12683
12684 switch (MK) {
12685 case NSAPI::NSMutableArr_addObject:
12686 case NSAPI::NSMutableArr_insertObjectAtIndex:
12687 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12688 return 0;
12689 case NSAPI::NSMutableArr_replaceObjectAtIndex:
12690 return 1;
12691
12692 default:
12693 return None;
12694 }
12695
12696 return None;
12697}
12698
12699static
12700Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12701 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012702 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12703 Message->getReceiverInterface(),
12704 NSAPI::ClassId_NSMutableDictionary);
12705 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012706 return None;
12707 }
12708
12709 Selector Sel = Message->getSelector();
12710
12711 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12712 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12713 if (!MKOpt) {
12714 return None;
12715 }
12716
12717 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12718
12719 switch (MK) {
12720 case NSAPI::NSMutableDict_setObjectForKey:
12721 case NSAPI::NSMutableDict_setValueForKey:
12722 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12723 return 0;
12724
12725 default:
12726 return None;
12727 }
12728
12729 return None;
12730}
12731
12732static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012733 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12734 Message->getReceiverInterface(),
12735 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012736
Alex Denisov5dfac812015-08-06 04:51:14 +000012737 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12738 Message->getReceiverInterface(),
12739 NSAPI::ClassId_NSMutableOrderedSet);
12740 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012741 return None;
12742 }
12743
12744 Selector Sel = Message->getSelector();
12745
12746 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12747 if (!MKOpt) {
12748 return None;
12749 }
12750
12751 NSAPI::NSSetMethodKind MK = *MKOpt;
12752
12753 switch (MK) {
12754 case NSAPI::NSMutableSet_addObject:
12755 case NSAPI::NSOrderedSet_setObjectAtIndex:
12756 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12757 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12758 return 0;
12759 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12760 return 1;
12761 }
12762
12763 return None;
12764}
12765
12766void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12767 if (!Message->isInstanceMessage()) {
12768 return;
12769 }
12770
12771 Optional<int> ArgOpt;
12772
12773 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12774 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12775 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12776 return;
12777 }
12778
12779 int ArgIndex = *ArgOpt;
12780
Alex Denisove1d882c2015-03-04 17:55:52 +000012781 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12782 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12783 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12784 }
12785
Alex Denisov5dfac812015-08-06 04:51:14 +000012786 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012787 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012788 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012789 Diag(Message->getSourceRange().getBegin(),
12790 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012791 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012792 }
12793 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012794 } else {
12795 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12796
12797 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12798 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12799 }
12800
12801 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12802 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12803 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12804 ValueDecl *Decl = ReceiverRE->getDecl();
12805 Diag(Message->getSourceRange().getBegin(),
12806 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012807 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012808 if (!ArgRE->isObjCSelfExpr()) {
12809 Diag(Decl->getLocation(),
12810 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012811 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012812 }
12813 }
12814 }
12815 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12816 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12817 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12818 ObjCIvarDecl *Decl = IvarRE->getDecl();
12819 Diag(Message->getSourceRange().getBegin(),
12820 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012821 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012822 Diag(Decl->getLocation(),
12823 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012824 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012825 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012826 }
12827 }
12828 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012829}
12830
John McCall31168b02011-06-15 23:02:42 +000012831/// Check a message send to see if it's likely to cause a retain cycle.
12832void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12833 // Only check instance methods whose selector looks like a setter.
12834 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12835 return;
12836
12837 // Try to find a variable that the receiver is strongly owned by.
12838 RetainCycleOwner owner;
12839 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012840 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012841 return;
12842 } else {
12843 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12844 owner.Variable = getCurMethodDecl()->getSelfDecl();
12845 owner.Loc = msg->getSuperLoc();
12846 owner.Range = msg->getSuperLoc();
12847 }
12848
12849 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012850 const ObjCMethodDecl *MD = msg->getMethodDecl();
12851 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12852 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12853 // noescape blocks should not be retained by the method.
12854 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12855 continue;
John McCall31168b02011-06-15 23:02:42 +000012856 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012857 }
12858 }
John McCall31168b02011-06-15 23:02:42 +000012859}
12860
12861/// Check a property assign to see if it's likely to cause a retain cycle.
12862void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12863 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012864 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012865 return;
12866
12867 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12868 diagnoseRetainCycle(*this, capturer, owner);
12869}
12870
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012871void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12872 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012873 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012874 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000012875
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012876 // Because we don't have an expression for the variable, we have to set the
12877 // location explicitly here.
12878 Owner.Loc = Var->getLocation();
12879 Owner.Range = Var->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +000012880
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012881 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12882 diagnoseRetainCycle(*this, Capturer, Owner);
12883}
12884
Ted Kremenek9304da92012-12-21 08:04:28 +000012885static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12886 Expr *RHS, bool isProperty) {
12887 // Check if RHS is an Objective-C object literal, which also can get
12888 // immediately zapped in a weak reference. Note that we explicitly
12889 // allow ObjCStringLiterals, since those are designed to never really die.
12890 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012891
Ted Kremenek64873352012-12-21 22:46:35 +000012892 // This enum needs to match with the 'select' in
12893 // warn_objc_arc_literal_assign (off-by-1).
12894 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12895 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12896 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012897
12898 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012899 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012900 << (isProperty ? 0 : 1)
12901 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012902
12903 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012904}
12905
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012906static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12907 Qualifiers::ObjCLifetime LT,
12908 Expr *RHS, bool isProperty) {
12909 // Strip off any implicit cast added to get to the one ARC-specific.
12910 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12911 if (cast->getCastKind() == CK_ARCConsumeObject) {
12912 S.Diag(Loc, diag::warn_arc_retained_assign)
12913 << (LT == Qualifiers::OCL_ExplicitNone)
12914 << (isProperty ? 0 : 1)
12915 << RHS->getSourceRange();
12916 return true;
12917 }
12918 RHS = cast->getSubExpr();
12919 }
12920
12921 if (LT == Qualifiers::OCL_Weak &&
12922 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12923 return true;
12924
12925 return false;
12926}
12927
Ted Kremenekb36234d2012-12-21 08:04:20 +000012928bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12929 QualType LHS, Expr *RHS) {
12930 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12931
12932 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12933 return false;
12934
12935 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12936 return true;
12937
12938 return false;
12939}
12940
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012941void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12942 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012943 QualType LHSType;
12944 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012945 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012946 ObjCPropertyRefExpr *PRE
12947 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12948 if (PRE && !PRE->isImplicitProperty()) {
12949 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12950 if (PD)
12951 LHSType = PD->getType();
12952 }
Fangrui Song6907ce22018-07-30 19:24:48 +000012953
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012954 if (LHSType.isNull())
12955 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012956
12957 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12958
12959 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012960 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012961 getCurFunction()->markSafeWeakUse(LHS);
12962 }
12963
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012964 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12965 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012966
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012967 // FIXME. Check for other life times.
12968 if (LT != Qualifiers::OCL_None)
12969 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000012970
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012971 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012972 if (PRE->isImplicitProperty())
12973 return;
12974 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12975 if (!PD)
12976 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000012977
Bill Wendling44426052012-12-20 19:22:21 +000012978 unsigned Attributes = PD->getPropertyAttributes();
12979 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012980 // when 'assign' attribute was not explicitly specified
12981 // by user, ignore it and rely on property type itself
12982 // for lifetime info.
12983 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12984 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12985 LHSType->isObjCRetainableType())
12986 return;
Fangrui Song6907ce22018-07-30 19:24:48 +000012987
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012988 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012989 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012990 Diag(Loc, diag::warn_arc_retained_property_assign)
12991 << RHS->getSourceRange();
12992 return;
12993 }
12994 RHS = cast->getSubExpr();
12995 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012996 }
Bill Wendling44426052012-12-20 19:22:21 +000012997 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012998 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12999 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000013000 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000013001 }
13002}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013003
13004//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13005
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013006static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13007 SourceLocation StmtLoc,
13008 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013009 // Do not warn if the body is a macro that expands to nothing, e.g:
13010 //
13011 // #define CALL(x)
13012 // if (condition)
13013 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013014 if (Body->hasLeadingEmptyMacro())
13015 return false;
13016
13017 // Get line numbers of statement and body.
13018 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000013019 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013020 &StmtLineInvalid);
13021 if (StmtLineInvalid)
13022 return false;
13023
13024 bool BodyLineInvalid;
13025 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13026 &BodyLineInvalid);
13027 if (BodyLineInvalid)
13028 return false;
13029
13030 // Warn if null statement and body are on the same line.
13031 if (StmtLine != BodyLine)
13032 return false;
13033
13034 return true;
13035}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013036
13037void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13038 const Stmt *Body,
13039 unsigned DiagID) {
13040 // Since this is a syntactic check, don't emit diagnostic for template
13041 // instantiations, this just adds noise.
13042 if (CurrentInstantiationScope)
13043 return;
13044
13045 // The body should be a null statement.
13046 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13047 if (!NBody)
13048 return;
13049
13050 // Do the usual checks.
13051 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13052 return;
13053
13054 Diag(NBody->getSemiLoc(), DiagID);
13055 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13056}
13057
13058void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13059 const Stmt *PossibleBody) {
13060 assert(!CurrentInstantiationScope); // Ensured by caller
13061
13062 SourceLocation StmtLoc;
13063 const Stmt *Body;
13064 unsigned DiagID;
13065 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13066 StmtLoc = FS->getRParenLoc();
13067 Body = FS->getBody();
13068 DiagID = diag::warn_empty_for_body;
13069 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13070 StmtLoc = WS->getCond()->getSourceRange().getEnd();
13071 Body = WS->getBody();
13072 DiagID = diag::warn_empty_while_body;
13073 } else
13074 return; // Neither `for' nor `while'.
13075
13076 // The body should be a null statement.
13077 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13078 if (!NBody)
13079 return;
13080
13081 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000013082 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013083 return;
13084
13085 // Do the usual checks.
13086 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13087 return;
13088
13089 // `for(...);' and `while(...);' are popular idioms, so in order to keep
13090 // noise level low, emit diagnostics only if for/while is followed by a
13091 // CompoundStmt, e.g.:
13092 // for (int i = 0; i < n; i++);
13093 // {
13094 // a(i);
13095 // }
13096 // or if for/while is followed by a statement with more indentation
13097 // than for/while itself:
13098 // for (int i = 0; i < n; i++);
13099 // a(i);
13100 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13101 if (!ProbableTypo) {
13102 bool BodyColInvalid;
13103 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013104 PossibleBody->getBeginLoc(), &BodyColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013105 if (BodyColInvalid)
13106 return;
13107
13108 bool StmtColInvalid;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013109 unsigned StmtCol =
13110 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000013111 if (StmtColInvalid)
13112 return;
13113
13114 if (BodyCol > StmtCol)
13115 ProbableTypo = true;
13116 }
13117
13118 if (ProbableTypo) {
13119 Diag(NBody->getSemiLoc(), DiagID);
13120 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13121 }
13122}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013123
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013124//===--- CHECK: Warn on self move with std::move. -------------------------===//
13125
13126/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13127void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13128 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013129 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13130 return;
13131
Richard Smith51ec0cf2017-02-21 01:17:38 +000013132 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013133 return;
13134
13135 // Strip parens and casts away.
13136 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13137 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13138
13139 // Check for a call expression
13140 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13141 if (!CE || CE->getNumArgs() != 1)
13142 return;
13143
13144 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000013145 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000013146 return;
13147
13148 // Get argument from std::move
13149 RHSExpr = CE->getArg(0);
13150
13151 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13152 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13153
13154 // Two DeclRefExpr's, check that the decls are the same.
13155 if (LHSDeclRef && RHSDeclRef) {
13156 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13157 return;
13158 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13159 RHSDeclRef->getDecl()->getCanonicalDecl())
13160 return;
13161
13162 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13163 << LHSExpr->getSourceRange()
13164 << RHSExpr->getSourceRange();
13165 return;
13166 }
13167
13168 // Member variables require a different approach to check for self moves.
13169 // MemberExpr's are the same if every nested MemberExpr refers to the same
13170 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13171 // the base Expr's are CXXThisExpr's.
13172 const Expr *LHSBase = LHSExpr;
13173 const Expr *RHSBase = RHSExpr;
13174 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13175 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13176 if (!LHSME || !RHSME)
13177 return;
13178
13179 while (LHSME && RHSME) {
13180 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13181 RHSME->getMemberDecl()->getCanonicalDecl())
13182 return;
13183
13184 LHSBase = LHSME->getBase();
13185 RHSBase = RHSME->getBase();
13186 LHSME = dyn_cast<MemberExpr>(LHSBase);
13187 RHSME = dyn_cast<MemberExpr>(RHSBase);
13188 }
13189
13190 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13191 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13192 if (LHSDeclRef && RHSDeclRef) {
13193 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13194 return;
13195 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13196 RHSDeclRef->getDecl()->getCanonicalDecl())
13197 return;
13198
13199 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13200 << LHSExpr->getSourceRange()
13201 << RHSExpr->getSourceRange();
13202 return;
13203 }
13204
13205 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13206 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13207 << LHSExpr->getSourceRange()
13208 << RHSExpr->getSourceRange();
13209}
13210
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013211//===--- Layout compatibility ----------------------------------------------//
13212
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013213static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013214
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013215/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013216static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013217 // C++11 [dcl.enum] p8:
13218 // Two enumeration types are layout-compatible if they have the same
13219 // underlying type.
13220 return ED1->isComplete() && ED2->isComplete() &&
13221 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13222}
13223
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013224/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013225static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13226 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013227 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13228 return false;
13229
13230 if (Field1->isBitField() != Field2->isBitField())
13231 return false;
13232
13233 if (Field1->isBitField()) {
13234 // Make sure that the bit-fields are the same length.
13235 unsigned Bits1 = Field1->getBitWidthValue(C);
13236 unsigned Bits2 = Field2->getBitWidthValue(C);
13237
13238 if (Bits1 != Bits2)
13239 return false;
13240 }
13241
13242 return true;
13243}
13244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013245/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013246/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013247static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13248 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013249 // If both records are C++ classes, check that base classes match.
13250 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13251 // If one of records is a CXXRecordDecl we are in C++ mode,
13252 // thus the other one is a CXXRecordDecl, too.
13253 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13254 // Check number of base classes.
13255 if (D1CXX->getNumBases() != D2CXX->getNumBases())
13256 return false;
13257
13258 // Check the base classes.
13259 for (CXXRecordDecl::base_class_const_iterator
13260 Base1 = D1CXX->bases_begin(),
13261 BaseEnd1 = D1CXX->bases_end(),
13262 Base2 = D2CXX->bases_begin();
13263 Base1 != BaseEnd1;
13264 ++Base1, ++Base2) {
13265 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13266 return false;
13267 }
13268 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13269 // If only RD2 is a C++ class, it should have zero base classes.
13270 if (D2CXX->getNumBases() > 0)
13271 return false;
13272 }
13273
13274 // Check the fields.
13275 RecordDecl::field_iterator Field2 = RD2->field_begin(),
13276 Field2End = RD2->field_end(),
13277 Field1 = RD1->field_begin(),
13278 Field1End = RD1->field_end();
13279 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13280 if (!isLayoutCompatible(C, *Field1, *Field2))
13281 return false;
13282 }
13283 if (Field1 != Field1End || Field2 != Field2End)
13284 return false;
13285
13286 return true;
13287}
13288
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013289/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013290/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013291static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13292 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013293 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013294 for (auto *Field2 : RD2->fields())
13295 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013296
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013297 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013298 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13299 I = UnmatchedFields.begin(),
13300 E = UnmatchedFields.end();
13301
13302 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000013303 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013304 bool Result = UnmatchedFields.erase(*I);
13305 (void) Result;
13306 assert(Result);
13307 break;
13308 }
13309 }
13310 if (I == E)
13311 return false;
13312 }
13313
13314 return UnmatchedFields.empty();
13315}
13316
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013317static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13318 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013319 if (RD1->isUnion() != RD2->isUnion())
13320 return false;
13321
13322 if (RD1->isUnion())
13323 return isLayoutCompatibleUnion(C, RD1, RD2);
13324 else
13325 return isLayoutCompatibleStruct(C, RD1, RD2);
13326}
13327
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013328/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013329static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013330 if (T1.isNull() || T2.isNull())
13331 return false;
13332
13333 // C++11 [basic.types] p11:
13334 // If two types T1 and T2 are the same type, then T1 and T2 are
13335 // layout-compatible types.
13336 if (C.hasSameType(T1, T2))
13337 return true;
13338
13339 T1 = T1.getCanonicalType().getUnqualifiedType();
13340 T2 = T2.getCanonicalType().getUnqualifiedType();
13341
13342 const Type::TypeClass TC1 = T1->getTypeClass();
13343 const Type::TypeClass TC2 = T2->getTypeClass();
13344
13345 if (TC1 != TC2)
13346 return false;
13347
13348 if (TC1 == Type::Enum) {
13349 return isLayoutCompatible(C,
13350 cast<EnumType>(T1)->getDecl(),
13351 cast<EnumType>(T2)->getDecl());
13352 } else if (TC1 == Type::Record) {
13353 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13354 return false;
13355
13356 return isLayoutCompatible(C,
13357 cast<RecordType>(T1)->getDecl(),
13358 cast<RecordType>(T2)->getDecl());
13359 }
13360
13361 return false;
13362}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013363
13364//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13365
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013366/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013367///
13368/// \param TypeExpr Type tag expression, as it appears in user's code.
13369///
13370/// \param VD Declaration of an identifier that appears in a type tag.
13371///
13372/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013373static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13374 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013375 while(true) {
13376 if (!TypeExpr)
13377 return false;
13378
13379 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13380
13381 switch (TypeExpr->getStmtClass()) {
13382 case Stmt::UnaryOperatorClass: {
13383 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13384 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13385 TypeExpr = UO->getSubExpr();
13386 continue;
13387 }
13388 return false;
13389 }
13390
13391 case Stmt::DeclRefExprClass: {
13392 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13393 *VD = DRE->getDecl();
13394 return true;
13395 }
13396
13397 case Stmt::IntegerLiteralClass: {
13398 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13399 llvm::APInt MagicValueAPInt = IL->getValue();
13400 if (MagicValueAPInt.getActiveBits() <= 64) {
13401 *MagicValue = MagicValueAPInt.getZExtValue();
13402 return true;
13403 } else
13404 return false;
13405 }
13406
13407 case Stmt::BinaryConditionalOperatorClass:
13408 case Stmt::ConditionalOperatorClass: {
13409 const AbstractConditionalOperator *ACO =
13410 cast<AbstractConditionalOperator>(TypeExpr);
13411 bool Result;
13412 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13413 if (Result)
13414 TypeExpr = ACO->getTrueExpr();
13415 else
13416 TypeExpr = ACO->getFalseExpr();
13417 continue;
13418 }
13419 return false;
13420 }
13421
13422 case Stmt::BinaryOperatorClass: {
13423 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13424 if (BO->getOpcode() == BO_Comma) {
13425 TypeExpr = BO->getRHS();
13426 continue;
13427 }
13428 return false;
13429 }
13430
13431 default:
13432 return false;
13433 }
13434 }
13435}
13436
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013437/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013438///
13439/// \param TypeExpr Expression that specifies a type tag.
13440///
13441/// \param MagicValues Registered magic values.
13442///
13443/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13444/// kind.
13445///
13446/// \param TypeInfo Information about the corresponding C type.
13447///
13448/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013449static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013450 const IdentifierInfo *ArgumentKind,
13451 const Expr *TypeExpr, const ASTContext &Ctx,
13452 const llvm::DenseMap<Sema::TypeTagMagicValue,
13453 Sema::TypeTagData> *MagicValues,
13454 bool &FoundWrongKind,
13455 Sema::TypeTagData &TypeInfo) {
13456 FoundWrongKind = false;
13457
13458 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000013459 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013460
13461 uint64_t MagicValue;
13462
13463 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13464 return false;
13465
13466 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000013467 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013468 if (I->getArgumentKind() != ArgumentKind) {
13469 FoundWrongKind = true;
13470 return false;
13471 }
13472 TypeInfo.Type = I->getMatchingCType();
13473 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13474 TypeInfo.MustBeNull = I->getMustBeNull();
13475 return true;
13476 }
13477 return false;
13478 }
13479
13480 if (!MagicValues)
13481 return false;
13482
13483 llvm::DenseMap<Sema::TypeTagMagicValue,
13484 Sema::TypeTagData>::const_iterator I =
13485 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13486 if (I == MagicValues->end())
13487 return false;
13488
13489 TypeInfo = I->second;
13490 return true;
13491}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013492
13493void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13494 uint64_t MagicValue, QualType Type,
13495 bool LayoutCompatible,
13496 bool MustBeNull) {
13497 if (!TypeTagForDatatypeMagicValues)
13498 TypeTagForDatatypeMagicValues.reset(
13499 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13500
13501 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13502 (*TypeTagForDatatypeMagicValues)[Magic] =
13503 TypeTagData(Type, LayoutCompatible, MustBeNull);
13504}
13505
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013506static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013507 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13508 if (!BT1)
13509 return false;
13510
13511 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13512 if (!BT2)
13513 return false;
13514
13515 BuiltinType::Kind T1Kind = BT1->getKind();
13516 BuiltinType::Kind T2Kind = BT2->getKind();
13517
13518 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
13519 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
13520 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13521 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13522}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013523
13524void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013525 const ArrayRef<const Expr *> ExprArgs,
13526 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013527 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13528 bool IsPointerAttr = Attr->getIsPointer();
13529
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013530 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000013531 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13532 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013533 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000013534 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013535 return;
13536 }
Joel E. Denny81508102018-03-13 14:51:22 +000013537 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013538 bool FoundWrongKind;
13539 TypeTagData TypeInfo;
13540 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13541 TypeTagForDatatypeMagicValues.get(),
13542 FoundWrongKind, TypeInfo)) {
13543 if (FoundWrongKind)
13544 Diag(TypeTagExpr->getExprLoc(),
13545 diag::warn_type_tag_for_datatype_wrong_kind)
13546 << TypeTagExpr->getSourceRange();
13547 return;
13548 }
13549
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013550 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000013551 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13552 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013553 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000013554 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000013555 return;
13556 }
Joel E. Denny81508102018-03-13 14:51:22 +000013557 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013558 if (IsPointerAttr) {
13559 // Skip implicit cast of pointer to `void *' (as a function argument).
13560 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000013561 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000013562 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013563 ArgumentExpr = ICE->getSubExpr();
13564 }
13565 QualType ArgumentType = ArgumentExpr->getType();
13566
13567 // Passing a `void*' pointer shouldn't trigger a warning.
13568 if (IsPointerAttr && ArgumentType->isVoidPointerType())
13569 return;
13570
13571 if (TypeInfo.MustBeNull) {
13572 // Type tag with matching void type requires a null pointer.
13573 if (!ArgumentExpr->isNullPointerConstant(Context,
13574 Expr::NPC_ValueDependentIsNotNull)) {
13575 Diag(ArgumentExpr->getExprLoc(),
13576 diag::warn_type_safety_null_pointer_required)
13577 << ArgumentKind->getName()
13578 << ArgumentExpr->getSourceRange()
13579 << TypeTagExpr->getSourceRange();
13580 }
13581 return;
13582 }
13583
13584 QualType RequiredType = TypeInfo.Type;
13585 if (IsPointerAttr)
13586 RequiredType = Context.getPointerType(RequiredType);
13587
13588 bool mismatch = false;
13589 if (!TypeInfo.LayoutCompatible) {
13590 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13591
13592 // C++11 [basic.fundamental] p1:
13593 // Plain char, signed char, and unsigned char are three distinct types.
13594 //
13595 // But we treat plain `char' as equivalent to `signed char' or `unsigned
13596 // char' depending on the current char signedness mode.
13597 if (mismatch)
13598 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13599 RequiredType->getPointeeType())) ||
13600 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13601 mismatch = false;
13602 } else
13603 if (IsPointerAttr)
13604 mismatch = !isLayoutCompatible(Context,
13605 ArgumentType->getPointeeType(),
13606 RequiredType->getPointeeType());
13607 else
13608 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13609
13610 if (mismatch)
13611 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000013612 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013613 << TypeInfo.LayoutCompatible << RequiredType
13614 << ArgumentExpr->getSourceRange()
13615 << TypeTagExpr->getSourceRange();
13616}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013617
13618void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13619 CharUnits Alignment) {
13620 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13621}
13622
13623void Sema::DiagnoseMisalignedMembers() {
13624 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000013625 const NamedDecl *ND = m.RD;
13626 if (ND->getName().empty()) {
13627 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13628 ND = TD;
13629 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013630 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000013631 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013632 }
13633 MisalignedMembers.clear();
13634}
13635
13636void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013637 E = E->IgnoreParens();
13638 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013639 return;
13640 if (isa<UnaryOperator>(E) &&
13641 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13642 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13643 if (isa<MemberExpr>(Op)) {
13644 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13645 MisalignedMember(Op));
13646 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013647 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000013648 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13649 Context.getTypeAlignInChars(
13650 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013651 MisalignedMembers.erase(MA);
13652 }
13653 }
13654}
13655
13656void Sema::RefersToMemberWithReducedAlignment(
13657 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000013658 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13659 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013660 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013661 if (!ME)
13662 return;
13663
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000013664 // No need to check expressions with an __unaligned-qualified type.
13665 if (E->getType().getQualifiers().hasUnaligned())
13666 return;
13667
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013668 // For a chain of MemberExpr like "a.b.c.d" this list
13669 // will keep FieldDecl's like [d, c, b].
13670 SmallVector<FieldDecl *, 4> ReverseMemberChain;
13671 const MemberExpr *TopME = nullptr;
13672 bool AnyIsPacked = false;
13673 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013674 QualType BaseType = ME->getBase()->getType();
13675 if (ME->isArrow())
13676 BaseType = BaseType->getPointeeType();
13677 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000013678 if (RD->isInvalidDecl())
13679 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013680
13681 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013682 auto *FD = dyn_cast<FieldDecl>(MD);
13683 // We do not care about non-data members.
13684 if (!FD || FD->isInvalidDecl())
13685 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013686
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013687 AnyIsPacked =
13688 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13689 ReverseMemberChain.push_back(FD);
13690
13691 TopME = ME;
13692 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13693 } while (ME);
13694 assert(TopME && "We did not compute a topmost MemberExpr!");
13695
13696 // Not the scope of this diagnostic.
13697 if (!AnyIsPacked)
13698 return;
13699
13700 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13701 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13702 // TODO: The innermost base of the member expression may be too complicated.
13703 // For now, just disregard these cases. This is left for future
13704 // improvement.
13705 if (!DRE && !isa<CXXThisExpr>(TopBase))
13706 return;
13707
13708 // Alignment expected by the whole expression.
13709 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13710
13711 // No need to do anything else with this case.
13712 if (ExpectedAlignment.isOne())
13713 return;
13714
13715 // Synthesize offset of the whole access.
13716 CharUnits Offset;
13717 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13718 I++) {
13719 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13720 }
13721
13722 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13723 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13724 ReverseMemberChain.back()->getParent()->getTypeForDecl());
13725
13726 // The base expression of the innermost MemberExpr may give
13727 // stronger guarantees than the class containing the member.
13728 if (DRE && !TopME->isArrow()) {
13729 const ValueDecl *VD = DRE->getDecl();
13730 if (!VD->getType()->isReferenceType())
13731 CompleteObjectAlignment =
13732 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13733 }
13734
13735 // Check if the synthesized offset fulfills the alignment.
13736 if (Offset % ExpectedAlignment != 0 ||
13737 // It may fulfill the offset it but the effective alignment may still be
13738 // lower than the expected expression alignment.
13739 CompleteObjectAlignment < ExpectedAlignment) {
13740 // If this happens, we want to determine a sensible culprit of this.
13741 // Intuitively, watching the chain of member expressions from right to
13742 // left, we start with the required alignment (as required by the field
13743 // type) but some packed attribute in that chain has reduced the alignment.
13744 // It may happen that another packed structure increases it again. But if
13745 // we are here such increase has not been enough. So pointing the first
13746 // FieldDecl that either is packed or else its RecordDecl is,
13747 // seems reasonable.
13748 FieldDecl *FD = nullptr;
13749 CharUnits Alignment;
13750 for (FieldDecl *FDI : ReverseMemberChain) {
13751 if (FDI->hasAttr<PackedAttr>() ||
13752 FDI->getParent()->hasAttr<PackedAttr>()) {
13753 FD = FDI;
13754 Alignment = std::min(
13755 Context.getTypeAlignInChars(FD->getType()),
13756 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13757 break;
13758 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013759 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013760 assert(FD && "We did not find a packed FieldDecl!");
13761 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013762 }
13763}
13764
13765void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13766 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013767
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013768 RefersToMemberWithReducedAlignment(
13769 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13770 _2, _3, _4));
13771}