blob: 12a599b4f130a393c57ea58b7d4333928758ccc3 [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"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000030#include "clang/AST/NSAPI.h"
Akira Hatanaka2be04412018-04-17 19:13:41 +000031#include "clang/AST/NonTrivialTypeVisitor.h"
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000032#include "clang/AST/OperationKinds.h"
33#include "clang/AST/Stmt.h"
34#include "clang/AST/TemplateBase.h"
35#include "clang/AST/Type.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/UnresolvedSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Analysis/Analyses/FormatString.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)
115 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
116 << 0 /*function call*/ << desiredArgCount << argCount
117 << call->getSourceRange();
118
119 // Highlight all the excess arguments.
120 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
121 call->getArg(argCount - 1)->getLocEnd());
Nico Weberade321e2018-04-10 18:53:28 +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()) {
138 S.Diag(ValArg->getLocStart(), 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()) {
147 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
148 << StrArg->getSourceRange();
149 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) {
159 S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
160 << 0 << 1 << TheCall->getNumArgs()
161 << TheCall->getCallee()->getSourceRange();
162 return true;
163 }
164
165 // All arguments should be wide string literals.
166 for (Expr *Arg : TheCall->arguments()) {
167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
168 if (!Literal || !Literal->isWide()) {
169 S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
170 << 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));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
186 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()) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000203 S.Diag(Arg.get()->getLocStart(), diag::err_overflow_builtin_must_be_int)
204 << 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())) {
Erich Keane1d73d1a2018-06-13 13:25:11 +0000224 S.Diag(Arg.get()->getLocStart(),
225 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,
Nico Weberade321e2018-04-10 18:53:28 +0000240 CallExpr *TheCall, unsigned SizeIdx,
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000241 unsigned DstSizeIdx) {
242 if (TheCall->getNumArgs() <= SizeIdx ||
243 TheCall->getNumArgs() <= DstSizeIdx)
244 return;
245
246 const Expr *SizeArg = TheCall->getArg(SizeIdx);
247 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
248
249 llvm::APSInt Size, DstSize;
250
251 // find out if both sizes are known at compile time
252 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
253 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
254 return;
255
256 if (Size.ule(DstSize))
257 return;
258
259 // confirmed overflow so generate the diagnostic.
260 IdentifierInfo *FnName = FDecl->getIdentifier();
261 SourceLocation SL = TheCall->getLocStart();
262 SourceRange SR = TheCall->getSourceRange();
263
264 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
265}
266
Peter Collingbournef7706832014-12-12 23:41:25 +0000267static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
268 if (checkArgCount(S, BuiltinCall, 2))
269 return true;
270
271 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
272 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
273 Expr *Call = BuiltinCall->getArg(0);
274 Expr *Chain = BuiltinCall->getArg(1);
275
276 if (Call->getStmtClass() != Stmt::CallExprClass) {
277 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
278 << Call->getSourceRange();
279 return true;
280 }
281
282 auto CE = cast<CallExpr>(Call);
283 if (CE->getCallee()->getType()->isBlockPointerType()) {
284 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
285 << Call->getSourceRange();
286 return true;
287 }
288
289 const Decl *TargetDecl = CE->getCalleeDecl();
290 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
291 if (FD->getBuiltinID()) {
292 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
293 << Call->getSourceRange();
294 return true;
295 }
296
297 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
298 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
299 << Call->getSourceRange();
300 return true;
301 }
302
303 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
304 if (ChainResult.isInvalid())
305 return true;
306 if (!ChainResult.get()->getType()->isPointerType()) {
307 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
308 << Chain->getSourceRange();
309 return true;
310 }
311
David Majnemerced8bdf2015-02-25 17:36:15 +0000312 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000313 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
314 QualType BuiltinTy = S.Context.getFunctionType(
315 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
316 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
317
318 Builtin =
319 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
320
321 BuiltinCall->setType(CE->getType());
322 BuiltinCall->setValueKind(CE->getValueKind());
323 BuiltinCall->setObjectKind(CE->getObjectKind());
324 BuiltinCall->setCallee(Builtin);
325 BuiltinCall->setArg(1, ChainResult.get());
326
327 return false;
328}
329
Reid Kleckner1d59f992015-01-22 01:36:17 +0000330static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
331 Scope::ScopeFlags NeededScopeFlags,
332 unsigned DiagID) {
333 // Scopes aren't available during instantiation. Fortunately, builtin
334 // functions cannot be template args so they cannot be formed through template
335 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000336 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000337 return false;
338
339 Scope *S = SemaRef.getCurScope();
340 while (S && !S->isSEHExceptScope())
341 S = S->getParent();
342 if (!S || !(S->getFlags() & NeededScopeFlags)) {
343 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
344 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
345 << DRE->getDecl()->getIdentifier();
346 return true;
347 }
348
349 return false;
350}
351
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000352static inline bool isBlockPointer(Expr *Arg) {
353 return Arg->getType()->isBlockPointerType();
354}
355
356/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
357/// void*, which is a requirement of device side enqueue.
358static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
359 const BlockPointerType *BPT =
360 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
361 ArrayRef<QualType> Params =
362 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
363 unsigned ArgCounter = 0;
364 bool IllegalParams = false;
365 // Iterate through the block parameters until either one is found that is not
366 // a local void*, or the block is valid.
367 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
368 I != E; ++I, ++ArgCounter) {
369 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
370 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
371 LangAS::opencl_local) {
372 // Get the location of the error. If a block literal has been passed
373 // (BlockExpr) then we can point straight to the offending argument,
374 // else we just point to the variable reference.
375 SourceLocation ErrorLoc;
376 if (isa<BlockExpr>(BlockArg)) {
377 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
378 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
379 } else if (isa<DeclRefExpr>(BlockArg)) {
380 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
381 }
382 S.Diag(ErrorLoc,
383 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
384 IllegalParams = true;
385 }
386 }
387
388 return IllegalParams;
389}
390
Joey Gouly84ae3362017-07-31 15:15:59 +0000391static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
392 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
393 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
394 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
395 return true;
396 }
397 return false;
398}
399
Joey Goulyfa76b492017-08-01 13:27:09 +0000400static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
401 if (checkArgCount(S, TheCall, 2))
402 return true;
403
404 if (checkOpenCLSubgroupExt(S, TheCall))
405 return true;
406
407 // First argument is an ndrange_t type.
408 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000409 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000410 S.Diag(NDRangeArg->getLocStart(),
411 diag::err_opencl_builtin_expected_type)
412 << TheCall->getDirectCallee() << "'ndrange_t'";
413 return true;
414 }
415
416 Expr *BlockArg = TheCall->getArg(1);
417 if (!isBlockPointer(BlockArg)) {
418 S.Diag(BlockArg->getLocStart(),
419 diag::err_opencl_builtin_expected_type)
420 << TheCall->getDirectCallee() << "block";
421 return true;
422 }
423 return checkOpenCLBlockArgs(S, BlockArg);
424}
425
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000426/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
427/// get_kernel_work_group_size
428/// and get_kernel_preferred_work_group_size_multiple builtin functions.
429static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
430 if (checkArgCount(S, TheCall, 1))
431 return true;
432
433 Expr *BlockArg = TheCall->getArg(0);
434 if (!isBlockPointer(BlockArg)) {
435 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000436 diag::err_opencl_builtin_expected_type)
437 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000438 return true;
439 }
440 return checkOpenCLBlockArgs(S, BlockArg);
441}
442
Simon Pilgrim2c518802017-03-30 14:13:19 +0000443/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000444static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
445 const QualType &IntType);
446
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000447static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000448 unsigned Start, unsigned End) {
449 bool IllegalParams = false;
450 for (unsigned I = Start; I <= End; ++I)
451 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
452 S.Context.getSizeType());
453 return IllegalParams;
454}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000455
456/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
457/// 'local void*' parameter of passed block.
458static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
459 Expr *BlockArg,
460 unsigned NumNonVarArgs) {
461 const BlockPointerType *BPT =
462 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
463 unsigned NumBlockParams =
464 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
465 unsigned TotalNumArgs = TheCall->getNumArgs();
466
467 // For each argument passed to the block, a corresponding uint needs to
468 // be passed to describe the size of the local memory.
469 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
470 S.Diag(TheCall->getLocStart(),
471 diag::err_opencl_enqueue_kernel_local_size_args);
472 return true;
473 }
474
475 // Check that the sizes of the local memory are specified by integers.
476 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
477 TotalNumArgs - 1);
478}
479
480/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
481/// overload formats specified in Table 6.13.17.1.
482/// int enqueue_kernel(queue_t queue,
483/// kernel_enqueue_flags_t flags,
484/// const ndrange_t ndrange,
485/// void (^block)(void))
486/// int enqueue_kernel(queue_t queue,
487/// kernel_enqueue_flags_t flags,
488/// const ndrange_t ndrange,
489/// uint num_events_in_wait_list,
490/// clk_event_t *event_wait_list,
491/// clk_event_t *event_ret,
492/// void (^block)(void))
493/// int enqueue_kernel(queue_t queue,
494/// kernel_enqueue_flags_t flags,
495/// const ndrange_t ndrange,
496/// void (^block)(local void*, ...),
497/// uint size0, ...)
498/// int enqueue_kernel(queue_t queue,
499/// kernel_enqueue_flags_t flags,
500/// const ndrange_t ndrange,
501/// uint num_events_in_wait_list,
502/// clk_event_t *event_wait_list,
503/// clk_event_t *event_ret,
504/// void (^block)(local void*, ...),
505/// uint size0, ...)
506static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
507 unsigned NumArgs = TheCall->getNumArgs();
508
509 if (NumArgs < 4) {
510 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
511 return true;
512 }
513
514 Expr *Arg0 = TheCall->getArg(0);
515 Expr *Arg1 = TheCall->getArg(1);
516 Expr *Arg2 = TheCall->getArg(2);
517 Expr *Arg3 = TheCall->getArg(3);
518
519 // First argument always needs to be a queue_t type.
520 if (!Arg0->getType()->isQueueT()) {
521 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000522 diag::err_opencl_builtin_expected_type)
523 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000524 return true;
525 }
526
527 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
528 if (!Arg1->getType()->isIntegerType()) {
529 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000530 diag::err_opencl_builtin_expected_type)
531 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000532 return true;
533 }
534
535 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000536 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000537 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000538 diag::err_opencl_builtin_expected_type)
539 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000540 return true;
541 }
542
543 // With four arguments, there is only one form that the function could be
544 // called in: no events and no variable arguments.
545 if (NumArgs == 4) {
546 // check that the last argument is the right block type.
547 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000548 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
549 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000550 return true;
551 }
552 // we have a block type, check the prototype
553 const BlockPointerType *BPT =
554 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
555 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
556 S.Diag(Arg3->getLocStart(),
557 diag::err_opencl_enqueue_kernel_blocks_no_args);
558 return true;
559 }
560 return false;
561 }
562 // we can have block + varargs.
563 if (isBlockPointer(Arg3))
564 return (checkOpenCLBlockArgs(S, Arg3) ||
565 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
566 // last two cases with either exactly 7 args or 7 args and varargs.
567 if (NumArgs >= 7) {
568 // check common block argument.
569 Expr *Arg6 = TheCall->getArg(6);
570 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000571 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
572 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000573 return true;
574 }
575 if (checkOpenCLBlockArgs(S, Arg6))
576 return true;
577
578 // Forth argument has to be any integer type.
579 if (!Arg3->getType()->isIntegerType()) {
580 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000581 diag::err_opencl_builtin_expected_type)
582 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000583 return true;
584 }
585 // check remaining common arguments.
586 Expr *Arg4 = TheCall->getArg(4);
587 Expr *Arg5 = TheCall->getArg(5);
588
Anastasia Stulova2b461202016-11-14 15:34:01 +0000589 // Fifth argument is always passed as a pointer to clk_event_t.
590 if (!Arg4->isNullPointerConstant(S.Context,
591 Expr::NPC_ValueDependentIsNotNull) &&
592 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000593 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000594 diag::err_opencl_builtin_expected_type)
595 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000596 << S.Context.getPointerType(S.Context.OCLClkEventTy);
597 return true;
598 }
599
Anastasia Stulova2b461202016-11-14 15:34:01 +0000600 // Sixth argument is always passed as a pointer to clk_event_t.
601 if (!Arg5->isNullPointerConstant(S.Context,
602 Expr::NPC_ValueDependentIsNotNull) &&
603 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000604 Arg5->getType()->getPointeeType()->isClkEventT())) {
605 S.Diag(TheCall->getArg(5)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000606 diag::err_opencl_builtin_expected_type)
607 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000608 << S.Context.getPointerType(S.Context.OCLClkEventTy);
609 return true;
610 }
611
612 if (NumArgs == 7)
613 return false;
614
615 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
616 }
617
618 // None of the specific case has been detected, give generic error
619 S.Diag(TheCall->getLocStart(),
620 diag::err_opencl_enqueue_kernel_incorrect_args);
621 return true;
622}
623
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000624/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000625static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000626 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000627}
628
629/// Returns true if pipe element type is different from the pointer.
630static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
631 const Expr *Arg0 = Call->getArg(0);
632 // First argument type should always be pipe.
633 if (!Arg0->getType()->isPipeType()) {
634 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000635 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000636 return true;
637 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000638 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000639 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
640 // Validates the access qualifier is compatible with the call.
641 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
642 // read_only and write_only, and assumed to be read_only if no qualifier is
643 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000644 switch (Call->getDirectCallee()->getBuiltinID()) {
645 case Builtin::BIread_pipe:
646 case Builtin::BIreserve_read_pipe:
647 case Builtin::BIcommit_read_pipe:
648 case Builtin::BIwork_group_reserve_read_pipe:
649 case Builtin::BIsub_group_reserve_read_pipe:
650 case Builtin::BIwork_group_commit_read_pipe:
651 case Builtin::BIsub_group_commit_read_pipe:
652 if (!(!AccessQual || AccessQual->isReadOnly())) {
653 S.Diag(Arg0->getLocStart(),
654 diag::err_opencl_builtin_pipe_invalid_access_modifier)
655 << "read_only" << Arg0->getSourceRange();
656 return true;
657 }
658 break;
659 case Builtin::BIwrite_pipe:
660 case Builtin::BIreserve_write_pipe:
661 case Builtin::BIcommit_write_pipe:
662 case Builtin::BIwork_group_reserve_write_pipe:
663 case Builtin::BIsub_group_reserve_write_pipe:
664 case Builtin::BIwork_group_commit_write_pipe:
665 case Builtin::BIsub_group_commit_write_pipe:
666 if (!(AccessQual && AccessQual->isWriteOnly())) {
667 S.Diag(Arg0->getLocStart(),
668 diag::err_opencl_builtin_pipe_invalid_access_modifier)
669 << "write_only" << Arg0->getSourceRange();
670 return true;
671 }
672 break;
673 default:
674 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000675 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000676 return false;
677}
678
679/// Returns true if pipe element type is different from the pointer.
680static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
681 const Expr *Arg0 = Call->getArg(0);
682 const Expr *ArgIdx = Call->getArg(Idx);
683 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000684 const QualType EltTy = PipeTy->getElementType();
685 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000686 // The Idx argument should be a pointer and the type of the pointer and
687 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000688 if (!ArgTy ||
689 !S.Context.hasSameType(
690 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000691 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000692 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000693 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000694 return true;
695 }
696 return false;
697}
698
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000699// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000700// \param S Reference to the semantic analyzer.
701// \param Call A pointer to the builtin call.
702// \return True if a semantic error has been found, false otherwise.
703static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000704 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
705 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000706 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000707 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000708 if (checkOpenCLPipeArg(S, Call))
709 return true;
710 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000711 // read/write_pipe(pipe T, T*).
712 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000713 if (checkOpenCLPipePacketType(S, Call, 1))
714 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000715 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000716
717 case 4: {
718 if (checkOpenCLPipeArg(S, Call))
719 return true;
720 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000721 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
722 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000723 if (!Call->getArg(1)->getType()->isReserveIDT()) {
724 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000725 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000726 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000727 return true;
728 }
729
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000730 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000731 const Expr *Arg2 = Call->getArg(2);
732 if (!Arg2->getType()->isIntegerType() &&
733 !Arg2->getType()->isUnsignedIntegerType()) {
734 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000735 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000736 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000737 return true;
738 }
739
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000740 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000741 if (checkOpenCLPipePacketType(S, Call, 3))
742 return true;
743 } break;
744 default:
745 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000746 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000747 return true;
748 }
749
750 return false;
751}
752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000753// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000754// /_}reserve_{read/write}_pipe
755// \param S Reference to the semantic analyzer.
756// \param Call The call to the builtin function to be analyzed.
757// \return True if a semantic error was found, false otherwise.
758static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
759 if (checkArgCount(S, Call, 2))
760 return true;
761
762 if (checkOpenCLPipeArg(S, Call))
763 return true;
764
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000765 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000766 if (!Call->getArg(1)->getType()->isIntegerType() &&
767 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
768 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000769 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000770 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000771 return true;
772 }
773
Joey Gouly922ca232017-08-09 14:52:47 +0000774 // Since return type of reserve_read/write_pipe built-in function is
Aaron Ballman68d50642018-06-19 14:53:20 +0000775 // reserve_id_t, which is not defined in the builtin def file , we used int
776 // as return type and need to override the return type of these functions.
777 Call->setType(S.Context.OCLReserveIDTy);
778
779 return false;
780}
781
782// Performs a semantic analysis on {work_group_/sub_group_
783// /_}commit_{read/write}_pipe
784// \param S Reference to the semantic analyzer.
785// \param Call The call to the builtin function to be analyzed.
786// \return True if a semantic error was found, false otherwise.
787static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
788 if (checkArgCount(S, Call, 2))
789 return true;
790
791 if (checkOpenCLPipeArg(S, Call))
792 return true;
793
794 // Check reserve_id_t.
795 if (!Call->getArg(1)->getType()->isReserveIDT()) {
796 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
797 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
798 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
799 return true;
800 }
801
802 return false;
803}
804
805// Performs a semantic analysis on the call to built-in Pipe
806// Query Functions.
807// \param S Reference to the semantic analyzer.
808// \param Call The call to the builtin function to be analyzed.
809// \return True if a semantic error was found, false otherwise.
810static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
811 if (checkArgCount(S, Call, 1))
812 return true;
813
814 if (!Call->getArg(0)->getType()->isPipeType()) {
815 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
816 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
817 return true;
818 }
819
820 return false;
821}
822
823// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
824// Performs semantic analysis for the to_global/local/private call.
825// \param S Reference to the semantic analyzer.
826// \param BuiltinID ID of the builtin function.
827// \param Call A pointer to the builtin call.
828// \return True if a semantic error has been found, false otherwise.
829static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
830 CallExpr *Call) {
831 if (Call->getNumArgs() != 1) {
832 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
833 << Call->getDirectCallee() << Call->getSourceRange();
834 return true;
835 }
836
837 auto RT = Call->getArg(0)->getType();
838 if (!RT->isPointerType() || RT->getPointeeType()
839 .getAddressSpace() == LangAS::opencl_constant) {
840 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
841 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
842 return true;
843 }
844
845 RT = RT->getPointeeType();
846 auto Qual = RT.getQualifiers();
847 switch (BuiltinID) {
848 case Builtin::BIto_global:
849 Qual.setAddressSpace(LangAS::opencl_global);
850 break;
851 case Builtin::BIto_local:
852 Qual.setAddressSpace(LangAS::opencl_local);
853 break;
854 case Builtin::BIto_private:
855 Qual.setAddressSpace(LangAS::opencl_private);
856 break;
857 default:
858 llvm_unreachable("Invalid builtin function");
859 }
860 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
861 RT.getUnqualifiedType(), Qual)));
862
863 return false;
864}
865
866// Emit an error and return true if the current architecture is not in the list
867// of supported architectures.
868static bool
869CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
870 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
871 llvm::Triple::ArchType CurArch =
872 S.getASTContext().getTargetInfo().getTriple().getArch();
873 if (llvm::is_contained(SupportedArchs, CurArch))
874 return false;
875 S.Diag(TheCall->getLocStart(), diag::err_builtin_target_unsupported)
876 << TheCall->getSourceRange();
877 return true;
878}
879
880ExprResult
881Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
882 CallExpr *TheCall) {
883 ExprResult TheCallResult(TheCall);
884
885 // Find out if any arguments are required to be integer constant expressions.
886 unsigned ICEArguments = 0;
887 ASTContext::GetBuiltinTypeError Error;
888 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
889 if (Error != ASTContext::GE_None)
890 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
891
892 // If any arguments are required to be ICE's, check and diagnose.
893 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
894 // Skip arguments not required to be ICE's.
895 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
896
897 llvm::APSInt Result;
898 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
899 return true;
900 ICEArguments &= ~(1 << ArgNo);
901 }
902
903 switch (BuiltinID) {
904 case Builtin::BI__builtin___CFStringMakeConstantString:
905 assert(TheCall->getNumArgs() == 1 &&
906 "Wrong # arguments to builtin CFStringMakeConstantString");
907 if (CheckObjCString(TheCall->getArg(0)))
908 return ExprError();
909 break;
910 case Builtin::BI__builtin_ms_va_start:
911 case Builtin::BI__builtin_stdarg_start:
912 case Builtin::BI__builtin_va_start:
913 if (SemaBuiltinVAStart(BuiltinID, TheCall))
914 return ExprError();
915 break;
916 case Builtin::BI__va_start: {
917 switch (Context.getTargetInfo().getTriple().getArch()) {
918 case llvm::Triple::arm:
919 case llvm::Triple::thumb:
920 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
921 return ExprError();
922 break;
923 default:
924 if (SemaBuiltinVAStart(BuiltinID, TheCall))
925 return ExprError();
926 break;
927 }
928 break;
929 }
930
931 // The acquire, release, and no fence variants are ARM and AArch64 only.
932 case Builtin::BI_interlockedbittestandset_acq:
933 case Builtin::BI_interlockedbittestandset_rel:
934 case Builtin::BI_interlockedbittestandset_nf:
935 case Builtin::BI_interlockedbittestandreset_acq:
936 case Builtin::BI_interlockedbittestandreset_rel:
937 case Builtin::BI_interlockedbittestandreset_nf:
938 if (CheckBuiltinTargetSupport(
939 *this, BuiltinID, TheCall,
940 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
941 return ExprError();
942 break;
943
944 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
945 case Builtin::BI_bittest64:
946 case Builtin::BI_bittestandcomplement64:
947 case Builtin::BI_bittestandreset64:
948 case Builtin::BI_bittestandset64:
949 case Builtin::BI_interlockedbittestandreset64:
950 case Builtin::BI_interlockedbittestandset64:
951 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
952 {llvm::Triple::x86_64, llvm::Triple::arm,
953 llvm::Triple::thumb, llvm::Triple::aarch64}))
954 return ExprError();
955 break;
956
957 case Builtin::BI__builtin_isgreater:
958 case Builtin::BI__builtin_isgreaterequal:
959 case Builtin::BI__builtin_isless:
960 case Builtin::BI__builtin_islessequal:
961 case Builtin::BI__builtin_islessgreater:
962 case Builtin::BI__builtin_isunordered:
963 if (SemaBuiltinUnorderedCompare(TheCall))
964 return ExprError();
965 break;
966 case Builtin::BI__builtin_fpclassify:
967 if (SemaBuiltinFPClassification(TheCall, 6))
968 return ExprError();
969 break;
970 case Builtin::BI__builtin_isfinite:
971 case Builtin::BI__builtin_isinf:
972 case Builtin::BI__builtin_isinf_sign:
973 case Builtin::BI__builtin_isnan:
974 case Builtin::BI__builtin_isnormal:
Aaron Ballmandd0e2b02018-06-19 14:59:11 +0000975 case Builtin::BI__builtin_signbit:
976 case Builtin::BI__builtin_signbitf:
977 case Builtin::BI__builtin_signbitl:
Aaron Ballman68d50642018-06-19 14:53:20 +0000978 if (SemaBuiltinFPClassification(TheCall, 1))
979 return ExprError();
980 break;
981 case Builtin::BI__builtin_shufflevector:
982 return SemaBuiltinShuffleVector(TheCall);
983 // TheCall will be freed by the smart pointer here, but that's fine, since
984 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
985 case Builtin::BI__builtin_prefetch:
986 if (SemaBuiltinPrefetch(TheCall))
987 return ExprError();
988 break;
989 case Builtin::BI__builtin_alloca_with_align:
990 if (SemaBuiltinAllocaWithAlign(TheCall))
991 return ExprError();
992 break;
993 case Builtin::BI__assume:
994 case Builtin::BI__builtin_assume:
995 if (SemaBuiltinAssume(TheCall))
996 return ExprError();
997 break;
998 case Builtin::BI__builtin_assume_aligned:
999 if (SemaBuiltinAssumeAligned(TheCall))
1000 return ExprError();
1001 break;
1002 case Builtin::BI__builtin_object_size:
1003 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1004 return ExprError();
1005 break;
1006 case Builtin::BI__builtin_longjmp:
1007 if (SemaBuiltinLongjmp(TheCall))
1008 return ExprError();
1009 break;
1010 case Builtin::BI__builtin_setjmp:
1011 if (SemaBuiltinSetjmp(TheCall))
1012 return ExprError();
1013 break;
1014 case Builtin::BI_setjmp:
1015 case Builtin::BI_setjmpex:
1016 if (checkArgCount(*this, TheCall, 1))
1017 return true;
1018 break;
1019 case Builtin::BI__builtin_classify_type:
1020 if (checkArgCount(*this, TheCall, 1)) return true;
1021 TheCall->setType(Context.IntTy);
1022 break;
1023 case Builtin::BI__builtin_constant_p:
1024 if (checkArgCount(*this, TheCall, 1)) return true;
1025 TheCall->setType(Context.IntTy);
1026 break;
1027 case Builtin::BI__sync_fetch_and_add:
1028 case Builtin::BI__sync_fetch_and_add_1:
1029 case Builtin::BI__sync_fetch_and_add_2:
1030 case Builtin::BI__sync_fetch_and_add_4:
1031 case Builtin::BI__sync_fetch_and_add_8:
1032 case Builtin::BI__sync_fetch_and_add_16:
1033 case Builtin::BI__sync_fetch_and_sub:
1034 case Builtin::BI__sync_fetch_and_sub_1:
1035 case Builtin::BI__sync_fetch_and_sub_2:
1036 case Builtin::BI__sync_fetch_and_sub_4:
1037 case Builtin::BI__sync_fetch_and_sub_8:
1038 case Builtin::BI__sync_fetch_and_sub_16:
1039 case Builtin::BI__sync_fetch_and_or:
1040 case Builtin::BI__sync_fetch_and_or_1:
1041 case Builtin::BI__sync_fetch_and_or_2:
1042 case Builtin::BI__sync_fetch_and_or_4:
1043 case Builtin::BI__sync_fetch_and_or_8:
1044 case Builtin::BI__sync_fetch_and_or_16:
1045 case Builtin::BI__sync_fetch_and_and:
1046 case Builtin::BI__sync_fetch_and_and_1:
1047 case Builtin::BI__sync_fetch_and_and_2:
1048 case Builtin::BI__sync_fetch_and_and_4:
1049 case Builtin::BI__sync_fetch_and_and_8:
1050 case Builtin::BI__sync_fetch_and_and_16:
1051 case Builtin::BI__sync_fetch_and_xor:
1052 case Builtin::BI__sync_fetch_and_xor_1:
1053 case Builtin::BI__sync_fetch_and_xor_2:
1054 case Builtin::BI__sync_fetch_and_xor_4:
1055 case Builtin::BI__sync_fetch_and_xor_8:
1056 case Builtin::BI__sync_fetch_and_xor_16:
1057 case Builtin::BI__sync_fetch_and_nand:
1058 case Builtin::BI__sync_fetch_and_nand_1:
1059 case Builtin::BI__sync_fetch_and_nand_2:
1060 case Builtin::BI__sync_fetch_and_nand_4:
1061 case Builtin::BI__sync_fetch_and_nand_8:
1062 case Builtin::BI__sync_fetch_and_nand_16:
1063 case Builtin::BI__sync_add_and_fetch:
1064 case Builtin::BI__sync_add_and_fetch_1:
1065 case Builtin::BI__sync_add_and_fetch_2:
1066 case Builtin::BI__sync_add_and_fetch_4:
1067 case Builtin::BI__sync_add_and_fetch_8:
1068 case Builtin::BI__sync_add_and_fetch_16:
1069 case Builtin::BI__sync_sub_and_fetch:
1070 case Builtin::BI__sync_sub_and_fetch_1:
1071 case Builtin::BI__sync_sub_and_fetch_2:
1072 case Builtin::BI__sync_sub_and_fetch_4:
1073 case Builtin::BI__sync_sub_and_fetch_8:
1074 case Builtin::BI__sync_sub_and_fetch_16:
1075 case Builtin::BI__sync_and_and_fetch:
1076 case Builtin::BI__sync_and_and_fetch_1:
1077 case Builtin::BI__sync_and_and_fetch_2:
1078 case Builtin::BI__sync_and_and_fetch_4:
1079 case Builtin::BI__sync_and_and_fetch_8:
1080 case Builtin::BI__sync_and_and_fetch_16:
1081 case Builtin::BI__sync_or_and_fetch:
1082 case Builtin::BI__sync_or_and_fetch_1:
1083 case Builtin::BI__sync_or_and_fetch_2:
1084 case Builtin::BI__sync_or_and_fetch_4:
1085 case Builtin::BI__sync_or_and_fetch_8:
1086 case Builtin::BI__sync_or_and_fetch_16:
1087 case Builtin::BI__sync_xor_and_fetch:
1088 case Builtin::BI__sync_xor_and_fetch_1:
1089 case Builtin::BI__sync_xor_and_fetch_2:
1090 case Builtin::BI__sync_xor_and_fetch_4:
1091 case Builtin::BI__sync_xor_and_fetch_8:
1092 case Builtin::BI__sync_xor_and_fetch_16:
1093 case Builtin::BI__sync_nand_and_fetch:
1094 case Builtin::BI__sync_nand_and_fetch_1:
1095 case Builtin::BI__sync_nand_and_fetch_2:
1096 case Builtin::BI__sync_nand_and_fetch_4:
1097 case Builtin::BI__sync_nand_and_fetch_8:
1098 case Builtin::BI__sync_nand_and_fetch_16:
1099 case Builtin::BI__sync_val_compare_and_swap:
1100 case Builtin::BI__sync_val_compare_and_swap_1:
1101 case Builtin::BI__sync_val_compare_and_swap_2:
1102 case Builtin::BI__sync_val_compare_and_swap_4:
1103 case Builtin::BI__sync_val_compare_and_swap_8:
1104 case Builtin::BI__sync_val_compare_and_swap_16:
1105 case Builtin::BI__sync_bool_compare_and_swap:
1106 case Builtin::BI__sync_bool_compare_and_swap_1:
1107 case Builtin::BI__sync_bool_compare_and_swap_2:
1108 case Builtin::BI__sync_bool_compare_and_swap_4:
1109 case Builtin::BI__sync_bool_compare_and_swap_8:
1110 case Builtin::BI__sync_bool_compare_and_swap_16:
1111 case Builtin::BI__sync_lock_test_and_set:
1112 case Builtin::BI__sync_lock_test_and_set_1:
1113 case Builtin::BI__sync_lock_test_and_set_2:
1114 case Builtin::BI__sync_lock_test_and_set_4:
1115 case Builtin::BI__sync_lock_test_and_set_8:
1116 case Builtin::BI__sync_lock_test_and_set_16:
1117 case Builtin::BI__sync_lock_release:
1118 case Builtin::BI__sync_lock_release_1:
1119 case Builtin::BI__sync_lock_release_2:
1120 case Builtin::BI__sync_lock_release_4:
1121 case Builtin::BI__sync_lock_release_8:
1122 case Builtin::BI__sync_lock_release_16:
1123 case Builtin::BI__sync_swap:
1124 case Builtin::BI__sync_swap_1:
1125 case Builtin::BI__sync_swap_2:
1126 case Builtin::BI__sync_swap_4:
1127 case Builtin::BI__sync_swap_8:
1128 case Builtin::BI__sync_swap_16:
1129 return SemaBuiltinAtomicOverloaded(TheCallResult);
1130 case Builtin::BI__builtin_nontemporal_load:
1131 case Builtin::BI__builtin_nontemporal_store:
1132 return SemaBuiltinNontemporalOverloaded(TheCallResult);
1133#define BUILTIN(ID, TYPE, ATTRS)
1134#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1135 case Builtin::BI##ID: \
1136 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1137#include "clang/Basic/Builtins.def"
1138 case Builtin::BI__annotation:
1139 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1140 return ExprError();
1141 break;
1142 case Builtin::BI__builtin_annotation:
1143 if (SemaBuiltinAnnotation(*this, TheCall))
1144 return ExprError();
1145 break;
1146 case Builtin::BI__builtin_addressof:
1147 if (SemaBuiltinAddressof(*this, TheCall))
1148 return ExprError();
1149 break;
1150 case Builtin::BI__builtin_add_overflow:
1151 case Builtin::BI__builtin_sub_overflow:
1152 case Builtin::BI__builtin_mul_overflow:
1153 if (SemaBuiltinOverflow(*this, TheCall))
1154 return ExprError();
1155 break;
1156 case Builtin::BI__builtin_operator_new:
1157 case Builtin::BI__builtin_operator_delete: {
1158 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1159 ExprResult Res =
1160 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1161 if (Res.isInvalid())
1162 CorrectDelayedTyposInExpr(TheCallResult.get());
1163 return Res;
1164 }
1165 case Builtin::BI__builtin_dump_struct: {
1166 // We first want to ensure we are called with 2 arguments
1167 if (checkArgCount(*this, TheCall, 2))
1168 return ExprError();
1169 // Ensure that the first argument is of type 'struct XX *'
1170 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1171 const QualType PtrArgType = PtrArg->getType();
1172 if (!PtrArgType->isPointerType() ||
1173 !PtrArgType->getPointeeType()->isRecordType()) {
1174 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1175 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1176 << "structure pointer";
1177 return ExprError();
Aaron Ballman06525342018-04-10 21:58:13 +00001178 }
1179
1180 // Ensure that the second argument is of type 'FunctionType'
1181 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1182 const QualType FnPtrArgType = FnPtrArg->getType();
1183 if (!FnPtrArgType->isPointerType()) {
1184 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1185 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1186 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1187 return ExprError();
1188 }
1189
1190 const auto *FuncType =
1191 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1192
1193 if (!FuncType) {
1194 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1195 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1196 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1197 return ExprError();
1198 }
1199
1200 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1201 if (!FT->getNumParams()) {
1202 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1203 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1204 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1205 return ExprError();
1206 }
1207 QualType PT = FT->getParamType(0);
1208 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1209 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1210 !PT->getPointeeType().isConstQualified()) {
1211 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1212 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1213 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1214 return ExprError();
1215 }
1216 }
1217
1218 TheCall->setType(Context.IntTy);
1219 break;
1220 }
1221
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001222 // check secure string manipulation functions where overflows
1223 // are detectable at compile time
1224 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001225 case Builtin::BI__builtin___memmove_chk:
1226 case Builtin::BI__builtin___memset_chk:
1227 case Builtin::BI__builtin___strlcat_chk:
1228 case Builtin::BI__builtin___strlcpy_chk:
1229 case Builtin::BI__builtin___strncat_chk:
1230 case Builtin::BI__builtin___strncpy_chk:
1231 case Builtin::BI__builtin___stpncpy_chk:
1232 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1233 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001234 case Builtin::BI__builtin___memccpy_chk:
1235 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1236 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001237 case Builtin::BI__builtin___snprintf_chk:
1238 case Builtin::BI__builtin___vsnprintf_chk:
1239 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1240 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001241 case Builtin::BI__builtin_call_with_static_chain:
1242 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1243 return ExprError();
1244 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001245 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001246 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001247 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1248 diag::err_seh___except_block))
1249 return ExprError();
1250 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001251 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001252 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001253 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1254 diag::err_seh___except_filter))
1255 return ExprError();
1256 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001257 case Builtin::BI__GetExceptionInfo:
1258 if (checkArgCount(*this, TheCall, 1))
1259 return ExprError();
1260
1261 if (CheckCXXThrowOperand(
1262 TheCall->getLocStart(),
1263 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1264 TheCall))
1265 return ExprError();
1266
1267 TheCall->setType(Context.VoidPtrTy);
1268 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001269 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001270 case Builtin::BIread_pipe:
1271 case Builtin::BIwrite_pipe:
1272 // Since those two functions are declared with var args, we need a semantic
1273 // check for the argument.
1274 if (SemaBuiltinRWPipe(*this, TheCall))
1275 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001276 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001277 break;
1278 case Builtin::BIreserve_read_pipe:
1279 case Builtin::BIreserve_write_pipe:
1280 case Builtin::BIwork_group_reserve_read_pipe:
1281 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001282 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1283 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001284 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001285 case Builtin::BIsub_group_reserve_read_pipe:
1286 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001287 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1288 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001289 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001290 break;
1291 case Builtin::BIcommit_read_pipe:
1292 case Builtin::BIcommit_write_pipe:
1293 case Builtin::BIwork_group_commit_read_pipe:
1294 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001295 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1296 return ExprError();
1297 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001298 case Builtin::BIsub_group_commit_read_pipe:
1299 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001300 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1301 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001302 return ExprError();
1303 break;
1304 case Builtin::BIget_pipe_num_packets:
1305 case Builtin::BIget_pipe_max_packets:
1306 if (SemaBuiltinPipePackets(*this, TheCall))
1307 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001308 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001309 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001310 case Builtin::BIto_global:
1311 case Builtin::BIto_local:
1312 case Builtin::BIto_private:
1313 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1314 return ExprError();
1315 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001316 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1317 case Builtin::BIenqueue_kernel:
1318 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1319 return ExprError();
1320 break;
1321 case Builtin::BIget_kernel_work_group_size:
1322 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1323 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1324 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001325 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001326 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1327 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1328 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1329 return ExprError();
1330 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001331 case Builtin::BI__builtin_os_log_format:
1332 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001333 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001334 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001335 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001336 }
Richard Smith760520b2014-06-03 23:27:44 +00001337
Nate Begeman4904e322010-06-08 02:47:44 +00001338 // Since the target specific builtins for each arch overlap, only check those
1339 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001340 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001341 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001342 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001343 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001344 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001345 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001346 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1347 return ExprError();
1348 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001349 case llvm::Triple::aarch64:
1350 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001351 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001352 return ExprError();
1353 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001354 case llvm::Triple::hexagon:
1355 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1356 return ExprError();
1357 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001358 case llvm::Triple::mips:
1359 case llvm::Triple::mipsel:
1360 case llvm::Triple::mips64:
1361 case llvm::Triple::mips64el:
1362 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1363 return ExprError();
1364 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001365 case llvm::Triple::systemz:
1366 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1367 return ExprError();
1368 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001369 case llvm::Triple::x86:
1370 case llvm::Triple::x86_64:
1371 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1372 return ExprError();
1373 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001374 case llvm::Triple::ppc:
1375 case llvm::Triple::ppc64:
1376 case llvm::Triple::ppc64le:
1377 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1378 return ExprError();
1379 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001380 default:
1381 break;
1382 }
1383 }
1384
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001385 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001386}
1387
Nate Begeman91e1fea2010-06-14 05:21:25 +00001388// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001389static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001390 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001391 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001392 switch (Type.getEltType()) {
1393 case NeonTypeFlags::Int8:
1394 case NeonTypeFlags::Poly8:
1395 return shift ? 7 : (8 << IsQuad) - 1;
1396 case NeonTypeFlags::Int16:
1397 case NeonTypeFlags::Poly16:
1398 return shift ? 15 : (4 << IsQuad) - 1;
1399 case NeonTypeFlags::Int32:
1400 return shift ? 31 : (2 << IsQuad) - 1;
1401 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001402 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001403 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001404 case NeonTypeFlags::Poly128:
1405 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001406 case NeonTypeFlags::Float16:
1407 assert(!shift && "cannot shift float types!");
1408 return (4 << IsQuad) - 1;
1409 case NeonTypeFlags::Float32:
1410 assert(!shift && "cannot shift float types!");
1411 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001412 case NeonTypeFlags::Float64:
1413 assert(!shift && "cannot shift float types!");
1414 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001415 }
David Blaikie8a40f702012-01-17 06:56:22 +00001416 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001417}
1418
Bob Wilsone4d77232011-11-08 05:04:11 +00001419/// getNeonEltType - Return the QualType corresponding to the elements of
1420/// the vector type specified by the NeonTypeFlags. This is used to check
1421/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001422static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001423 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001424 switch (Flags.getEltType()) {
1425 case NeonTypeFlags::Int8:
1426 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1427 case NeonTypeFlags::Int16:
1428 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1429 case NeonTypeFlags::Int32:
1430 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1431 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001432 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001433 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1434 else
1435 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1436 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001437 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001438 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001439 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001440 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001441 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001442 if (IsInt64Long)
1443 return Context.UnsignedLongTy;
1444 else
1445 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001446 case NeonTypeFlags::Poly128:
1447 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001448 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001449 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001450 case NeonTypeFlags::Float32:
1451 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001452 case NeonTypeFlags::Float64:
1453 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001454 }
David Blaikie8a40f702012-01-17 06:56:22 +00001455 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001456}
1457
Tim Northover12670412014-02-19 10:37:05 +00001458bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001459 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001460 uint64_t mask = 0;
1461 unsigned TV = 0;
1462 int PtrArgNum = -1;
1463 bool HasConstPtr = false;
1464 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001465#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001466#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001467#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001468#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001469 }
1470
1471 // For NEON intrinsics which are overloaded on vector element type, validate
1472 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001473 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001474 if (mask) {
1475 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1476 return true;
1477
1478 TV = Result.getLimitedValue(64);
1479 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1480 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001481 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001482 }
1483
1484 if (PtrArgNum >= 0) {
1485 // Check that pointer arguments have the specified type.
1486 Expr *Arg = TheCall->getArg(PtrArgNum);
1487 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1488 Arg = ICE->getSubExpr();
1489 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1490 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001491
Tim Northovera2ee4332014-03-29 15:09:45 +00001492 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001493 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1494 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001495 bool IsInt64Long =
1496 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1497 QualType EltTy =
1498 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001499 if (HasConstPtr)
1500 EltTy = EltTy.withConst();
1501 QualType LHSTy = Context.getPointerType(EltTy);
1502 AssignConvertType ConvTy;
1503 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1504 if (RHS.isInvalid())
1505 return true;
1506 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1507 RHS.get(), AA_Assigning))
1508 return true;
1509 }
1510
1511 // For NEON intrinsics which take an immediate value as part of the
1512 // instruction, range check them here.
1513 unsigned i = 0, l = 0, u = 0;
1514 switch (BuiltinID) {
1515 default:
1516 return false;
Luke Geesondc54b372018-06-12 09:54:27 +00001517 #define GET_NEON_IMMEDIATE_CHECK
1518 #include "clang/Basic/arm_neon.inc"
1519 #include "clang/Basic/arm_fp16.inc"
1520 #undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001521 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001522
Richard Sandiford28940af2014-04-16 08:47:51 +00001523 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001524}
1525
Tim Northovera2ee4332014-03-29 15:09:45 +00001526bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1527 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001528 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001529 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001530 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001531 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001532 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001533 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1534 BuiltinID == AArch64::BI__builtin_arm_strex ||
1535 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001536 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001537 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001538 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1539 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1540 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001541
1542 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1543
1544 // Ensure that we have the proper number of arguments.
1545 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1546 return true;
1547
1548 // Inspect the pointer argument of the atomic builtin. This should always be
1549 // a pointer type, whose element is an integral scalar or pointer type.
1550 // Because it is a pointer type, we don't have to worry about any implicit
1551 // casts here.
1552 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1553 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1554 if (PointerArgRes.isInvalid())
1555 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001556 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001557
1558 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1559 if (!pointerType) {
1560 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1561 << PointerArg->getType() << PointerArg->getSourceRange();
1562 return true;
1563 }
1564
1565 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1566 // task is to insert the appropriate casts into the AST. First work out just
1567 // what the appropriate type is.
1568 QualType ValType = pointerType->getPointeeType();
1569 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1570 if (IsLdrex)
1571 AddrType.addConst();
1572
1573 // Issue a warning if the cast is dodgy.
1574 CastKind CastNeeded = CK_NoOp;
1575 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1576 CastNeeded = CK_BitCast;
1577 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1578 << PointerArg->getType()
1579 << Context.getPointerType(AddrType)
1580 << AA_Passing << PointerArg->getSourceRange();
1581 }
1582
1583 // Finally, do the cast and replace the argument with the corrected version.
1584 AddrType = Context.getPointerType(AddrType);
1585 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1586 if (PointerArgRes.isInvalid())
1587 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001588 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001589
1590 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1591
1592 // In general, we allow ints, floats and pointers to be loaded and stored.
1593 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1594 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1595 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1596 << PointerArg->getType() << PointerArg->getSourceRange();
1597 return true;
1598 }
1599
1600 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001601 if (Context.getTypeSize(ValType) > MaxWidth) {
1602 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001603 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1604 << PointerArg->getType() << PointerArg->getSourceRange();
1605 return true;
1606 }
1607
1608 switch (ValType.getObjCLifetime()) {
1609 case Qualifiers::OCL_None:
1610 case Qualifiers::OCL_ExplicitNone:
1611 // okay
1612 break;
1613
1614 case Qualifiers::OCL_Weak:
1615 case Qualifiers::OCL_Strong:
1616 case Qualifiers::OCL_Autoreleasing:
1617 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1618 << ValType << PointerArg->getSourceRange();
1619 return true;
1620 }
1621
Tim Northover6aacd492013-07-16 09:47:53 +00001622 if (IsLdrex) {
1623 TheCall->setType(ValType);
1624 return false;
1625 }
1626
1627 // Initialize the argument to be stored.
1628 ExprResult ValArg = TheCall->getArg(0);
1629 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1630 Context, ValType, /*consume*/ false);
1631 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1632 if (ValArg.isInvalid())
1633 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001634 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001635
1636 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1637 // but the custom checker bypasses all default analysis.
1638 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001639 return false;
1640}
1641
Nate Begeman4904e322010-06-08 02:47:44 +00001642bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001643 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001644 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1645 BuiltinID == ARM::BI__builtin_arm_strex ||
1646 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001647 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001648 }
1649
Yi Kong26d104a2014-08-13 19:18:14 +00001650 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1651 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1652 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1653 }
1654
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001655 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1656 BuiltinID == ARM::BI__builtin_arm_wsr64)
1657 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1658
1659 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1660 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1661 BuiltinID == ARM::BI__builtin_arm_wsr ||
1662 BuiltinID == ARM::BI__builtin_arm_wsrp)
1663 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1664
Tim Northover12670412014-02-19 10:37:05 +00001665 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1666 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001667
Yi Kong4efadfb2014-07-03 16:01:25 +00001668 // For intrinsics which take an immediate value as part of the instruction,
1669 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001670 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001671 switch (BuiltinID) {
1672 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001673 case ARM::BI__builtin_arm_ssat:
1674 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1675 case ARM::BI__builtin_arm_usat:
1676 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1677 case ARM::BI__builtin_arm_ssat16:
1678 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1679 case ARM::BI__builtin_arm_usat16:
1680 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001681 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001682 case ARM::BI__builtin_arm_vcvtr_d:
1683 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001684 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001685 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001686 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001687 case ARM::BI__builtin_arm_dbg:
1688 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001689 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001690}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001691
Tim Northover573cbee2014-05-24 12:52:07 +00001692bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001693 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001694 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001695 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1696 BuiltinID == AArch64::BI__builtin_arm_strex ||
1697 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001698 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1699 }
1700
Yi Konga5548432014-08-13 19:18:20 +00001701 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1702 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1703 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1704 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1705 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1706 }
1707
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001708 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1709 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001710 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001711
1712 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1713 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1714 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1715 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1716 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1717
Tim Northovera2ee4332014-03-29 15:09:45 +00001718 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1719 return true;
1720
Yi Kong19a29ac2014-07-17 10:52:06 +00001721 // For intrinsics which take an immediate value as part of the instruction,
1722 // range check them here.
1723 unsigned i = 0, l = 0, u = 0;
1724 switch (BuiltinID) {
1725 default: return false;
1726 case AArch64::BI__builtin_arm_dmb:
1727 case AArch64::BI__builtin_arm_dsb:
1728 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1729 }
1730
Yi Kong19a29ac2014-07-17 10:52:06 +00001731 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001732}
1733
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001734bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1735 CallExpr *TheCall) {
1736 struct ArgInfo {
1737 ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1738 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1739 unsigned OpNum = 0;
1740 bool IsSigned = false;
1741 unsigned BitWidth = 0;
1742 unsigned Align = 0;
1743 };
1744
1745 static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1746 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
1747 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
1748 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
1749 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
1750 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
1751 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
1752 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
1753 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
1754 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
1755 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
1756 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
1757
1758 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
1759 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
1760 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
1761 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
1762 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
1763 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
1764 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
1765 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
1766 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
1767 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
1768 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
1769
1770 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
1771 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
1772 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
1773 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
1774 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
1775 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
1776 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
1777 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
1778 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
1779 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
1780 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
1781 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
1782 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
1783 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
1784 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
1785 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
1786 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
1787 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
1788 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
1789 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
1790 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
1791 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
1792 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
1793 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
1794 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
1795 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
1796 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
1797 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
1798 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
1799 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
1800 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
1801 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
1802 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
1803 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
1804 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
1805 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
1806 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
1807 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
1808 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
1809 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
1810 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
1811 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
1812 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
1813 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
1814 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
1815 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
1816 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
1817 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
1818 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
1819 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
1820 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
1821 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1822 {{ 1, false, 6, 0 }} },
1823 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
1824 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
1825 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
1826 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
1827 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
1828 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
1829 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1830 {{ 1, false, 5, 0 }} },
1831 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
1832 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
1833 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
1834 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
1835 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
1836 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
1837 { 2, false, 5, 0 }} },
1838 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
1839 { 2, false, 6, 0 }} },
1840 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
1841 { 3, false, 5, 0 }} },
1842 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
1843 { 3, false, 6, 0 }} },
1844 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
1845 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
1846 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
1847 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
1848 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
1849 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
1850 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
1851 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
1852 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
1853 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
1854 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
1855 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
1856 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
1857 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
1858 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
1859 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1860 {{ 2, false, 4, 0 },
1861 { 3, false, 5, 0 }} },
1862 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1863 {{ 2, false, 4, 0 },
1864 { 3, false, 5, 0 }} },
1865 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1866 {{ 2, false, 4, 0 },
1867 { 3, false, 5, 0 }} },
1868 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1869 {{ 2, false, 4, 0 },
1870 { 3, false, 5, 0 }} },
1871 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
1872 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
1873 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
1874 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
1875 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
1876 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
1877 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
1878 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
1879 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
1880 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
1881 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
1882 { 2, false, 5, 0 }} },
1883 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
1884 { 2, false, 6, 0 }} },
1885 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
1886 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
1887 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
1888 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
1889 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
1890 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
1891 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
1892 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
1893 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1894 {{ 1, false, 4, 0 }} },
1895 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
1896 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1897 {{ 1, false, 4, 0 }} },
1898 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
1899 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
1900 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
1901 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
1902 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
1903 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
1904 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
1905 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
1906 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
1907 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
1908 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
1909 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
1910 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
1911 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
1912 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
1913 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
1914 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
1915 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
1916 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
1917 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1918 {{ 3, false, 1, 0 }} },
1919 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
1920 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
1921 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
1922 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1923 {{ 3, false, 1, 0 }} },
1924 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
1925 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
1926 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
1927 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1928 {{ 3, false, 1, 0 }} },
1929 };
1930
1931 auto F = Infos.find(BuiltinID);
1932 if (F == Infos.end())
1933 return false;
1934
1935 bool Error = false;
1936
1937 for (const ArgInfo &A : F->second) {
1938 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1939 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1940 if (!A.Align) {
1941 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1942 } else {
1943 unsigned M = 1 << A.Align;
1944 Min *= M;
1945 Max *= M;
1946 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1947 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1948 }
1949 }
1950 return Error;
1951}
1952
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001953// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1954// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1955// ordering for DSP is unspecified. MSA is ordered by the data format used
1956// by the underlying instruction i.e., df/m, df/n and then by size.
1957//
1958// FIXME: The size tests here should instead be tablegen'd along with the
1959// definitions from include/clang/Basic/BuiltinsMips.def.
1960// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1961// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001962bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001963 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001964 switch (BuiltinID) {
1965 default: return false;
1966 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1967 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001968 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1969 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1970 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1971 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1972 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001973 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1974 // df/m field.
1975 // These intrinsics take an unsigned 3 bit immediate.
1976 case Mips::BI__builtin_msa_bclri_b:
1977 case Mips::BI__builtin_msa_bnegi_b:
1978 case Mips::BI__builtin_msa_bseti_b:
1979 case Mips::BI__builtin_msa_sat_s_b:
1980 case Mips::BI__builtin_msa_sat_u_b:
1981 case Mips::BI__builtin_msa_slli_b:
1982 case Mips::BI__builtin_msa_srai_b:
1983 case Mips::BI__builtin_msa_srari_b:
1984 case Mips::BI__builtin_msa_srli_b:
1985 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1986 case Mips::BI__builtin_msa_binsli_b:
1987 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1988 // These intrinsics take an unsigned 4 bit immediate.
1989 case Mips::BI__builtin_msa_bclri_h:
1990 case Mips::BI__builtin_msa_bnegi_h:
1991 case Mips::BI__builtin_msa_bseti_h:
1992 case Mips::BI__builtin_msa_sat_s_h:
1993 case Mips::BI__builtin_msa_sat_u_h:
1994 case Mips::BI__builtin_msa_slli_h:
1995 case Mips::BI__builtin_msa_srai_h:
1996 case Mips::BI__builtin_msa_srari_h:
1997 case Mips::BI__builtin_msa_srli_h:
1998 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1999 case Mips::BI__builtin_msa_binsli_h:
2000 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002001 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002002 // The first block of intrinsics actually have an unsigned 5 bit field,
2003 // not a df/n field.
2004 case Mips::BI__builtin_msa_clei_u_b:
2005 case Mips::BI__builtin_msa_clei_u_h:
2006 case Mips::BI__builtin_msa_clei_u_w:
2007 case Mips::BI__builtin_msa_clei_u_d:
2008 case Mips::BI__builtin_msa_clti_u_b:
2009 case Mips::BI__builtin_msa_clti_u_h:
2010 case Mips::BI__builtin_msa_clti_u_w:
2011 case Mips::BI__builtin_msa_clti_u_d:
2012 case Mips::BI__builtin_msa_maxi_u_b:
2013 case Mips::BI__builtin_msa_maxi_u_h:
2014 case Mips::BI__builtin_msa_maxi_u_w:
2015 case Mips::BI__builtin_msa_maxi_u_d:
2016 case Mips::BI__builtin_msa_mini_u_b:
2017 case Mips::BI__builtin_msa_mini_u_h:
2018 case Mips::BI__builtin_msa_mini_u_w:
2019 case Mips::BI__builtin_msa_mini_u_d:
2020 case Mips::BI__builtin_msa_addvi_b:
2021 case Mips::BI__builtin_msa_addvi_h:
2022 case Mips::BI__builtin_msa_addvi_w:
2023 case Mips::BI__builtin_msa_addvi_d:
2024 case Mips::BI__builtin_msa_bclri_w:
2025 case Mips::BI__builtin_msa_bnegi_w:
2026 case Mips::BI__builtin_msa_bseti_w:
2027 case Mips::BI__builtin_msa_sat_s_w:
2028 case Mips::BI__builtin_msa_sat_u_w:
2029 case Mips::BI__builtin_msa_slli_w:
2030 case Mips::BI__builtin_msa_srai_w:
2031 case Mips::BI__builtin_msa_srari_w:
2032 case Mips::BI__builtin_msa_srli_w:
2033 case Mips::BI__builtin_msa_srlri_w:
2034 case Mips::BI__builtin_msa_subvi_b:
2035 case Mips::BI__builtin_msa_subvi_h:
2036 case Mips::BI__builtin_msa_subvi_w:
2037 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2038 case Mips::BI__builtin_msa_binsli_w:
2039 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2040 // These intrinsics take an unsigned 6 bit immediate.
2041 case Mips::BI__builtin_msa_bclri_d:
2042 case Mips::BI__builtin_msa_bnegi_d:
2043 case Mips::BI__builtin_msa_bseti_d:
2044 case Mips::BI__builtin_msa_sat_s_d:
2045 case Mips::BI__builtin_msa_sat_u_d:
2046 case Mips::BI__builtin_msa_slli_d:
2047 case Mips::BI__builtin_msa_srai_d:
2048 case Mips::BI__builtin_msa_srari_d:
2049 case Mips::BI__builtin_msa_srli_d:
2050 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2051 case Mips::BI__builtin_msa_binsli_d:
2052 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2053 // These intrinsics take a signed 5 bit immediate.
2054 case Mips::BI__builtin_msa_ceqi_b:
2055 case Mips::BI__builtin_msa_ceqi_h:
2056 case Mips::BI__builtin_msa_ceqi_w:
2057 case Mips::BI__builtin_msa_ceqi_d:
2058 case Mips::BI__builtin_msa_clti_s_b:
2059 case Mips::BI__builtin_msa_clti_s_h:
2060 case Mips::BI__builtin_msa_clti_s_w:
2061 case Mips::BI__builtin_msa_clti_s_d:
2062 case Mips::BI__builtin_msa_clei_s_b:
2063 case Mips::BI__builtin_msa_clei_s_h:
2064 case Mips::BI__builtin_msa_clei_s_w:
2065 case Mips::BI__builtin_msa_clei_s_d:
2066 case Mips::BI__builtin_msa_maxi_s_b:
2067 case Mips::BI__builtin_msa_maxi_s_h:
2068 case Mips::BI__builtin_msa_maxi_s_w:
2069 case Mips::BI__builtin_msa_maxi_s_d:
2070 case Mips::BI__builtin_msa_mini_s_b:
2071 case Mips::BI__builtin_msa_mini_s_h:
2072 case Mips::BI__builtin_msa_mini_s_w:
2073 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2074 // These intrinsics take an unsigned 8 bit immediate.
2075 case Mips::BI__builtin_msa_andi_b:
2076 case Mips::BI__builtin_msa_nori_b:
2077 case Mips::BI__builtin_msa_ori_b:
2078 case Mips::BI__builtin_msa_shf_b:
2079 case Mips::BI__builtin_msa_shf_h:
2080 case Mips::BI__builtin_msa_shf_w:
2081 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2082 case Mips::BI__builtin_msa_bseli_b:
2083 case Mips::BI__builtin_msa_bmnzi_b:
2084 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2085 // df/n format
2086 // These intrinsics take an unsigned 4 bit immediate.
2087 case Mips::BI__builtin_msa_copy_s_b:
2088 case Mips::BI__builtin_msa_copy_u_b:
2089 case Mips::BI__builtin_msa_insve_b:
2090 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002091 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2092 // These intrinsics take an unsigned 3 bit immediate.
2093 case Mips::BI__builtin_msa_copy_s_h:
2094 case Mips::BI__builtin_msa_copy_u_h:
2095 case Mips::BI__builtin_msa_insve_h:
2096 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002097 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2098 // These intrinsics take an unsigned 2 bit immediate.
2099 case Mips::BI__builtin_msa_copy_s_w:
2100 case Mips::BI__builtin_msa_copy_u_w:
2101 case Mips::BI__builtin_msa_insve_w:
2102 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002103 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2104 // These intrinsics take an unsigned 1 bit immediate.
2105 case Mips::BI__builtin_msa_copy_s_d:
2106 case Mips::BI__builtin_msa_copy_u_d:
2107 case Mips::BI__builtin_msa_insve_d:
2108 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002109 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2110 // Memory offsets and immediate loads.
2111 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00002112 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002113 case Mips::BI__builtin_msa_ldi_h:
2114 case Mips::BI__builtin_msa_ldi_w:
2115 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2116 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2117 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2118 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2119 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2120 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2121 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2122 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2123 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00002124 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002125
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002126 if (!m)
2127 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2128
2129 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2130 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002131}
2132
Kit Bartone50adcb2015-03-30 19:40:59 +00002133bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2134 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00002135 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2136 BuiltinID == PPC::BI__builtin_divdeu ||
2137 BuiltinID == PPC::BI__builtin_bpermd;
2138 bool IsTarget64Bit = Context.getTargetInfo()
2139 .getTypeWidth(Context
2140 .getTargetInfo()
2141 .getIntPtrType()) == 64;
2142 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2143 BuiltinID == PPC::BI__builtin_divweu ||
2144 BuiltinID == PPC::BI__builtin_divde ||
2145 BuiltinID == PPC::BI__builtin_divdeu;
2146
2147 if (Is64BitBltin && !IsTarget64Bit)
2148 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2149 << TheCall->getSourceRange();
2150
2151 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2152 (BuiltinID == PPC::BI__builtin_bpermd &&
2153 !Context.getTargetInfo().hasFeature("bpermd")))
2154 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2155 << TheCall->getSourceRange();
2156
Kit Bartone50adcb2015-03-30 19:40:59 +00002157 switch (BuiltinID) {
2158 default: return false;
2159 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2160 case PPC::BI__builtin_altivec_crypto_vshasigmad:
2161 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2162 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2163 case PPC::BI__builtin_tbegin:
2164 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2165 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2166 case PPC::BI__builtin_tabortwc:
2167 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2168 case PPC::BI__builtin_tabortwci:
2169 case PPC::BI__builtin_tabortdci:
2170 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2171 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00002172 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00002173 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00002174 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00002175 }
2176 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2177}
2178
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002179bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2180 CallExpr *TheCall) {
2181 if (BuiltinID == SystemZ::BI__builtin_tabort) {
2182 Expr *Arg = TheCall->getArg(0);
2183 llvm::APSInt AbortCode(32);
2184 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2185 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2186 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2187 << Arg->getSourceRange();
2188 }
2189
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002190 // For intrinsics which take an immediate value as part of the instruction,
2191 // range check them here.
2192 unsigned i = 0, l = 0, u = 0;
2193 switch (BuiltinID) {
2194 default: return false;
2195 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2196 case SystemZ::BI__builtin_s390_verimb:
2197 case SystemZ::BI__builtin_s390_verimh:
2198 case SystemZ::BI__builtin_s390_verimf:
2199 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2200 case SystemZ::BI__builtin_s390_vfaeb:
2201 case SystemZ::BI__builtin_s390_vfaeh:
2202 case SystemZ::BI__builtin_s390_vfaef:
2203 case SystemZ::BI__builtin_s390_vfaebs:
2204 case SystemZ::BI__builtin_s390_vfaehs:
2205 case SystemZ::BI__builtin_s390_vfaefs:
2206 case SystemZ::BI__builtin_s390_vfaezb:
2207 case SystemZ::BI__builtin_s390_vfaezh:
2208 case SystemZ::BI__builtin_s390_vfaezf:
2209 case SystemZ::BI__builtin_s390_vfaezbs:
2210 case SystemZ::BI__builtin_s390_vfaezhs:
2211 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002212 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002213 case SystemZ::BI__builtin_s390_vfidb:
2214 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2215 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002216 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002217 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2218 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2219 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2220 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2221 case SystemZ::BI__builtin_s390_vstrcb:
2222 case SystemZ::BI__builtin_s390_vstrch:
2223 case SystemZ::BI__builtin_s390_vstrcf:
2224 case SystemZ::BI__builtin_s390_vstrczb:
2225 case SystemZ::BI__builtin_s390_vstrczh:
2226 case SystemZ::BI__builtin_s390_vstrczf:
2227 case SystemZ::BI__builtin_s390_vstrcbs:
2228 case SystemZ::BI__builtin_s390_vstrchs:
2229 case SystemZ::BI__builtin_s390_vstrcfs:
2230 case SystemZ::BI__builtin_s390_vstrczbs:
2231 case SystemZ::BI__builtin_s390_vstrczhs:
2232 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002233 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2234 case SystemZ::BI__builtin_s390_vfminsb:
2235 case SystemZ::BI__builtin_s390_vfmaxsb:
2236 case SystemZ::BI__builtin_s390_vfmindb:
2237 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002238 }
2239 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002240}
2241
Craig Topper5ba2c502015-11-07 08:08:31 +00002242/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2243/// This checks that the target supports __builtin_cpu_supports and
2244/// that the string argument is constant and valid.
2245static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2246 Expr *Arg = TheCall->getArg(0);
2247
2248 // Check if the argument is a string literal.
2249 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2250 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2251 << Arg->getSourceRange();
2252
2253 // Check the contents of the string.
2254 StringRef Feature =
2255 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2256 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2257 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2258 << Arg->getSourceRange();
2259 return false;
2260}
2261
Craig Topper699ae0c2017-08-10 20:28:30 +00002262/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2263/// This checks that the target supports __builtin_cpu_is and
2264/// that the string argument is constant and valid.
2265static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2266 Expr *Arg = TheCall->getArg(0);
2267
2268 // Check if the argument is a string literal.
2269 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2270 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2271 << Arg->getSourceRange();
2272
2273 // Check the contents of the string.
2274 StringRef Feature =
2275 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2276 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2277 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2278 << Arg->getSourceRange();
2279 return false;
2280}
2281
Craig Toppera7e253e2016-09-23 04:48:31 +00002282// Check if the rounding mode is legal.
2283bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2284 // Indicates if this instruction has rounding control or just SAE.
2285 bool HasRC = false;
2286
2287 unsigned ArgNum = 0;
2288 switch (BuiltinID) {
2289 default:
2290 return false;
2291 case X86::BI__builtin_ia32_vcvttsd2si32:
2292 case X86::BI__builtin_ia32_vcvttsd2si64:
2293 case X86::BI__builtin_ia32_vcvttsd2usi32:
2294 case X86::BI__builtin_ia32_vcvttsd2usi64:
2295 case X86::BI__builtin_ia32_vcvttss2si32:
2296 case X86::BI__builtin_ia32_vcvttss2si64:
2297 case X86::BI__builtin_ia32_vcvttss2usi32:
2298 case X86::BI__builtin_ia32_vcvttss2usi64:
2299 ArgNum = 1;
2300 break;
Craig Topper2da60bc2018-06-21 05:01:01 +00002301 case X86::BI__builtin_ia32_maxpd512:
2302 case X86::BI__builtin_ia32_maxps512:
2303 case X86::BI__builtin_ia32_minpd512:
2304 case X86::BI__builtin_ia32_minps512:
2305 ArgNum = 2;
2306 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002307 case X86::BI__builtin_ia32_cvtps2pd512_mask:
2308 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2309 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2310 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2311 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2312 case X86::BI__builtin_ia32_cvttps2dq512_mask:
2313 case X86::BI__builtin_ia32_cvttps2qq512_mask:
2314 case X86::BI__builtin_ia32_cvttps2udq512_mask:
2315 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2316 case X86::BI__builtin_ia32_exp2pd_mask:
2317 case X86::BI__builtin_ia32_exp2ps_mask:
2318 case X86::BI__builtin_ia32_getexppd512_mask:
2319 case X86::BI__builtin_ia32_getexpps512_mask:
2320 case X86::BI__builtin_ia32_rcp28pd_mask:
2321 case X86::BI__builtin_ia32_rcp28ps_mask:
2322 case X86::BI__builtin_ia32_rsqrt28pd_mask:
2323 case X86::BI__builtin_ia32_rsqrt28ps_mask:
2324 case X86::BI__builtin_ia32_vcomisd:
2325 case X86::BI__builtin_ia32_vcomiss:
2326 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2327 ArgNum = 3;
2328 break;
2329 case X86::BI__builtin_ia32_cmppd512_mask:
2330 case X86::BI__builtin_ia32_cmpps512_mask:
2331 case X86::BI__builtin_ia32_cmpsd_mask:
2332 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002333 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002334 case X86::BI__builtin_ia32_getexpsd128_round_mask:
2335 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002336 case X86::BI__builtin_ia32_maxsd_round_mask:
2337 case X86::BI__builtin_ia32_maxss_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002338 case X86::BI__builtin_ia32_minsd_round_mask:
2339 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002340 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2341 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2342 case X86::BI__builtin_ia32_reducepd512_mask:
2343 case X86::BI__builtin_ia32_reduceps512_mask:
2344 case X86::BI__builtin_ia32_rndscalepd_mask:
2345 case X86::BI__builtin_ia32_rndscaleps_mask:
2346 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2347 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2348 ArgNum = 4;
2349 break;
2350 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002351 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002352 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002353 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002354 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002355 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002356 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002357 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002358 case X86::BI__builtin_ia32_rangepd512_mask:
2359 case X86::BI__builtin_ia32_rangeps512_mask:
2360 case X86::BI__builtin_ia32_rangesd128_round_mask:
2361 case X86::BI__builtin_ia32_rangess128_round_mask:
2362 case X86::BI__builtin_ia32_reducesd_mask:
2363 case X86::BI__builtin_ia32_reducess_mask:
2364 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2365 case X86::BI__builtin_ia32_rndscaless_round_mask:
2366 ArgNum = 5;
2367 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002368 case X86::BI__builtin_ia32_vcvtsd2si64:
2369 case X86::BI__builtin_ia32_vcvtsd2si32:
2370 case X86::BI__builtin_ia32_vcvtsd2usi32:
2371 case X86::BI__builtin_ia32_vcvtsd2usi64:
2372 case X86::BI__builtin_ia32_vcvtss2si32:
2373 case X86::BI__builtin_ia32_vcvtss2si64:
2374 case X86::BI__builtin_ia32_vcvtss2usi32:
2375 case X86::BI__builtin_ia32_vcvtss2usi64:
2376 ArgNum = 1;
2377 HasRC = true;
2378 break;
Craig Topper3614b412018-06-10 06:01:42 +00002379 case X86::BI__builtin_ia32_addpd512:
2380 case X86::BI__builtin_ia32_addps512:
2381 case X86::BI__builtin_ia32_divpd512:
2382 case X86::BI__builtin_ia32_divps512:
2383 case X86::BI__builtin_ia32_mulpd512:
2384 case X86::BI__builtin_ia32_mulps512:
2385 case X86::BI__builtin_ia32_subpd512:
2386 case X86::BI__builtin_ia32_subps512:
Craig Topper8e066312016-11-07 07:01:09 +00002387 case X86::BI__builtin_ia32_cvtsi2sd64:
2388 case X86::BI__builtin_ia32_cvtsi2ss32:
2389 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002390 case X86::BI__builtin_ia32_cvtusi2sd64:
2391 case X86::BI__builtin_ia32_cvtusi2ss32:
2392 case X86::BI__builtin_ia32_cvtusi2ss64:
2393 ArgNum = 2;
2394 HasRC = true;
2395 break;
2396 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2397 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2398 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2399 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2400 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2401 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2402 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2403 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2404 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2405 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2406 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002407 case X86::BI__builtin_ia32_sqrtpd512_mask:
2408 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002409 ArgNum = 3;
2410 HasRC = true;
2411 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002412 case X86::BI__builtin_ia32_addss_round_mask:
2413 case X86::BI__builtin_ia32_addsd_round_mask:
2414 case X86::BI__builtin_ia32_divss_round_mask:
2415 case X86::BI__builtin_ia32_divsd_round_mask:
2416 case X86::BI__builtin_ia32_mulss_round_mask:
2417 case X86::BI__builtin_ia32_mulsd_round_mask:
2418 case X86::BI__builtin_ia32_subss_round_mask:
2419 case X86::BI__builtin_ia32_subsd_round_mask:
2420 case X86::BI__builtin_ia32_scalefpd512_mask:
2421 case X86::BI__builtin_ia32_scalefps512_mask:
2422 case X86::BI__builtin_ia32_scalefsd_round_mask:
2423 case X86::BI__builtin_ia32_scalefss_round_mask:
2424 case X86::BI__builtin_ia32_getmantpd512_mask:
2425 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002426 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2427 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2428 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002429 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2430 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2431 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2432 case X86::BI__builtin_ia32_vfmaddss3_mask:
2433 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2434 case X86::BI__builtin_ia32_vfmaddss3_mask3:
Craig Topperb92c77d2018-06-07 02:46:02 +00002435 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2436 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2437 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2438 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2439 case X86::BI__builtin_ia32_vfmaddps512_mask:
2440 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2441 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2442 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2443 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2444 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2445 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2446 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2447 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2448 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2449 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2450 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
Craig Topper7609f1c2016-10-01 21:03:50 +00002451 ArgNum = 4;
2452 HasRC = true;
2453 break;
2454 case X86::BI__builtin_ia32_getmantsd_round_mask:
2455 case X86::BI__builtin_ia32_getmantss_round_mask:
2456 ArgNum = 5;
2457 HasRC = true;
2458 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002459 }
2460
2461 llvm::APSInt Result;
2462
2463 // We can't check the value of a dependent argument.
2464 Expr *Arg = TheCall->getArg(ArgNum);
2465 if (Arg->isTypeDependent() || Arg->isValueDependent())
2466 return false;
2467
2468 // Check constant-ness first.
2469 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2470 return true;
2471
2472 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2473 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2474 // combined with ROUND_NO_EXC.
2475 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2476 Result == 8/*ROUND_NO_EXC*/ ||
2477 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2478 return false;
2479
2480 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2481 << Arg->getSourceRange();
2482}
2483
Craig Topperdf5beb22017-03-13 17:16:50 +00002484// Check if the gather/scatter scale is legal.
2485bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2486 CallExpr *TheCall) {
2487 unsigned ArgNum = 0;
2488 switch (BuiltinID) {
2489 default:
2490 return false;
2491 case X86::BI__builtin_ia32_gatherpfdpd:
2492 case X86::BI__builtin_ia32_gatherpfdps:
2493 case X86::BI__builtin_ia32_gatherpfqpd:
2494 case X86::BI__builtin_ia32_gatherpfqps:
2495 case X86::BI__builtin_ia32_scatterpfdpd:
2496 case X86::BI__builtin_ia32_scatterpfdps:
2497 case X86::BI__builtin_ia32_scatterpfqpd:
2498 case X86::BI__builtin_ia32_scatterpfqps:
2499 ArgNum = 3;
2500 break;
2501 case X86::BI__builtin_ia32_gatherd_pd:
2502 case X86::BI__builtin_ia32_gatherd_pd256:
2503 case X86::BI__builtin_ia32_gatherq_pd:
2504 case X86::BI__builtin_ia32_gatherq_pd256:
2505 case X86::BI__builtin_ia32_gatherd_ps:
2506 case X86::BI__builtin_ia32_gatherd_ps256:
2507 case X86::BI__builtin_ia32_gatherq_ps:
2508 case X86::BI__builtin_ia32_gatherq_ps256:
2509 case X86::BI__builtin_ia32_gatherd_q:
2510 case X86::BI__builtin_ia32_gatherd_q256:
2511 case X86::BI__builtin_ia32_gatherq_q:
2512 case X86::BI__builtin_ia32_gatherq_q256:
2513 case X86::BI__builtin_ia32_gatherd_d:
2514 case X86::BI__builtin_ia32_gatherd_d256:
2515 case X86::BI__builtin_ia32_gatherq_d:
2516 case X86::BI__builtin_ia32_gatherq_d256:
2517 case X86::BI__builtin_ia32_gather3div2df:
2518 case X86::BI__builtin_ia32_gather3div2di:
2519 case X86::BI__builtin_ia32_gather3div4df:
2520 case X86::BI__builtin_ia32_gather3div4di:
2521 case X86::BI__builtin_ia32_gather3div4sf:
2522 case X86::BI__builtin_ia32_gather3div4si:
2523 case X86::BI__builtin_ia32_gather3div8sf:
2524 case X86::BI__builtin_ia32_gather3div8si:
2525 case X86::BI__builtin_ia32_gather3siv2df:
2526 case X86::BI__builtin_ia32_gather3siv2di:
2527 case X86::BI__builtin_ia32_gather3siv4df:
2528 case X86::BI__builtin_ia32_gather3siv4di:
2529 case X86::BI__builtin_ia32_gather3siv4sf:
2530 case X86::BI__builtin_ia32_gather3siv4si:
2531 case X86::BI__builtin_ia32_gather3siv8sf:
2532 case X86::BI__builtin_ia32_gather3siv8si:
2533 case X86::BI__builtin_ia32_gathersiv8df:
2534 case X86::BI__builtin_ia32_gathersiv16sf:
2535 case X86::BI__builtin_ia32_gatherdiv8df:
2536 case X86::BI__builtin_ia32_gatherdiv16sf:
2537 case X86::BI__builtin_ia32_gathersiv8di:
2538 case X86::BI__builtin_ia32_gathersiv16si:
2539 case X86::BI__builtin_ia32_gatherdiv8di:
2540 case X86::BI__builtin_ia32_gatherdiv16si:
2541 case X86::BI__builtin_ia32_scatterdiv2df:
2542 case X86::BI__builtin_ia32_scatterdiv2di:
2543 case X86::BI__builtin_ia32_scatterdiv4df:
2544 case X86::BI__builtin_ia32_scatterdiv4di:
2545 case X86::BI__builtin_ia32_scatterdiv4sf:
2546 case X86::BI__builtin_ia32_scatterdiv4si:
2547 case X86::BI__builtin_ia32_scatterdiv8sf:
2548 case X86::BI__builtin_ia32_scatterdiv8si:
2549 case X86::BI__builtin_ia32_scattersiv2df:
2550 case X86::BI__builtin_ia32_scattersiv2di:
2551 case X86::BI__builtin_ia32_scattersiv4df:
2552 case X86::BI__builtin_ia32_scattersiv4di:
2553 case X86::BI__builtin_ia32_scattersiv4sf:
2554 case X86::BI__builtin_ia32_scattersiv4si:
2555 case X86::BI__builtin_ia32_scattersiv8sf:
2556 case X86::BI__builtin_ia32_scattersiv8si:
2557 case X86::BI__builtin_ia32_scattersiv8df:
2558 case X86::BI__builtin_ia32_scattersiv16sf:
2559 case X86::BI__builtin_ia32_scatterdiv8df:
2560 case X86::BI__builtin_ia32_scatterdiv16sf:
2561 case X86::BI__builtin_ia32_scattersiv8di:
2562 case X86::BI__builtin_ia32_scattersiv16si:
2563 case X86::BI__builtin_ia32_scatterdiv8di:
2564 case X86::BI__builtin_ia32_scatterdiv16si:
2565 ArgNum = 4;
2566 break;
2567 }
2568
2569 llvm::APSInt Result;
2570
2571 // We can't check the value of a dependent argument.
2572 Expr *Arg = TheCall->getArg(ArgNum);
2573 if (Arg->isTypeDependent() || Arg->isValueDependent())
2574 return false;
2575
2576 // Check constant-ness first.
2577 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2578 return true;
2579
2580 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2581 return false;
2582
2583 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2584 << Arg->getSourceRange();
2585}
2586
Craig Topper51738f82018-04-26 20:14:46 +00002587static bool isX86_32Builtin(unsigned BuiltinID) {
2588 // These builtins only work on x86-32 targets.
2589 switch (BuiltinID) {
2590 case X86::BI__builtin_ia32_readeflags_u32:
2591 case X86::BI__builtin_ia32_writeeflags_u32:
2592 return true;
2593 }
2594
2595 return false;
2596}
2597
Craig Topperf0ddc892016-09-23 04:48:27 +00002598bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2599 if (BuiltinID == X86::BI__builtin_cpu_supports)
2600 return SemaBuiltinCpuSupports(*this, TheCall);
2601
Craig Topper699ae0c2017-08-10 20:28:30 +00002602 if (BuiltinID == X86::BI__builtin_cpu_is)
2603 return SemaBuiltinCpuIs(*this, TheCall);
2604
Craig Topper51738f82018-04-26 20:14:46 +00002605 // Check for 32-bit only builtins on a 64-bit target.
2606 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2607 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2608 return Diag(TheCall->getCallee()->getLocStart(),
2609 diag::err_32_bit_builtin_64_bit_tgt);
2610
Craig Toppera7e253e2016-09-23 04:48:31 +00002611 // If the intrinsic has rounding or SAE make sure its valid.
2612 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2613 return true;
2614
Craig Topperdf5beb22017-03-13 17:16:50 +00002615 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2616 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2617 return true;
2618
Craig Topperf0ddc892016-09-23 04:48:27 +00002619 // For intrinsics which take an immediate value as part of the instruction,
2620 // range check them here.
2621 int i = 0, l = 0, u = 0;
2622 switch (BuiltinID) {
2623 default:
2624 return false;
Craig Topper11899b02018-06-05 21:54:35 +00002625 case X86::BI__builtin_ia32_vec_ext_v2si:
Craig Topperf3914b72018-06-06 00:24:55 +00002626 case X86::BI__builtin_ia32_vec_ext_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002627 case X86::BI__builtin_ia32_vextractf128_pd256:
2628 case X86::BI__builtin_ia32_vextractf128_ps256:
2629 case X86::BI__builtin_ia32_vextractf128_si256:
2630 case X86::BI__builtin_ia32_extract128i256:
Craig Topper5f50f3382018-06-08 21:50:07 +00002631 case X86::BI__builtin_ia32_extractf64x4_mask:
2632 case X86::BI__builtin_ia32_extracti64x4_mask:
2633 case X86::BI__builtin_ia32_extractf32x8_mask:
2634 case X86::BI__builtin_ia32_extracti32x8_mask:
2635 case X86::BI__builtin_ia32_extractf64x2_256_mask:
2636 case X86::BI__builtin_ia32_extracti64x2_256_mask:
2637 case X86::BI__builtin_ia32_extractf32x4_256_mask:
2638 case X86::BI__builtin_ia32_extracti32x4_256_mask:
Craig Topper11899b02018-06-05 21:54:35 +00002639 i = 1; l = 0; u = 1;
2640 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002641 case X86::BI__builtin_ia32_vec_set_v2di:
Craig Topper3428bee2018-06-08 03:24:47 +00002642 case X86::BI__builtin_ia32_vinsertf128_pd256:
2643 case X86::BI__builtin_ia32_vinsertf128_ps256:
2644 case X86::BI__builtin_ia32_vinsertf128_si256:
2645 case X86::BI__builtin_ia32_insert128i256:
2646 case X86::BI__builtin_ia32_insertf32x8:
2647 case X86::BI__builtin_ia32_inserti32x8:
2648 case X86::BI__builtin_ia32_insertf64x4:
2649 case X86::BI__builtin_ia32_inserti64x4:
2650 case X86::BI__builtin_ia32_insertf64x2_256:
2651 case X86::BI__builtin_ia32_inserti64x2_256:
2652 case X86::BI__builtin_ia32_insertf32x4_256:
2653 case X86::BI__builtin_ia32_inserti32x4_256:
Craig Topperf3914b72018-06-06 00:24:55 +00002654 i = 2; l = 0; u = 1;
2655 break;
Craig Topperacf56012018-06-08 00:59:27 +00002656 case X86::BI__builtin_ia32_vpermilpd:
Craig Topper11899b02018-06-05 21:54:35 +00002657 case X86::BI__builtin_ia32_vec_ext_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002658 case X86::BI__builtin_ia32_vec_ext_v4si:
2659 case X86::BI__builtin_ia32_vec_ext_v4sf:
2660 case X86::BI__builtin_ia32_vec_ext_v4di:
Craig Topper5f50f3382018-06-08 21:50:07 +00002661 case X86::BI__builtin_ia32_extractf32x4_mask:
2662 case X86::BI__builtin_ia32_extracti32x4_mask:
2663 case X86::BI__builtin_ia32_extractf64x2_512_mask:
2664 case X86::BI__builtin_ia32_extracti64x2_512_mask:
Craig Topper11899b02018-06-05 21:54:35 +00002665 i = 1; l = 0; u = 3;
2666 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002667 case X86::BI_mm_prefetch:
2668 case X86::BI__builtin_ia32_vec_ext_v8hi:
2669 case X86::BI__builtin_ia32_vec_ext_v8si:
2670 i = 1; l = 0; u = 7;
2671 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002672 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper7d17d722018-06-08 00:00:21 +00002673 case X86::BI__builtin_ia32_blendpd:
Craig Topper422a1bb2018-06-08 07:18:33 +00002674 case X86::BI__builtin_ia32_shufpd:
Craig Topper11899b02018-06-05 21:54:35 +00002675 case X86::BI__builtin_ia32_vec_set_v4hi:
Craig Topperf3914b72018-06-06 00:24:55 +00002676 case X86::BI__builtin_ia32_vec_set_v4si:
2677 case X86::BI__builtin_ia32_vec_set_v4di:
Craig Topper93921362018-06-07 23:03:08 +00002678 case X86::BI__builtin_ia32_shuf_f32x4_256:
2679 case X86::BI__builtin_ia32_shuf_f64x2_256:
2680 case X86::BI__builtin_ia32_shuf_i32x4_256:
2681 case X86::BI__builtin_ia32_shuf_i64x2_256:
Craig Topper3428bee2018-06-08 03:24:47 +00002682 case X86::BI__builtin_ia32_insertf64x2_512:
2683 case X86::BI__builtin_ia32_inserti64x2_512:
2684 case X86::BI__builtin_ia32_insertf32x4:
2685 case X86::BI__builtin_ia32_inserti32x4:
Craig Topper39c87102016-05-18 03:18:12 +00002686 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002687 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002688 case X86::BI__builtin_ia32_vpermil2pd:
2689 case X86::BI__builtin_ia32_vpermil2pd256:
2690 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002691 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002692 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002693 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002694 case X86::BI__builtin_ia32_cmpb128_mask:
2695 case X86::BI__builtin_ia32_cmpw128_mask:
2696 case X86::BI__builtin_ia32_cmpd128_mask:
2697 case X86::BI__builtin_ia32_cmpq128_mask:
2698 case X86::BI__builtin_ia32_cmpb256_mask:
2699 case X86::BI__builtin_ia32_cmpw256_mask:
2700 case X86::BI__builtin_ia32_cmpd256_mask:
2701 case X86::BI__builtin_ia32_cmpq256_mask:
2702 case X86::BI__builtin_ia32_cmpb512_mask:
2703 case X86::BI__builtin_ia32_cmpw512_mask:
2704 case X86::BI__builtin_ia32_cmpd512_mask:
2705 case X86::BI__builtin_ia32_cmpq512_mask:
2706 case X86::BI__builtin_ia32_ucmpb128_mask:
2707 case X86::BI__builtin_ia32_ucmpw128_mask:
2708 case X86::BI__builtin_ia32_ucmpd128_mask:
2709 case X86::BI__builtin_ia32_ucmpq128_mask:
2710 case X86::BI__builtin_ia32_ucmpb256_mask:
2711 case X86::BI__builtin_ia32_ucmpw256_mask:
2712 case X86::BI__builtin_ia32_ucmpd256_mask:
2713 case X86::BI__builtin_ia32_ucmpq256_mask:
2714 case X86::BI__builtin_ia32_ucmpb512_mask:
2715 case X86::BI__builtin_ia32_ucmpw512_mask:
2716 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002717 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002718 case X86::BI__builtin_ia32_vpcomub:
2719 case X86::BI__builtin_ia32_vpcomuw:
2720 case X86::BI__builtin_ia32_vpcomud:
2721 case X86::BI__builtin_ia32_vpcomuq:
2722 case X86::BI__builtin_ia32_vpcomb:
2723 case X86::BI__builtin_ia32_vpcomw:
2724 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002725 case X86::BI__builtin_ia32_vpcomq:
Craig Topperf3914b72018-06-06 00:24:55 +00002726 case X86::BI__builtin_ia32_vec_set_v8hi:
2727 case X86::BI__builtin_ia32_vec_set_v8si:
Craig Topper39c87102016-05-18 03:18:12 +00002728 i = 2; l = 0; u = 7;
2729 break;
Craig Topperacf56012018-06-08 00:59:27 +00002730 case X86::BI__builtin_ia32_vpermilpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002731 case X86::BI__builtin_ia32_roundps:
2732 case X86::BI__builtin_ia32_roundpd:
2733 case X86::BI__builtin_ia32_roundps256:
2734 case X86::BI__builtin_ia32_roundpd256:
Craig Topper03a1d482018-06-15 17:03:32 +00002735 case X86::BI__builtin_ia32_getmantpd128_mask:
2736 case X86::BI__builtin_ia32_getmantpd256_mask:
2737 case X86::BI__builtin_ia32_getmantps128_mask:
2738 case X86::BI__builtin_ia32_getmantps256_mask:
2739 case X86::BI__builtin_ia32_getmantpd512_mask:
2740 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002741 case X86::BI__builtin_ia32_vec_ext_v16qi:
2742 case X86::BI__builtin_ia32_vec_ext_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002743 i = 1; l = 0; u = 15;
2744 break;
Craig Topper7d17d722018-06-08 00:00:21 +00002745 case X86::BI__builtin_ia32_pblendd128:
2746 case X86::BI__builtin_ia32_blendps:
2747 case X86::BI__builtin_ia32_blendpd256:
Craig Topper422a1bb2018-06-08 07:18:33 +00002748 case X86::BI__builtin_ia32_shufpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002749 case X86::BI__builtin_ia32_roundss:
2750 case X86::BI__builtin_ia32_roundsd:
2751 case X86::BI__builtin_ia32_rangepd128_mask:
2752 case X86::BI__builtin_ia32_rangepd256_mask:
2753 case X86::BI__builtin_ia32_rangepd512_mask:
2754 case X86::BI__builtin_ia32_rangeps128_mask:
2755 case X86::BI__builtin_ia32_rangeps256_mask:
2756 case X86::BI__builtin_ia32_rangeps512_mask:
2757 case X86::BI__builtin_ia32_getmantsd_round_mask:
2758 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002759 case X86::BI__builtin_ia32_vec_set_v16qi:
2760 case X86::BI__builtin_ia32_vec_set_v16hi:
Craig Topper39c87102016-05-18 03:18:12 +00002761 i = 2; l = 0; u = 15;
2762 break;
Craig Topperf3914b72018-06-06 00:24:55 +00002763 case X86::BI__builtin_ia32_vec_ext_v32qi:
2764 i = 1; l = 0; u = 31;
2765 break;
Craig Topper39c87102016-05-18 03:18:12 +00002766 case X86::BI__builtin_ia32_cmpps:
2767 case X86::BI__builtin_ia32_cmpss:
2768 case X86::BI__builtin_ia32_cmppd:
2769 case X86::BI__builtin_ia32_cmpsd:
2770 case X86::BI__builtin_ia32_cmpps256:
2771 case X86::BI__builtin_ia32_cmppd256:
2772 case X86::BI__builtin_ia32_cmpps128_mask:
2773 case X86::BI__builtin_ia32_cmppd128_mask:
2774 case X86::BI__builtin_ia32_cmpps256_mask:
2775 case X86::BI__builtin_ia32_cmppd256_mask:
2776 case X86::BI__builtin_ia32_cmpps512_mask:
2777 case X86::BI__builtin_ia32_cmppd512_mask:
2778 case X86::BI__builtin_ia32_cmpsd_mask:
2779 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topperf3914b72018-06-06 00:24:55 +00002780 case X86::BI__builtin_ia32_vec_set_v32qi:
Craig Topper39c87102016-05-18 03:18:12 +00002781 i = 2; l = 0; u = 31;
2782 break;
Craig Topper03f4f042018-06-08 18:00:25 +00002783 case X86::BI__builtin_ia32_permdf256:
2784 case X86::BI__builtin_ia32_permdi256:
2785 case X86::BI__builtin_ia32_permdf512:
2786 case X86::BI__builtin_ia32_permdi512:
Craig Topperacf56012018-06-08 00:59:27 +00002787 case X86::BI__builtin_ia32_vpermilps:
2788 case X86::BI__builtin_ia32_vpermilps256:
2789 case X86::BI__builtin_ia32_vpermilpd512:
2790 case X86::BI__builtin_ia32_vpermilps512:
Craig Topper03de1662018-06-08 06:13:16 +00002791 case X86::BI__builtin_ia32_pshufd:
2792 case X86::BI__builtin_ia32_pshufd256:
2793 case X86::BI__builtin_ia32_pshufd512:
2794 case X86::BI__builtin_ia32_pshufhw:
2795 case X86::BI__builtin_ia32_pshufhw256:
2796 case X86::BI__builtin_ia32_pshufhw512:
2797 case X86::BI__builtin_ia32_pshuflw:
2798 case X86::BI__builtin_ia32_pshuflw256:
2799 case X86::BI__builtin_ia32_pshuflw512:
Craig Topper39c87102016-05-18 03:18:12 +00002800 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002801 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002802 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002803 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2804 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002805 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2806 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2807 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2808 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2809 case X86::BI__builtin_ia32_rndscaleps_mask:
2810 case X86::BI__builtin_ia32_rndscalepd_mask:
2811 case X86::BI__builtin_ia32_reducepd128_mask:
2812 case X86::BI__builtin_ia32_reducepd256_mask:
2813 case X86::BI__builtin_ia32_reducepd512_mask:
2814 case X86::BI__builtin_ia32_reduceps128_mask:
2815 case X86::BI__builtin_ia32_reduceps256_mask:
2816 case X86::BI__builtin_ia32_reduceps512_mask:
2817 case X86::BI__builtin_ia32_prold512_mask:
2818 case X86::BI__builtin_ia32_prolq512_mask:
2819 case X86::BI__builtin_ia32_prold128_mask:
2820 case X86::BI__builtin_ia32_prold256_mask:
2821 case X86::BI__builtin_ia32_prolq128_mask:
2822 case X86::BI__builtin_ia32_prolq256_mask:
Craig Topper4217d172018-06-15 17:40:37 +00002823 case X86::BI__builtin_ia32_prord512_mask:
2824 case X86::BI__builtin_ia32_prorq512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002825 case X86::BI__builtin_ia32_prord128_mask:
2826 case X86::BI__builtin_ia32_prord256_mask:
2827 case X86::BI__builtin_ia32_prorq128_mask:
2828 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002829 case X86::BI__builtin_ia32_fpclasspd128_mask:
2830 case X86::BI__builtin_ia32_fpclasspd256_mask:
2831 case X86::BI__builtin_ia32_fpclassps128_mask:
2832 case X86::BI__builtin_ia32_fpclassps256_mask:
2833 case X86::BI__builtin_ia32_fpclassps512_mask:
2834 case X86::BI__builtin_ia32_fpclasspd512_mask:
2835 case X86::BI__builtin_ia32_fpclasssd_mask:
2836 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper31730ae2018-06-14 22:02:35 +00002837 case X86::BI__builtin_ia32_pslldqi128_byteshift:
2838 case X86::BI__builtin_ia32_pslldqi256_byteshift:
2839 case X86::BI__builtin_ia32_pslldqi512_byteshift:
2840 case X86::BI__builtin_ia32_psrldqi128_byteshift:
2841 case X86::BI__builtin_ia32_psrldqi256_byteshift:
2842 case X86::BI__builtin_ia32_psrldqi512_byteshift:
Craig Topper39c87102016-05-18 03:18:12 +00002843 i = 1; l = 0; u = 255;
2844 break;
Craig Topper9d3962f2018-06-08 18:00:22 +00002845 case X86::BI__builtin_ia32_vperm2f128_pd256:
2846 case X86::BI__builtin_ia32_vperm2f128_ps256:
2847 case X86::BI__builtin_ia32_vperm2f128_si256:
2848 case X86::BI__builtin_ia32_permti256:
Craig Topper7d17d722018-06-08 00:00:21 +00002849 case X86::BI__builtin_ia32_pblendw128:
2850 case X86::BI__builtin_ia32_pblendw256:
2851 case X86::BI__builtin_ia32_blendps256:
2852 case X86::BI__builtin_ia32_pblendd256:
Craig Topper39c87102016-05-18 03:18:12 +00002853 case X86::BI__builtin_ia32_palignr128:
2854 case X86::BI__builtin_ia32_palignr256:
Craig Topper8e3689c2018-05-22 20:48:24 +00002855 case X86::BI__builtin_ia32_palignr512:
Craig Toppere56819e2018-06-07 21:27:41 +00002856 case X86::BI__builtin_ia32_alignq512:
2857 case X86::BI__builtin_ia32_alignd512:
2858 case X86::BI__builtin_ia32_alignd128:
2859 case X86::BI__builtin_ia32_alignd256:
2860 case X86::BI__builtin_ia32_alignq128:
2861 case X86::BI__builtin_ia32_alignq256:
Craig Topper39c87102016-05-18 03:18:12 +00002862 case X86::BI__builtin_ia32_vcomisd:
2863 case X86::BI__builtin_ia32_vcomiss:
Craig Topper93921362018-06-07 23:03:08 +00002864 case X86::BI__builtin_ia32_shuf_f32x4:
2865 case X86::BI__builtin_ia32_shuf_f64x2:
2866 case X86::BI__builtin_ia32_shuf_i32x4:
2867 case X86::BI__builtin_ia32_shuf_i64x2:
Craig Topper422a1bb2018-06-08 07:18:33 +00002868 case X86::BI__builtin_ia32_shufpd512:
2869 case X86::BI__builtin_ia32_shufps:
2870 case X86::BI__builtin_ia32_shufps256:
2871 case X86::BI__builtin_ia32_shufps512:
Craig Topper91bbe982018-06-11 06:18:29 +00002872 case X86::BI__builtin_ia32_dbpsadbw128:
2873 case X86::BI__builtin_ia32_dbpsadbw256:
2874 case X86::BI__builtin_ia32_dbpsadbw512:
Craig Topper2527c372018-06-13 07:19:28 +00002875 case X86::BI__builtin_ia32_vpshldd128:
2876 case X86::BI__builtin_ia32_vpshldd256:
2877 case X86::BI__builtin_ia32_vpshldd512:
2878 case X86::BI__builtin_ia32_vpshldq128:
2879 case X86::BI__builtin_ia32_vpshldq256:
2880 case X86::BI__builtin_ia32_vpshldq512:
2881 case X86::BI__builtin_ia32_vpshldw128:
2882 case X86::BI__builtin_ia32_vpshldw256:
2883 case X86::BI__builtin_ia32_vpshldw512:
2884 case X86::BI__builtin_ia32_vpshrdd128:
2885 case X86::BI__builtin_ia32_vpshrdd256:
2886 case X86::BI__builtin_ia32_vpshrdd512:
2887 case X86::BI__builtin_ia32_vpshrdq128:
2888 case X86::BI__builtin_ia32_vpshrdq256:
2889 case X86::BI__builtin_ia32_vpshrdq512:
2890 case X86::BI__builtin_ia32_vpshrdw128:
2891 case X86::BI__builtin_ia32_vpshrdw256:
2892 case X86::BI__builtin_ia32_vpshrdw512:
Craig Topper39c87102016-05-18 03:18:12 +00002893 i = 2; l = 0; u = 255;
2894 break;
2895 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2896 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2897 case X86::BI__builtin_ia32_fixupimmps512_mask:
2898 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2899 case X86::BI__builtin_ia32_fixupimmsd_mask:
2900 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2901 case X86::BI__builtin_ia32_fixupimmss_mask:
2902 case X86::BI__builtin_ia32_fixupimmss_maskz:
2903 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2904 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2905 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2906 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2907 case X86::BI__builtin_ia32_fixupimmps128_mask:
2908 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2909 case X86::BI__builtin_ia32_fixupimmps256_mask:
2910 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2911 case X86::BI__builtin_ia32_pternlogd512_mask:
2912 case X86::BI__builtin_ia32_pternlogd512_maskz:
2913 case X86::BI__builtin_ia32_pternlogq512_mask:
2914 case X86::BI__builtin_ia32_pternlogq512_maskz:
2915 case X86::BI__builtin_ia32_pternlogd128_mask:
2916 case X86::BI__builtin_ia32_pternlogd128_maskz:
2917 case X86::BI__builtin_ia32_pternlogd256_mask:
2918 case X86::BI__builtin_ia32_pternlogd256_maskz:
2919 case X86::BI__builtin_ia32_pternlogq128_mask:
2920 case X86::BI__builtin_ia32_pternlogq128_maskz:
2921 case X86::BI__builtin_ia32_pternlogq256_mask:
2922 case X86::BI__builtin_ia32_pternlogq256_maskz:
2923 i = 3; l = 0; u = 255;
2924 break;
Craig Topper9625db02017-03-12 22:19:10 +00002925 case X86::BI__builtin_ia32_gatherpfdpd:
2926 case X86::BI__builtin_ia32_gatherpfdps:
2927 case X86::BI__builtin_ia32_gatherpfqpd:
2928 case X86::BI__builtin_ia32_gatherpfqps:
2929 case X86::BI__builtin_ia32_scatterpfdpd:
2930 case X86::BI__builtin_ia32_scatterpfdps:
2931 case X86::BI__builtin_ia32_scatterpfqpd:
2932 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002933 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002934 break;
Craig Topper39c87102016-05-18 03:18:12 +00002935 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2936 case X86::BI__builtin_ia32_rndscaless_round_mask:
2937 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002938 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002939 }
Chandler Carruth16e6bc22018-06-21 23:46:09 +00002940
2941 // Note that we don't force a hard error on the range check here, allowing
2942 // template-generated or macro-generated dead code to potentially have out-of-
2943 // range values. These need to code generate, but don't need to necessarily
2944 // make any sense. We use a warning that defaults to an error.
2945 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002946}
2947
Richard Smith55ce3522012-06-25 20:30:08 +00002948/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2949/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2950/// Returns true when the format fits the function and the FormatStringInfo has
2951/// been populated.
2952bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2953 FormatStringInfo *FSI) {
2954 FSI->HasVAListArg = Format->getFirstArg() == 0;
2955 FSI->FormatIdx = Format->getFormatIdx() - 1;
2956 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002957
Richard Smith55ce3522012-06-25 20:30:08 +00002958 // The way the format attribute works in GCC, the implicit this argument
2959 // of member functions is counted. However, it doesn't appear in our own
2960 // lists, so decrement format_idx in that case.
2961 if (IsCXXMember) {
2962 if(FSI->FormatIdx == 0)
2963 return false;
2964 --FSI->FormatIdx;
2965 if (FSI->FirstDataArg != 0)
2966 --FSI->FirstDataArg;
2967 }
2968 return true;
2969}
Mike Stump11289f42009-09-09 15:08:12 +00002970
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002971/// Checks if a the given expression evaluates to null.
2972///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002973/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002974static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002975 // If the expression has non-null type, it doesn't evaluate to null.
2976 if (auto nullability
2977 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2978 if (*nullability == NullabilityKind::NonNull)
2979 return false;
2980 }
2981
Ted Kremeneka146db32014-01-17 06:24:47 +00002982 // As a special case, transparent unions initialized with zero are
2983 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002984 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002985 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2986 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002987 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002988 if (const InitListExpr *ILE =
2989 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002990 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002991 }
2992
2993 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002994 return (!Expr->isValueDependent() &&
2995 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2996 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002997}
2998
2999static void CheckNonNullArgument(Sema &S,
3000 const Expr *ArgExpr,
3001 SourceLocation CallSiteLoc) {
3002 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00003003 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3004 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00003005}
3006
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003007bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3008 FormatStringInfo FSI;
3009 if ((GetFormatStringType(Format) == FST_NSString) &&
3010 getFormatStringInfo(Format, false, &FSI)) {
3011 Idx = FSI.FormatIdx;
3012 return true;
3013 }
3014 return false;
3015}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003016
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003017/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003018/// as formatting string to formatting method.
3019static void
3020DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3021 const NamedDecl *FDecl,
3022 Expr **Args,
3023 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003024 unsigned Idx = 0;
3025 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003026 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3027 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003028 Idx = 2;
3029 Format = true;
3030 }
3031 else
3032 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3033 if (S.GetFormatNSStringIdx(I, Idx)) {
3034 Format = true;
3035 break;
3036 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003037 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003038 if (!Format || NumArgs <= Idx)
3039 return;
3040 const Expr *FormatExpr = Args[Idx];
3041 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3042 FormatExpr = CSCE->getSubExpr();
3043 const StringLiteral *FormatString;
3044 if (const ObjCStringLiteral *OSL =
3045 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3046 FormatString = OSL->getString();
3047 else
3048 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3049 if (!FormatString)
3050 return;
3051 if (S.FormatStringHasSArg(FormatString)) {
3052 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3053 << "%s" << 1 << 1;
3054 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3055 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003056 }
3057}
3058
Douglas Gregorb4866e82015-06-19 18:13:19 +00003059/// Determine whether the given type has a non-null nullability annotation.
3060static bool isNonNullType(ASTContext &ctx, QualType type) {
3061 if (auto nullability = type->getNullability(ctx))
3062 return *nullability == NullabilityKind::NonNull;
3063
3064 return false;
3065}
3066
Ted Kremenek2bc73332014-01-17 06:24:43 +00003067static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00003068 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003069 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00003070 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00003071 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003072 assert((FDecl || Proto) && "Need a function declaration or prototype");
3073
Ted Kremenek9aedc152014-01-17 06:24:56 +00003074 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00003075 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00003076 if (FDecl) {
3077 // Handle the nonnull attribute on the function/method declaration itself.
3078 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3079 if (!NonNull->args_size()) {
3080 // Easy case: all pointer arguments are nonnull.
3081 for (const auto *Arg : Args)
3082 if (S.isValidPointerAttrType(Arg->getType()))
3083 CheckNonNullArgument(S, Arg, CallSiteLoc);
3084 return;
3085 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003086
Joel E. Denny81508102018-03-13 14:51:22 +00003087 for (const ParamIdx &Idx : NonNull->args()) {
3088 unsigned IdxAST = Idx.getASTIndex();
3089 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00003090 continue;
3091 if (NonNullArgs.empty())
3092 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00003093 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003094 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003095 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003096 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003097
Douglas Gregorb4866e82015-06-19 18:13:19 +00003098 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3099 // Handle the nonnull attribute on the parameters of the
3100 // function/method.
3101 ArrayRef<ParmVarDecl*> parms;
3102 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3103 parms = FD->parameters();
3104 else
3105 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3106
3107 unsigned ParamIndex = 0;
3108 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3109 I != E; ++I, ++ParamIndex) {
3110 const ParmVarDecl *PVD = *I;
3111 if (PVD->hasAttr<NonNullAttr>() ||
3112 isNonNullType(S.Context, PVD->getType())) {
3113 if (NonNullArgs.empty())
3114 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00003115
Douglas Gregorb4866e82015-06-19 18:13:19 +00003116 NonNullArgs.set(ParamIndex);
3117 }
3118 }
3119 } else {
3120 // If we have a non-function, non-method declaration but no
3121 // function prototype, try to dig out the function prototype.
3122 if (!Proto) {
3123 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3124 QualType type = VD->getType().getNonReferenceType();
3125 if (auto pointerType = type->getAs<PointerType>())
3126 type = pointerType->getPointeeType();
3127 else if (auto blockType = type->getAs<BlockPointerType>())
3128 type = blockType->getPointeeType();
3129 // FIXME: data member pointers?
3130
3131 // Dig out the function prototype, if there is one.
3132 Proto = type->getAs<FunctionProtoType>();
3133 }
3134 }
3135
3136 // Fill in non-null argument information from the nullability
3137 // information on the parameter types (if we have them).
3138 if (Proto) {
3139 unsigned Index = 0;
3140 for (auto paramType : Proto->getParamTypes()) {
3141 if (isNonNullType(S.Context, paramType)) {
3142 if (NonNullArgs.empty())
3143 NonNullArgs.resize(Args.size());
3144
3145 NonNullArgs.set(Index);
3146 }
3147
3148 ++Index;
3149 }
3150 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00003151 }
Richard Smith588bd9b2014-08-27 04:59:42 +00003152
Douglas Gregorb4866e82015-06-19 18:13:19 +00003153 // Check for non-null arguments.
3154 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3155 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00003156 if (NonNullArgs[ArgIndex])
3157 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003158 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00003159}
3160
Richard Smith55ce3522012-06-25 20:30:08 +00003161/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00003162/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
3163/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003164void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00003165 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3166 bool IsMemberFunction, SourceLocation Loc,
3167 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00003168 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00003169 if (CurContext->isDependentContext())
3170 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00003171
Ted Kremenekb8176da2010-09-09 04:33:05 +00003172 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00003173 llvm::SmallBitVector CheckedVarArgs;
3174 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003175 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003176 // Only create vector if there are format attributes.
3177 CheckedVarArgs.resize(Args.size());
3178
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003179 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003180 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003181 }
Richard Smithd7293d72013-08-05 18:49:43 +00003182 }
Richard Smith55ce3522012-06-25 20:30:08 +00003183
3184 // Refuse POD arguments that weren't caught by the format string
3185 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003186 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3187 if (CallType != VariadicDoesNotApply &&
3188 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003189 unsigned NumParams = Proto ? Proto->getNumParams()
3190 : FDecl && isa<FunctionDecl>(FDecl)
3191 ? cast<FunctionDecl>(FDecl)->getNumParams()
3192 : FDecl && isa<ObjCMethodDecl>(FDecl)
3193 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3194 : 0;
3195
Alp Toker9cacbab2014-01-20 20:26:09 +00003196 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003197 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003198 if (const Expr *Arg = Args[ArgIdx]) {
3199 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3200 checkVariadicArgument(Arg, CallType);
3201 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003202 }
Richard Smithd7293d72013-08-05 18:49:43 +00003203 }
Mike Stump11289f42009-09-09 15:08:12 +00003204
Douglas Gregorb4866e82015-06-19 18:13:19 +00003205 if (FDecl || Proto) {
3206 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003207
Richard Trieu41bc0992013-06-22 00:20:41 +00003208 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003209 if (FDecl) {
3210 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003211 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003212 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003213 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003214
3215 if (FD)
3216 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003217}
3218
3219/// CheckConstructorCall - Check a constructor call for correctness and safety
3220/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003221void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3222 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003223 const FunctionProtoType *Proto,
3224 SourceLocation Loc) {
3225 VariadicCallType CallType =
3226 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003227 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3228 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003229}
3230
3231/// CheckFunctionCall - Check a direct function call for various correctness
3232/// and safety properties not strictly enforced by the C type system.
3233bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3234 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003235 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3236 isa<CXXMethodDecl>(FDecl);
3237 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3238 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003239 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3240 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003241 Expr** Args = TheCall->getArgs();
3242 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003243
3244 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003245 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003246 // If this is a call to a member operator, hide the first argument
3247 // from checkCall.
3248 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003249 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003250 ++Args;
3251 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003252 } else if (IsMemberFunction)
3253 ImplicitThis =
3254 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3255
3256 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003257 IsMemberFunction, TheCall->getRParenLoc(),
3258 TheCall->getCallee()->getSourceRange(), CallType);
3259
3260 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3261 // None of the checks below are needed for functions that don't have
3262 // simple names (e.g., C++ conversion functions).
3263 if (!FnInfo)
3264 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003265
Richard Trieua7f30b12016-12-06 01:42:28 +00003266 CheckAbsoluteValueFunction(TheCall, FDecl);
3267 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003268
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003269 if (getLangOpts().ObjC1)
3270 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003271
Anna Zaks22122702012-01-17 00:37:07 +00003272 unsigned CMId = FDecl->getMemoryFunctionKind();
3273 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003274 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003275
Anna Zaks201d4892012-01-13 21:52:01 +00003276 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003277 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003278 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003279 else if (CMId == Builtin::BIstrncat)
3280 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003281 else
Anna Zaks22122702012-01-17 00:37:07 +00003282 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003283
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003284 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003285}
3286
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003287bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003288 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003289 VariadicCallType CallType =
3290 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003291
George Burgess IVce6284b2017-01-28 02:19:40 +00003292 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3293 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003294 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003295
3296 return false;
3297}
3298
Richard Trieu664c4c62013-06-20 21:03:13 +00003299bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3300 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003301 QualType Ty;
3302 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003303 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003304 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003305 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003306 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003307 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003308
Douglas Gregorb4866e82015-06-19 18:13:19 +00003309 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3310 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003311 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003312
Richard Trieu664c4c62013-06-20 21:03:13 +00003313 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003314 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003315 CallType = VariadicDoesNotApply;
3316 } else if (Ty->isBlockPointerType()) {
3317 CallType = VariadicBlock;
3318 } else { // Ty->isFunctionPointerType()
3319 CallType = VariadicFunction;
3320 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003321
George Burgess IVce6284b2017-01-28 02:19:40 +00003322 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003323 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3324 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003325 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003326
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003327 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003328}
3329
Richard Trieu41bc0992013-06-22 00:20:41 +00003330/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3331/// such as function pointers returned from functions.
3332bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003333 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003334 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003335 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003336 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003337 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003338 TheCall->getCallee()->getSourceRange(), CallType);
3339
3340 return false;
3341}
3342
Tim Northovere94a34c2014-03-11 10:49:14 +00003343static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003344 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003345 return false;
3346
JF Bastiendda2cb12016-04-18 18:01:49 +00003347 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003348 switch (Op) {
3349 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003350 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003351 llvm_unreachable("There is no ordering argument for an init");
3352
3353 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003354 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003355 case AtomicExpr::AO__atomic_load_n:
3356 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003357 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3358 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003359
3360 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003361 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003362 case AtomicExpr::AO__atomic_store:
3363 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003364 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3365 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3366 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003367
3368 default:
3369 return true;
3370 }
3371}
3372
Richard Smithfeea8832012-04-12 05:08:17 +00003373ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3374 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003375 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3376 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003377
Yaxun Liu39195062017-08-04 18:16:31 +00003378 // All the non-OpenCL operations take one of the following forms.
3379 // The OpenCL operations take the __c11 forms with one extra argument for
3380 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003381 enum {
3382 // C __c11_atomic_init(A *, C)
3383 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003384
Richard Smithfeea8832012-04-12 05:08:17 +00003385 // C __c11_atomic_load(A *, int)
3386 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003387
Richard Smithfeea8832012-04-12 05:08:17 +00003388 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003389 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003390
Eric Fiselier8d662442016-03-30 23:39:56 +00003391 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003392 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003393
Richard Smithfeea8832012-04-12 05:08:17 +00003394 // C __c11_atomic_add(A *, M, int)
3395 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003396
Richard Smithfeea8832012-04-12 05:08:17 +00003397 // C __atomic_exchange_n(A *, CP, int)
3398 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003399
Richard Smithfeea8832012-04-12 05:08:17 +00003400 // void __atomic_exchange(A *, C *, CP, int)
3401 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003402
Richard Smithfeea8832012-04-12 05:08:17 +00003403 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3404 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003405
Richard Smithfeea8832012-04-12 05:08:17 +00003406 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3407 GNUCmpXchg
3408 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003409
Yaxun Liu39195062017-08-04 18:16:31 +00003410 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003411 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3412 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003413 // where:
3414 // C is an appropriate type,
3415 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3416 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3417 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3418 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003419
Yaxun Liu39195062017-08-04 18:16:31 +00003420 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3421 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3422 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003423 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3424 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3425 AtomicExpr::AO__atomic_load,
3426 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003427 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3428 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3429 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3430 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3431 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003432 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3433 Op == AtomicExpr::AO__atomic_store_n ||
3434 Op == AtomicExpr::AO__atomic_exchange_n ||
3435 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3436 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003437 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003438
3439 switch (Op) {
3440 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003441 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003442 Form = Init;
3443 break;
3444
3445 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003446 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003447 case AtomicExpr::AO__atomic_load_n:
3448 Form = Load;
3449 break;
3450
Richard Smithfeea8832012-04-12 05:08:17 +00003451 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003452 Form = LoadCopy;
3453 break;
3454
3455 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003456 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003457 case AtomicExpr::AO__atomic_store:
3458 case AtomicExpr::AO__atomic_store_n:
3459 Form = Copy;
3460 break;
3461
3462 case AtomicExpr::AO__c11_atomic_fetch_add:
3463 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003464 case AtomicExpr::AO__opencl_atomic_fetch_add:
3465 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3466 case AtomicExpr::AO__opencl_atomic_fetch_min:
3467 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003468 case AtomicExpr::AO__atomic_fetch_add:
3469 case AtomicExpr::AO__atomic_fetch_sub:
3470 case AtomicExpr::AO__atomic_add_fetch:
3471 case AtomicExpr::AO__atomic_sub_fetch:
3472 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003473 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003474 case AtomicExpr::AO__c11_atomic_fetch_and:
3475 case AtomicExpr::AO__c11_atomic_fetch_or:
3476 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003477 case AtomicExpr::AO__opencl_atomic_fetch_and:
3478 case AtomicExpr::AO__opencl_atomic_fetch_or:
3479 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003480 case AtomicExpr::AO__atomic_fetch_and:
3481 case AtomicExpr::AO__atomic_fetch_or:
3482 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003483 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003484 case AtomicExpr::AO__atomic_and_fetch:
3485 case AtomicExpr::AO__atomic_or_fetch:
3486 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003487 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003488 Form = Arithmetic;
3489 break;
3490
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003491 case AtomicExpr::AO__atomic_fetch_min:
3492 case AtomicExpr::AO__atomic_fetch_max:
3493 IsMinMax = true;
3494 Form = Arithmetic;
3495 break;
3496
Richard Smithfeea8832012-04-12 05:08:17 +00003497 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003498 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003499 case AtomicExpr::AO__atomic_exchange_n:
3500 Form = Xchg;
3501 break;
3502
3503 case AtomicExpr::AO__atomic_exchange:
3504 Form = GNUXchg;
3505 break;
3506
3507 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3508 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003509 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3510 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003511 Form = C11CmpXchg;
3512 break;
3513
3514 case AtomicExpr::AO__atomic_compare_exchange:
3515 case AtomicExpr::AO__atomic_compare_exchange_n:
3516 Form = GNUCmpXchg;
3517 break;
3518 }
3519
Yaxun Liu39195062017-08-04 18:16:31 +00003520 unsigned AdjustedNumArgs = NumArgs[Form];
3521 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3522 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003523 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003524 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003525 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003526 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003527 << TheCall->getCallee()->getSourceRange();
3528 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003529 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3530 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003531 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003532 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003533 << TheCall->getCallee()->getSourceRange();
3534 return ExprError();
3535 }
3536
Richard Smithfeea8832012-04-12 05:08:17 +00003537 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003538 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003539 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3540 if (ConvertedPtr.isInvalid())
3541 return ExprError();
3542
3543 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003544 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3545 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003546 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003547 << Ptr->getType() << Ptr->getSourceRange();
3548 return ExprError();
3549 }
3550
Richard Smithfeea8832012-04-12 05:08:17 +00003551 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3552 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3553 QualType ValType = AtomTy; // 'C'
3554 if (IsC11) {
3555 if (!AtomTy->isAtomicType()) {
3556 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3557 << Ptr->getType() << Ptr->getSourceRange();
3558 return ExprError();
3559 }
Yaxun Liu39195062017-08-04 18:16:31 +00003560 if (AtomTy.isConstQualified() ||
3561 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003562 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003563 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3564 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003565 return ExprError();
3566 }
Richard Smithfeea8832012-04-12 05:08:17 +00003567 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003568 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003569 if (ValType.isConstQualified()) {
3570 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3571 << Ptr->getType() << Ptr->getSourceRange();
3572 return ExprError();
3573 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003574 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003575
Richard Smithfeea8832012-04-12 05:08:17 +00003576 // For an arithmetic operation, the implied arithmetic must be well-formed.
3577 if (Form == Arithmetic) {
3578 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003579 if (IsAddSub && !ValType->isIntegerType()
3580 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003581 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3582 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3583 return ExprError();
3584 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003585 if (IsMinMax) {
3586 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3587 if (!BT || (BT->getKind() != BuiltinType::Int &&
3588 BT->getKind() != BuiltinType::UInt)) {
3589 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3590 return ExprError();
3591 }
3592 }
3593 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003594 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3595 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3596 return ExprError();
3597 }
David Majnemere85cff82015-01-28 05:48:06 +00003598 if (IsC11 && ValType->isPointerType() &&
3599 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3600 diag::err_incomplete_type)) {
3601 return ExprError();
3602 }
Richard Smithfeea8832012-04-12 05:08:17 +00003603 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3604 // For __atomic_*_n operations, the value type must be a scalar integral or
3605 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003606 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003607 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3608 return ExprError();
3609 }
3610
Eli Friedmanaa769812013-09-11 03:49:34 +00003611 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3612 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003613 // For GNU atomics, require a trivially-copyable type. This is not part of
3614 // the GNU atomics specification, but we enforce it for sanity.
3615 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003616 << Ptr->getType() << Ptr->getSourceRange();
3617 return ExprError();
3618 }
3619
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003620 switch (ValType.getObjCLifetime()) {
3621 case Qualifiers::OCL_None:
3622 case Qualifiers::OCL_ExplicitNone:
3623 // okay
3624 break;
3625
3626 case Qualifiers::OCL_Weak:
3627 case Qualifiers::OCL_Strong:
3628 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003629 // FIXME: Can this happen? By this point, ValType should be known
3630 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003631 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3632 << ValType << Ptr->getSourceRange();
3633 return ExprError();
3634 }
3635
JF Bastien7f0a05a2018-05-25 00:07:09 +00003636 // All atomic operations have an overload which takes a pointer to a volatile
3637 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
3638 // into the result or the other operands. Similarly atomic_load takes a
3639 // pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003640 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003641 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003642 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003643 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3644 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003645 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003646 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003647 ResultType = Context.BoolTy;
3648
Richard Smithfeea8832012-04-12 05:08:17 +00003649 // The type of a parameter passed 'by value'. In the GNU atomics, such
3650 // arguments are actually passed as pointers.
3651 QualType ByValType = ValType; // 'CP'
JF Bastien7f0a05a2018-05-25 00:07:09 +00003652 bool IsPassedByAddress = false;
3653 if (!IsC11 && !IsN) {
Richard Smithfeea8832012-04-12 05:08:17 +00003654 ByValType = Ptr->getType();
JF Bastien7f0a05a2018-05-25 00:07:09 +00003655 IsPassedByAddress = true;
3656 }
Richard Smithfeea8832012-04-12 05:08:17 +00003657
JF Bastien7f0a05a2018-05-25 00:07:09 +00003658 // The first argument's non-CV pointer type is used to deduce the type of
3659 // subsequent arguments, except for:
3660 // - weak flag (always converted to bool)
3661 // - memory order (always converted to int)
3662 // - scope (always converted to int)
3663 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003664 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003665 if (i < NumVals[Form] + 1) {
3666 switch (i) {
JF Bastien7f0a05a2018-05-25 00:07:09 +00003667 case 0:
3668 // The first argument is always a pointer. It has a fixed type.
3669 // It is always dereferenced, a nullptr is undefined.
3670 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
3671 // Nothing else to do: we already know all we want about this pointer.
3672 continue;
Richard Smithfeea8832012-04-12 05:08:17 +00003673 case 1:
3674 // The second argument is the non-atomic operand. For arithmetic, this
3675 // is always passed by value, and for a compare_exchange it is always
3676 // passed by address. For the rest, GNU uses by-address and C11 uses
3677 // by-value.
3678 assert(Form != Load);
3679 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3680 Ty = ValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003681 else if (Form == Copy || Form == Xchg) {
3682 if (IsPassedByAddress)
3683 // The value pointer is always dereferenced, a nullptr is undefined.
3684 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003685 Ty = ByValType;
JF Bastien7f0a05a2018-05-25 00:07:09 +00003686 } else if (Form == Arithmetic)
Richard Smithfeea8832012-04-12 05:08:17 +00003687 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003688 else {
3689 Expr *ValArg = TheCall->getArg(i);
JF Bastien7f0a05a2018-05-25 00:07:09 +00003690 // The value pointer is always dereferenced, a nullptr is undefined.
Alex Lorenz67522152016-11-23 16:57:03 +00003691 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003692 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003693 // Keep address space of non-atomic pointer type.
3694 if (const PointerType *PtrTy =
3695 ValArg->getType()->getAs<PointerType>()) {
3696 AS = PtrTy->getPointeeType().getAddressSpace();
3697 }
3698 Ty = Context.getPointerType(
3699 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3700 }
Richard Smithfeea8832012-04-12 05:08:17 +00003701 break;
3702 case 2:
JF Bastien7f0a05a2018-05-25 00:07:09 +00003703 // The third argument to compare_exchange / GNU exchange is the desired
JF Bastien7853d5f2018-05-25 17:36:49 +00003704 // value, either by-value (for the C11 and *_n variant) or as a pointer.
3705 if (IsPassedByAddress)
JF Bastien7f0a05a2018-05-25 00:07:09 +00003706 CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getLocStart());
Richard Smithfeea8832012-04-12 05:08:17 +00003707 Ty = ByValType;
3708 break;
3709 case 3:
3710 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3711 Ty = Context.BoolTy;
3712 break;
3713 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003714 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003715 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003716 Ty = Context.IntTy;
3717 }
Richard Smithfeea8832012-04-12 05:08:17 +00003718
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003719 InitializedEntity Entity =
3720 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003721 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003722 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3723 if (Arg.isInvalid())
3724 return true;
3725 TheCall->setArg(i, Arg.get());
3726 }
3727
Richard Smithfeea8832012-04-12 05:08:17 +00003728 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003729 SmallVector<Expr*, 5> SubExprs;
3730 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003731 switch (Form) {
3732 case Init:
3733 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003734 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003735 break;
3736 case Load:
3737 SubExprs.push_back(TheCall->getArg(1)); // Order
3738 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003739 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003740 case Copy:
3741 case Arithmetic:
3742 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003743 SubExprs.push_back(TheCall->getArg(2)); // Order
3744 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003745 break;
3746 case GNUXchg:
3747 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3748 SubExprs.push_back(TheCall->getArg(3)); // Order
3749 SubExprs.push_back(TheCall->getArg(1)); // Val1
3750 SubExprs.push_back(TheCall->getArg(2)); // Val2
3751 break;
3752 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003753 SubExprs.push_back(TheCall->getArg(3)); // Order
3754 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003755 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003756 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003757 break;
3758 case GNUCmpXchg:
3759 SubExprs.push_back(TheCall->getArg(4)); // Order
3760 SubExprs.push_back(TheCall->getArg(1)); // Val1
3761 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3762 SubExprs.push_back(TheCall->getArg(2)); // Val2
3763 SubExprs.push_back(TheCall->getArg(3)); // Weak
3764 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003765 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003766
3767 if (SubExprs.size() >= 2 && Form != Init) {
3768 llvm::APSInt Result(32);
3769 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3770 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003771 Diag(SubExprs[1]->getLocStart(),
3772 diag::warn_atomic_op_has_invalid_memory_order)
3773 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003774 }
3775
Yaxun Liu30d652a2017-08-15 16:02:49 +00003776 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3777 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3778 llvm::APSInt Result(32);
3779 if (Scope->isIntegerConstantExpr(Result, Context) &&
3780 !ScopeModel->isValid(Result.getZExtValue())) {
3781 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3782 << Scope->getSourceRange();
3783 }
3784 SubExprs.push_back(Scope);
3785 }
3786
Fariborz Jahanian615de762013-05-28 17:37:39 +00003787 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3788 SubExprs, ResultType, Op,
3789 TheCall->getRParenLoc());
3790
3791 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003792 Op == AtomicExpr::AO__c11_atomic_store ||
3793 Op == AtomicExpr::AO__opencl_atomic_load ||
3794 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003795 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003796 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3797 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3798 Op == AtomicExpr::AO__opencl_atomic_load)
3799 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003800
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003801 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003802}
3803
John McCall29ad95b2011-08-27 01:09:30 +00003804/// checkBuiltinArgument - Given a call to a builtin function, perform
3805/// normal type-checking on the given argument, updating the call in
3806/// place. This is useful when a builtin function requires custom
3807/// type-checking for some of its arguments but not necessarily all of
3808/// them.
3809///
3810/// Returns true on error.
3811static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3812 FunctionDecl *Fn = E->getDirectCallee();
3813 assert(Fn && "builtin call without direct callee!");
3814
3815 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3816 InitializedEntity Entity =
3817 InitializedEntity::InitializeParameter(S.Context, Param);
3818
3819 ExprResult Arg = E->getArg(0);
3820 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3821 if (Arg.isInvalid())
3822 return true;
3823
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003824 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003825 return false;
3826}
3827
Chris Lattnerdc046542009-05-08 06:58:22 +00003828/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3829/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3830/// type of its first argument. The main ActOnCallExpr routines have already
3831/// promoted the types of arguments because all of these calls are prototyped as
3832/// void(...).
3833///
3834/// This function goes through and does final semantic checking for these
3835/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003836ExprResult
3837Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003838 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003839 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3840 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3841
3842 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003843 if (TheCall->getNumArgs() < 1) {
3844 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3845 << 0 << 1 << TheCall->getNumArgs()
3846 << TheCall->getCallee()->getSourceRange();
3847 return ExprError();
3848 }
Mike Stump11289f42009-09-09 15:08:12 +00003849
Chris Lattnerdc046542009-05-08 06:58:22 +00003850 // Inspect the first argument of the atomic builtin. This should always be
3851 // a pointer type, whose element is an integral scalar or pointer type.
3852 // Because it is a pointer type, we don't have to worry about any implicit
3853 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003854 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003855 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003856 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3857 if (FirstArgResult.isInvalid())
3858 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003859 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003860 TheCall->setArg(0, FirstArg);
3861
John McCall31168b02011-06-15 23:02:42 +00003862 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3863 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003864 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3865 << FirstArg->getType() << FirstArg->getSourceRange();
3866 return ExprError();
3867 }
Mike Stump11289f42009-09-09 15:08:12 +00003868
John McCall31168b02011-06-15 23:02:42 +00003869 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003870 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003871 !ValType->isBlockPointerType()) {
3872 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3873 << FirstArg->getType() << FirstArg->getSourceRange();
3874 return ExprError();
3875 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003876
Aaron Ballmana383c942018-05-05 17:38:42 +00003877 if (ValType.isConstQualified()) {
3878 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3879 << FirstArg->getType() << FirstArg->getSourceRange();
3880 return ExprError();
3881 }
3882
John McCall31168b02011-06-15 23:02:42 +00003883 switch (ValType.getObjCLifetime()) {
3884 case Qualifiers::OCL_None:
3885 case Qualifiers::OCL_ExplicitNone:
3886 // okay
3887 break;
3888
3889 case Qualifiers::OCL_Weak:
3890 case Qualifiers::OCL_Strong:
3891 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003892 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003893 << ValType << FirstArg->getSourceRange();
3894 return ExprError();
3895 }
3896
John McCallb50451a2011-10-05 07:41:44 +00003897 // Strip any qualifiers off ValType.
3898 ValType = ValType.getUnqualifiedType();
3899
Chandler Carruth3973af72010-07-18 20:54:12 +00003900 // The majority of builtins return a value, but a few have special return
3901 // types, so allow them to override appropriately below.
3902 QualType ResultType = ValType;
3903
Chris Lattnerdc046542009-05-08 06:58:22 +00003904 // We need to figure out which concrete builtin this maps onto. For example,
3905 // __sync_fetch_and_add with a 2 byte object turns into
3906 // __sync_fetch_and_add_2.
3907#define BUILTIN_ROW(x) \
3908 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3909 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003910
Chris Lattnerdc046542009-05-08 06:58:22 +00003911 static const unsigned BuiltinIndices[][5] = {
3912 BUILTIN_ROW(__sync_fetch_and_add),
3913 BUILTIN_ROW(__sync_fetch_and_sub),
3914 BUILTIN_ROW(__sync_fetch_and_or),
3915 BUILTIN_ROW(__sync_fetch_and_and),
3916 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003917 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003918
Chris Lattnerdc046542009-05-08 06:58:22 +00003919 BUILTIN_ROW(__sync_add_and_fetch),
3920 BUILTIN_ROW(__sync_sub_and_fetch),
3921 BUILTIN_ROW(__sync_and_and_fetch),
3922 BUILTIN_ROW(__sync_or_and_fetch),
3923 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003924 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003925
Chris Lattnerdc046542009-05-08 06:58:22 +00003926 BUILTIN_ROW(__sync_val_compare_and_swap),
3927 BUILTIN_ROW(__sync_bool_compare_and_swap),
3928 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003929 BUILTIN_ROW(__sync_lock_release),
3930 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003931 };
Mike Stump11289f42009-09-09 15:08:12 +00003932#undef BUILTIN_ROW
3933
Chris Lattnerdc046542009-05-08 06:58:22 +00003934 // Determine the index of the size.
3935 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003936 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003937 case 1: SizeIndex = 0; break;
3938 case 2: SizeIndex = 1; break;
3939 case 4: SizeIndex = 2; break;
3940 case 8: SizeIndex = 3; break;
3941 case 16: SizeIndex = 4; break;
3942 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003943 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3944 << FirstArg->getType() << FirstArg->getSourceRange();
3945 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003946 }
Mike Stump11289f42009-09-09 15:08:12 +00003947
Chris Lattnerdc046542009-05-08 06:58:22 +00003948 // Each of these builtins has one pointer argument, followed by some number of
3949 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3950 // that we ignore. Find out which row of BuiltinIndices to read from as well
3951 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003952 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003953 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003954 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003955 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003956 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003957 case Builtin::BI__sync_fetch_and_add:
3958 case Builtin::BI__sync_fetch_and_add_1:
3959 case Builtin::BI__sync_fetch_and_add_2:
3960 case Builtin::BI__sync_fetch_and_add_4:
3961 case Builtin::BI__sync_fetch_and_add_8:
3962 case Builtin::BI__sync_fetch_and_add_16:
3963 BuiltinIndex = 0;
3964 break;
3965
3966 case Builtin::BI__sync_fetch_and_sub:
3967 case Builtin::BI__sync_fetch_and_sub_1:
3968 case Builtin::BI__sync_fetch_and_sub_2:
3969 case Builtin::BI__sync_fetch_and_sub_4:
3970 case Builtin::BI__sync_fetch_and_sub_8:
3971 case Builtin::BI__sync_fetch_and_sub_16:
3972 BuiltinIndex = 1;
3973 break;
3974
3975 case Builtin::BI__sync_fetch_and_or:
3976 case Builtin::BI__sync_fetch_and_or_1:
3977 case Builtin::BI__sync_fetch_and_or_2:
3978 case Builtin::BI__sync_fetch_and_or_4:
3979 case Builtin::BI__sync_fetch_and_or_8:
3980 case Builtin::BI__sync_fetch_and_or_16:
3981 BuiltinIndex = 2;
3982 break;
3983
3984 case Builtin::BI__sync_fetch_and_and:
3985 case Builtin::BI__sync_fetch_and_and_1:
3986 case Builtin::BI__sync_fetch_and_and_2:
3987 case Builtin::BI__sync_fetch_and_and_4:
3988 case Builtin::BI__sync_fetch_and_and_8:
3989 case Builtin::BI__sync_fetch_and_and_16:
3990 BuiltinIndex = 3;
3991 break;
Mike Stump11289f42009-09-09 15:08:12 +00003992
Douglas Gregor73722482011-11-28 16:30:08 +00003993 case Builtin::BI__sync_fetch_and_xor:
3994 case Builtin::BI__sync_fetch_and_xor_1:
3995 case Builtin::BI__sync_fetch_and_xor_2:
3996 case Builtin::BI__sync_fetch_and_xor_4:
3997 case Builtin::BI__sync_fetch_and_xor_8:
3998 case Builtin::BI__sync_fetch_and_xor_16:
3999 BuiltinIndex = 4;
4000 break;
4001
Hal Finkeld2208b52014-10-02 20:53:50 +00004002 case Builtin::BI__sync_fetch_and_nand:
4003 case Builtin::BI__sync_fetch_and_nand_1:
4004 case Builtin::BI__sync_fetch_and_nand_2:
4005 case Builtin::BI__sync_fetch_and_nand_4:
4006 case Builtin::BI__sync_fetch_and_nand_8:
4007 case Builtin::BI__sync_fetch_and_nand_16:
4008 BuiltinIndex = 5;
4009 WarnAboutSemanticsChange = true;
4010 break;
4011
Douglas Gregor73722482011-11-28 16:30:08 +00004012 case Builtin::BI__sync_add_and_fetch:
4013 case Builtin::BI__sync_add_and_fetch_1:
4014 case Builtin::BI__sync_add_and_fetch_2:
4015 case Builtin::BI__sync_add_and_fetch_4:
4016 case Builtin::BI__sync_add_and_fetch_8:
4017 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004018 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00004019 break;
4020
4021 case Builtin::BI__sync_sub_and_fetch:
4022 case Builtin::BI__sync_sub_and_fetch_1:
4023 case Builtin::BI__sync_sub_and_fetch_2:
4024 case Builtin::BI__sync_sub_and_fetch_4:
4025 case Builtin::BI__sync_sub_and_fetch_8:
4026 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004027 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00004028 break;
4029
4030 case Builtin::BI__sync_and_and_fetch:
4031 case Builtin::BI__sync_and_and_fetch_1:
4032 case Builtin::BI__sync_and_and_fetch_2:
4033 case Builtin::BI__sync_and_and_fetch_4:
4034 case Builtin::BI__sync_and_and_fetch_8:
4035 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004036 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00004037 break;
4038
4039 case Builtin::BI__sync_or_and_fetch:
4040 case Builtin::BI__sync_or_and_fetch_1:
4041 case Builtin::BI__sync_or_and_fetch_2:
4042 case Builtin::BI__sync_or_and_fetch_4:
4043 case Builtin::BI__sync_or_and_fetch_8:
4044 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004045 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00004046 break;
4047
4048 case Builtin::BI__sync_xor_and_fetch:
4049 case Builtin::BI__sync_xor_and_fetch_1:
4050 case Builtin::BI__sync_xor_and_fetch_2:
4051 case Builtin::BI__sync_xor_and_fetch_4:
4052 case Builtin::BI__sync_xor_and_fetch_8:
4053 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004054 BuiltinIndex = 10;
4055 break;
4056
4057 case Builtin::BI__sync_nand_and_fetch:
4058 case Builtin::BI__sync_nand_and_fetch_1:
4059 case Builtin::BI__sync_nand_and_fetch_2:
4060 case Builtin::BI__sync_nand_and_fetch_4:
4061 case Builtin::BI__sync_nand_and_fetch_8:
4062 case Builtin::BI__sync_nand_and_fetch_16:
4063 BuiltinIndex = 11;
4064 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00004065 break;
Mike Stump11289f42009-09-09 15:08:12 +00004066
Chris Lattnerdc046542009-05-08 06:58:22 +00004067 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004068 case Builtin::BI__sync_val_compare_and_swap_1:
4069 case Builtin::BI__sync_val_compare_and_swap_2:
4070 case Builtin::BI__sync_val_compare_and_swap_4:
4071 case Builtin::BI__sync_val_compare_and_swap_8:
4072 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004073 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00004074 NumFixed = 2;
4075 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004076
Chris Lattnerdc046542009-05-08 06:58:22 +00004077 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00004078 case Builtin::BI__sync_bool_compare_and_swap_1:
4079 case Builtin::BI__sync_bool_compare_and_swap_2:
4080 case Builtin::BI__sync_bool_compare_and_swap_4:
4081 case Builtin::BI__sync_bool_compare_and_swap_8:
4082 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004083 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00004084 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00004085 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004086 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004087
JF Bastien7f0a05a2018-05-25 00:07:09 +00004088 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00004089 case Builtin::BI__sync_lock_test_and_set_1:
4090 case Builtin::BI__sync_lock_test_and_set_2:
4091 case Builtin::BI__sync_lock_test_and_set_4:
4092 case Builtin::BI__sync_lock_test_and_set_8:
4093 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004094 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00004095 break;
4096
Chris Lattnerdc046542009-05-08 06:58:22 +00004097 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00004098 case Builtin::BI__sync_lock_release_1:
4099 case Builtin::BI__sync_lock_release_2:
4100 case Builtin::BI__sync_lock_release_4:
4101 case Builtin::BI__sync_lock_release_8:
4102 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004103 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00004104 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00004105 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00004106 break;
Douglas Gregor73722482011-11-28 16:30:08 +00004107
4108 case Builtin::BI__sync_swap:
4109 case Builtin::BI__sync_swap_1:
4110 case Builtin::BI__sync_swap_2:
4111 case Builtin::BI__sync_swap_4:
4112 case Builtin::BI__sync_swap_8:
4113 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00004114 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00004115 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00004116 }
Mike Stump11289f42009-09-09 15:08:12 +00004117
Chris Lattnerdc046542009-05-08 06:58:22 +00004118 // Now that we know how many fixed arguments we expect, first check that we
4119 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004120 if (TheCall->getNumArgs() < 1+NumFixed) {
4121 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
4122 << 0 << 1+NumFixed << TheCall->getNumArgs()
4123 << TheCall->getCallee()->getSourceRange();
4124 return ExprError();
4125 }
Mike Stump11289f42009-09-09 15:08:12 +00004126
Hal Finkeld2208b52014-10-02 20:53:50 +00004127 if (WarnAboutSemanticsChange) {
4128 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
4129 << TheCall->getCallee()->getSourceRange();
4130 }
4131
Chris Lattner5b9241b2009-05-08 15:36:58 +00004132 // Get the decl for the concrete builtin from this, we can tell what the
4133 // concrete integer type we should convert to is.
4134 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00004135 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004136 FunctionDecl *NewBuiltinDecl;
4137 if (NewBuiltinID == BuiltinID)
4138 NewBuiltinDecl = FDecl;
4139 else {
4140 // Perform builtin lookup to avoid redeclaring it.
4141 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4142 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
4143 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4144 assert(Res.getFoundDecl());
4145 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004146 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00004147 return ExprError();
4148 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004149
John McCallcf142162010-08-07 06:22:56 +00004150 // The first argument --- the pointer --- has a fixed type; we
4151 // deduce the types of the rest of the arguments accordingly. Walk
4152 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00004153 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00004154 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00004155
Chris Lattnerdc046542009-05-08 06:58:22 +00004156 // GCC does an implicit conversion to the pointer or integer ValType. This
4157 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00004158 // Initialize the argument.
4159 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4160 ValType, /*consume*/ false);
4161 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00004162 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004163 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00004164
Chris Lattnerdc046542009-05-08 06:58:22 +00004165 // Okay, we have something that *can* be converted to the right type. Check
4166 // to see if there is a potentially weird extension going on here. This can
4167 // happen when you do an atomic operation on something like an char* and
4168 // pass in 42. The 42 gets converted to char. This is even more strange
4169 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00004170 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004171 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00004172 }
Mike Stump11289f42009-09-09 15:08:12 +00004173
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004174 ASTContext& Context = this->getASTContext();
4175
4176 // Create a new DeclRefExpr to refer to the new decl.
4177 DeclRefExpr* NewDRE = DeclRefExpr::Create(
4178 Context,
4179 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00004180 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004181 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00004182 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004183 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00004184 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00004185 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00004186
Chris Lattnerdc046542009-05-08 06:58:22 +00004187 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00004188 // FIXME: This loses syntactic information.
4189 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4190 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4191 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004192 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004193
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004194 // Change the result type of the call to match the original value type. This
4195 // is arbitrary, but the codegen for these builtins ins design to handle it
4196 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004197 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004198
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004199 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004200}
4201
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004202/// SemaBuiltinNontemporalOverloaded - We have a call to
4203/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4204/// overloaded function based on the pointer type of its last argument.
4205///
4206/// This function goes through and does final semantic checking for these
4207/// builtins.
4208ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4209 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4210 DeclRefExpr *DRE =
4211 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4212 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4213 unsigned BuiltinID = FDecl->getBuiltinID();
4214 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4215 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4216 "Unexpected nontemporal load/store builtin!");
4217 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4218 unsigned numArgs = isStore ? 2 : 1;
4219
4220 // Ensure that we have the proper number of arguments.
4221 if (checkArgCount(*this, TheCall, numArgs))
4222 return ExprError();
4223
4224 // Inspect the last argument of the nontemporal builtin. This should always
4225 // be a pointer type, from which we imply the type of the memory access.
4226 // Because it is a pointer type, we don't have to worry about any implicit
4227 // casts here.
4228 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4229 ExprResult PointerArgResult =
4230 DefaultFunctionArrayLvalueConversion(PointerArg);
4231
4232 if (PointerArgResult.isInvalid())
4233 return ExprError();
4234 PointerArg = PointerArgResult.get();
4235 TheCall->setArg(numArgs - 1, PointerArg);
4236
4237 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4238 if (!pointerType) {
4239 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4240 << PointerArg->getType() << PointerArg->getSourceRange();
4241 return ExprError();
4242 }
4243
4244 QualType ValType = pointerType->getPointeeType();
4245
4246 // Strip any qualifiers off ValType.
4247 ValType = ValType.getUnqualifiedType();
4248 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4249 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4250 !ValType->isVectorType()) {
4251 Diag(DRE->getLocStart(),
4252 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4253 << PointerArg->getType() << PointerArg->getSourceRange();
4254 return ExprError();
4255 }
4256
4257 if (!isStore) {
4258 TheCall->setType(ValType);
4259 return TheCallResult;
4260 }
4261
4262 ExprResult ValArg = TheCall->getArg(0);
4263 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4264 Context, ValType, /*consume*/ false);
4265 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4266 if (ValArg.isInvalid())
4267 return ExprError();
4268
4269 TheCall->setArg(0, ValArg.get());
4270 TheCall->setType(Context.VoidTy);
4271 return TheCallResult;
4272}
4273
Chris Lattner6436fb62009-02-18 06:01:06 +00004274/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004275/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004276/// Note: It might also make sense to do the UTF-16 conversion here (would
4277/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004278bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004279 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004280 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4281
Douglas Gregorfb65e592011-07-27 05:40:30 +00004282 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004283 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4284 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004285 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004286 }
Mike Stump11289f42009-09-09 15:08:12 +00004287
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004288 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004289 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004290 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004291 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4292 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4293 llvm::UTF16 *ToPtr = &ToBuf[0];
4294
4295 llvm::ConversionResult Result =
4296 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4297 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004298 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004299 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004300 Diag(Arg->getLocStart(),
4301 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4302 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004303 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004304}
4305
Mehdi Amini06d367c2016-10-24 20:39:34 +00004306/// CheckObjCString - Checks that the format string argument to the os_log()
4307/// and os_trace() functions is correct, and converts it to const char *.
4308ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4309 Arg = Arg->IgnoreParenCasts();
4310 auto *Literal = dyn_cast<StringLiteral>(Arg);
4311 if (!Literal) {
4312 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4313 Literal = ObjcLiteral->getString();
4314 }
4315 }
4316
4317 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4318 return ExprError(
4319 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4320 << Arg->getSourceRange());
4321 }
4322
4323 ExprResult Result(Literal);
4324 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4325 InitializedEntity Entity =
4326 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4327 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4328 return Result;
4329}
4330
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004331/// Check that the user is calling the appropriate va_start builtin for the
4332/// target and calling convention.
4333static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4334 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4335 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004336 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004337 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004338 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4339 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004340 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004341 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4342 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4343 if (IsMSVAStart) {
4344 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004345 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004346 return S.Diag(Fn->getLocStart(),
4347 diag::err_ms_va_start_used_in_sysv_function);
4348 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004349 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004350 // On x64 Windows, don't allow this in System V ABI functions.
4351 // (Yes, that means there's no corresponding way to support variadic
4352 // System V ABI functions on Windows.)
4353 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004354 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004355 return S.Diag(Fn->getLocStart(),
4356 diag::err_va_start_used_in_wrong_abi_function)
4357 << !IsWindows;
4358 }
4359 return false;
4360 }
4361
4362 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004363 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004364 return false;
4365}
4366
4367static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4368 ParmVarDecl **LastParam = nullptr) {
4369 // Determine whether the current function, block, or obj-c method is variadic
4370 // and get its parameter list.
4371 bool IsVariadic = false;
4372 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004373 DeclContext *Caller = S.CurContext;
4374 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4375 IsVariadic = Block->isVariadic();
4376 Params = Block->parameters();
4377 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004378 IsVariadic = FD->isVariadic();
4379 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004380 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004381 IsVariadic = MD->isVariadic();
4382 // FIXME: This isn't correct for methods (results in bogus warning).
4383 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004384 } else if (isa<CapturedDecl>(Caller)) {
4385 // We don't support va_start in a CapturedDecl.
4386 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4387 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004388 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004389 // This must be some other declcontext that parses exprs.
4390 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4391 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004392 }
4393
4394 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004395 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004396 return true;
4397 }
4398
4399 if (LastParam)
4400 *LastParam = Params.empty() ? nullptr : Params.back();
4401
4402 return false;
4403}
4404
Aaron Ballman68d50642018-06-19 14:53:20 +00004405/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4406/// for validity. Emit an error and return true on failure; return false
4407/// on success.
4408bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
4409 Expr *Fn = TheCall->getCallee();
4410
4411 if (checkVAStartABI(*this, BuiltinID, Fn))
4412 return true;
4413
4414 if (TheCall->getNumArgs() > 2) {
4415 Diag(TheCall->getArg(2)->getLocStart(),
4416 diag::err_typecheck_call_too_many_args)
4417 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4418 << Fn->getSourceRange()
4419 << SourceRange(TheCall->getArg(2)->getLocStart(),
4420 (*(TheCall->arg_end()-1))->getLocEnd());
4421 return true;
4422 }
4423
4424 if (TheCall->getNumArgs() < 2) {
4425 return Diag(TheCall->getLocEnd(),
4426 diag::err_typecheck_call_too_few_args_at_least)
4427 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
4428 }
4429
4430 // Type-check the first argument normally.
4431 if (checkBuiltinArgument(*this, TheCall, 0))
4432 return true;
4433
4434 // Check that the current function is variadic, and get its last parameter.
4435 ParmVarDecl *LastParam;
4436 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
4437 return true;
4438
4439 // Verify that the second argument to the builtin is the last argument of the
4440 // current function or method.
4441 bool SecondArgIsLastNamedArgument = false;
4442 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
4443
4444 // These are valid if SecondArgIsLastNamedArgument is false after the next
4445 // block.
4446 QualType Type;
4447 SourceLocation ParamLoc;
4448 bool IsCRegister = false;
4449
4450 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4451 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
4452 SecondArgIsLastNamedArgument = PV == LastParam;
4453
4454 Type = PV->getType();
4455 ParamLoc = PV->getLocation();
4456 IsCRegister =
4457 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
4458 }
4459 }
4460
4461 if (!SecondArgIsLastNamedArgument)
4462 Diag(TheCall->getArg(1)->getLocStart(),
4463 diag::warn_second_arg_of_va_start_not_last_named_param);
4464 else if (IsCRegister || Type->isReferenceType() ||
4465 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4466 // Promotable integers are UB, but enumerations need a bit of
4467 // extra checking to see what their promotable type actually is.
4468 if (!Type->isPromotableIntegerType())
4469 return false;
4470 if (!Type->isEnumeralType())
4471 return true;
4472 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4473 return !(ED &&
4474 Context.typesAreCompatible(ED->getPromotionType(), Type));
4475 }()) {
4476 unsigned Reason = 0;
4477 if (Type->isReferenceType()) Reason = 1;
4478 else if (IsCRegister) Reason = 2;
4479 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
4480 Diag(ParamLoc, diag::note_parameter_type) << Type;
4481 }
4482
4483 TheCall->setType(Context.VoidTy);
4484 return false;
4485}
4486
4487bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
4488 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4489 // const char *named_addr);
4490
4491 Expr *Func = Call->getCallee();
4492
4493 if (Call->getNumArgs() < 3)
4494 return Diag(Call->getLocEnd(),
4495 diag::err_typecheck_call_too_few_args_at_least)
4496 << 0 /*function call*/ << 3 << Call->getNumArgs();
4497
4498 // Type-check the first argument normally.
4499 if (checkBuiltinArgument(*this, Call, 0))
4500 return true;
4501
4502 // Check that the current function is variadic.
4503 if (checkVAStartIsInVariadicFunction(*this, Func))
4504 return true;
4505
4506 // __va_start on Windows does not validate the parameter qualifiers
4507
4508 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4509 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4510
4511 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4512 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4513
4514 const QualType &ConstCharPtrTy =
4515 Context.getPointerType(Context.CharTy.withConst());
4516 if (!Arg1Ty->isPointerType() ||
4517 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4518 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4519 << Arg1->getType() << ConstCharPtrTy
4520 << 1 /* different class */
4521 << 0 /* qualifier difference */
4522 << 3 /* parameter mismatch */
4523 << 2 << Arg1->getType() << ConstCharPtrTy;
4524
4525 const QualType SizeTy = Context.getSizeType();
4526 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4527 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4528 << Arg2->getType() << SizeTy
4529 << 1 /* different class */
4530 << 0 /* qualifier difference */
4531 << 3 /* parameter mismatch */
4532 << 3 << Arg2->getType() << SizeTy;
4533
4534 return false;
4535}
4536
4537/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4538/// friends. This is declared to take (...), so we have to check everything.
4539bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4540 if (TheCall->getNumArgs() < 2)
4541 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4542 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4543 if (TheCall->getNumArgs() > 2)
4544 return Diag(TheCall->getArg(2)->getLocStart(),
4545 diag::err_typecheck_call_too_many_args)
4546 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4547 << SourceRange(TheCall->getArg(2)->getLocStart(),
4548 (*(TheCall->arg_end()-1))->getLocEnd());
4549
4550 ExprResult OrigArg0 = TheCall->getArg(0);
4551 ExprResult OrigArg1 = TheCall->getArg(1);
4552
4553 // Do standard promotions between the two arguments, returning their common
4554 // type.
4555 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4556 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4557 return true;
4558
4559 // Make sure any conversions are pushed back into the call; this is
4560 // type safe since unordered compare builtins are declared as "_Bool
4561 // foo(...)".
4562 TheCall->setArg(0, OrigArg0.get());
4563 TheCall->setArg(1, OrigArg1.get());
4564
4565 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4566 return false;
4567
4568 // If the common type isn't a real floating type, then the arguments were
4569 // invalid for this operation.
4570 if (Res.isNull() || !Res->isRealFloatingType())
4571 return Diag(OrigArg0.get()->getLocStart(),
4572 diag::err_typecheck_call_invalid_ordered_compare)
4573 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4574 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4575
4576 return false;
4577}
4578
4579/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4580/// __builtin_isnan and friends. This is declared to take (...), so we have
4581/// to check everything. We expect the last argument to be a floating point
4582/// value.
4583bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4584 if (TheCall->getNumArgs() < NumArgs)
4585 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4586 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4587 if (TheCall->getNumArgs() > NumArgs)
4588 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4589 diag::err_typecheck_call_too_many_args)
4590 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4591 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4592 (*(TheCall->arg_end()-1))->getLocEnd());
4593
4594 Expr *OrigArg = TheCall->getArg(NumArgs-1);
4595
4596 if (OrigArg->isTypeDependent())
4597 return false;
4598
4599 // This operation requires a non-_Complex floating-point number.
4600 if (!OrigArg->getType()->isRealFloatingType())
4601 return Diag(OrigArg->getLocStart(),
4602 diag::err_typecheck_call_invalid_unary_fp)
4603 << OrigArg->getType() << OrigArg->getSourceRange();
4604
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00004605 // If this is an implicit conversion from float -> float, double, or
4606 // long double, remove it.
Aaron Ballman68d50642018-06-19 14:53:20 +00004607 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4608 // Only remove standard FloatCasts, leaving other casts inplace
4609 if (Cast->getCastKind() == CK_FloatingCast) {
4610 Expr *CastArg = Cast->getSubExpr();
4611 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
Aaron Ballmandd0e2b02018-06-19 14:59:11 +00004612 assert(
4613 (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4614 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
4615 Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
4616 "promotion from float to either float, double, or long double is "
4617 "the only expected cast here");
Aaron Ballman68d50642018-06-19 14:53:20 +00004618 Cast->setSubExpr(nullptr);
4619 TheCall->setArg(NumArgs-1, CastArg);
4620 }
4621 }
4622 }
4623
4624 return false;
4625}
4626
4627// Customized Sema Checking for VSX builtins that have the following signature:
4628// vector [...] builtinName(vector [...], vector [...], const int);
4629// Which takes the same type of vectors (any legal vector type) for the first
4630// two arguments and takes compile time constant for the third argument.
4631// Example builtins are :
4632// vector double vec_xxpermdi(vector double, vector double, int);
4633// vector short vec_xxsldwi(vector short, vector short, int);
4634bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4635 unsigned ExpectedNumArgs = 3;
4636 if (TheCall->getNumArgs() < ExpectedNumArgs)
4637 return Diag(TheCall->getLocEnd(),
4638 diag::err_typecheck_call_too_few_args_at_least)
4639 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4640 << TheCall->getSourceRange();
4641
4642 if (TheCall->getNumArgs() > ExpectedNumArgs)
4643 return Diag(TheCall->getLocEnd(),
4644 diag::err_typecheck_call_too_many_args_at_most)
4645 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4646 << TheCall->getSourceRange();
4647
4648 // Check the third argument is a compile time constant
4649 llvm::APSInt Value;
4650 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4651 return Diag(TheCall->getLocStart(),
4652 diag::err_vsx_builtin_nonconstant_argument)
4653 << 3 /* argument index */ << TheCall->getDirectCallee()
4654 << SourceRange(TheCall->getArg(2)->getLocStart(),
4655 TheCall->getArg(2)->getLocEnd());
4656
4657 QualType Arg1Ty = TheCall->getArg(0)->getType();
4658 QualType Arg2Ty = TheCall->getArg(1)->getType();
4659
4660 // Check the type of argument 1 and argument 2 are vectors.
4661 SourceLocation BuiltinLoc = TheCall->getLocStart();
4662 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4663 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4664 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4665 << TheCall->getDirectCallee()
4666 << SourceRange(TheCall->getArg(0)->getLocStart(),
4667 TheCall->getArg(1)->getLocEnd());
4668 }
4669
4670 // Check the first two arguments are the same type.
4671 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4672 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4673 << TheCall->getDirectCallee()
4674 << SourceRange(TheCall->getArg(0)->getLocStart(),
4675 TheCall->getArg(1)->getLocEnd());
4676 }
4677
4678 // When default clang type checking is turned off and the customized type
4679 // checking is used, the returning type of the function must be explicitly
4680 // set. Otherwise it is _Bool by default.
4681 TheCall->setType(Arg1Ty);
4682
4683 return false;
4684}
4685
4686/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4687// This is declared to take (...), so we have to check everything.
4688ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4689 if (TheCall->getNumArgs() < 2)
4690 return ExprError(Diag(TheCall->getLocEnd(),
4691 diag::err_typecheck_call_too_few_args_at_least)
4692 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4693 << TheCall->getSourceRange());
4694
4695 // Determine which of the following types of shufflevector we're checking:
4696 // 1) unary, vector mask: (lhs, mask)
4697 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4698 QualType resType = TheCall->getArg(0)->getType();
4699 unsigned numElements = 0;
4700
4701 if (!TheCall->getArg(0)->isTypeDependent() &&
4702 !TheCall->getArg(1)->isTypeDependent()) {
4703 QualType LHSType = TheCall->getArg(0)->getType();
4704 QualType RHSType = TheCall->getArg(1)->getType();
4705
4706 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4707 return ExprError(Diag(TheCall->getLocStart(),
4708 diag::err_vec_builtin_non_vector)
4709 << TheCall->getDirectCallee()
4710 << SourceRange(TheCall->getArg(0)->getLocStart(),
4711 TheCall->getArg(1)->getLocEnd()));
4712
4713 numElements = LHSType->getAs<VectorType>()->getNumElements();
4714 unsigned numResElements = TheCall->getNumArgs() - 2;
4715
4716 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4717 // with mask. If so, verify that RHS is an integer vector type with the
4718 // same number of elts as lhs.
4719 if (TheCall->getNumArgs() == 2) {
4720 if (!RHSType->hasIntegerRepresentation() ||
4721 RHSType->getAs<VectorType>()->getNumElements() != numElements)
4722 return ExprError(Diag(TheCall->getLocStart(),
4723 diag::err_vec_builtin_incompatible_vector)
4724 << TheCall->getDirectCallee()
4725 << SourceRange(TheCall->getArg(1)->getLocStart(),
4726 TheCall->getArg(1)->getLocEnd()));
4727 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4728 return ExprError(Diag(TheCall->getLocStart(),
4729 diag::err_vec_builtin_incompatible_vector)
4730 << TheCall->getDirectCallee()
4731 << SourceRange(TheCall->getArg(0)->getLocStart(),
4732 TheCall->getArg(1)->getLocEnd()));
4733 } else if (numElements != numResElements) {
4734 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4735 resType = Context.getVectorType(eltType, numResElements,
4736 VectorType::GenericVector);
4737 }
4738 }
4739
4740 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4741 if (TheCall->getArg(i)->isTypeDependent() ||
4742 TheCall->getArg(i)->isValueDependent())
4743 continue;
4744
4745 llvm::APSInt Result(32);
4746 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4747 return ExprError(Diag(TheCall->getLocStart(),
4748 diag::err_shufflevector_nonconstant_argument)
4749 << TheCall->getArg(i)->getSourceRange());
4750
4751 // Allow -1 which will be translated to undef in the IR.
4752 if (Result.isSigned() && Result.isAllOnesValue())
4753 continue;
4754
4755 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4756 return ExprError(Diag(TheCall->getLocStart(),
4757 diag::err_shufflevector_argument_too_large)
4758 << TheCall->getArg(i)->getSourceRange());
4759 }
4760
4761 SmallVector<Expr*, 32> exprs;
4762
4763 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4764 exprs.push_back(TheCall->getArg(i));
4765 TheCall->setArg(i, nullptr);
4766 }
4767
4768 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4769 TheCall->getCallee()->getLocStart(),
4770 TheCall->getRParenLoc());
4771}
4772
4773/// SemaConvertVectorExpr - Handle __builtin_convertvector
4774ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4775 SourceLocation BuiltinLoc,
4776 SourceLocation RParenLoc) {
4777 ExprValueKind VK = VK_RValue;
4778 ExprObjectKind OK = OK_Ordinary;
4779 QualType DstTy = TInfo->getType();
4780 QualType SrcTy = E->getType();
4781
4782 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4783 return ExprError(Diag(BuiltinLoc,
4784 diag::err_convertvector_non_vector)
4785 << E->getSourceRange());
4786 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4787 return ExprError(Diag(BuiltinLoc,
4788 diag::err_convertvector_non_vector_type));
4789
4790 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4791 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4792 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4793 if (SrcElts != DstElts)
4794 return ExprError(Diag(BuiltinLoc,
4795 diag::err_convertvector_incompatible_vector)
4796 << E->getSourceRange());
4797 }
4798
4799 return new (Context)
4800 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4801}
4802
4803/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4804// This is declared to take (const void*, ...) and can take two
4805// optional constant int args.
4806bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4807 unsigned NumArgs = TheCall->getNumArgs();
4808
4809 if (NumArgs > 3)
4810 return Diag(TheCall->getLocEnd(),
4811 diag::err_typecheck_call_too_many_args_at_most)
4812 << 0 /*function call*/ << 3 << NumArgs
4813 << TheCall->getSourceRange();
4814
4815 // Argument 0 is checked for us and the remaining arguments must be
4816 // constant integers.
4817 for (unsigned i = 1; i != NumArgs; ++i)
Richard Sandiford28940af2014-04-16 08:47:51 +00004818 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004819 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004820
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004821 return false;
4822}
4823
Hal Finkelf0417332014-07-17 14:25:55 +00004824/// SemaBuiltinAssume - Handle __assume (MS Extension).
4825// __assume does not evaluate its arguments, and should warn if its argument
4826// has side effects.
4827bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4828 Expr *Arg = TheCall->getArg(0);
4829 if (Arg->isInstantiationDependent()) return false;
4830
4831 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004832 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004833 << Arg->getSourceRange()
4834 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4835
4836 return false;
4837}
4838
David Majnemer86b1bfa2016-10-31 18:07:57 +00004839/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004840/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4841/// than 8.
4842bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4843 // The alignment must be a constant integer.
4844 Expr *Arg = TheCall->getArg(1);
4845
4846 // We can't check the value of a dependent argument.
4847 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004848 if (const auto *UE =
4849 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4850 if (UE->getKind() == UETT_AlignOf)
4851 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4852 << Arg->getSourceRange();
4853
David Majnemer51169932016-10-31 05:37:48 +00004854 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4855
4856 if (!Result.isPowerOf2())
4857 return Diag(TheCall->getLocStart(),
4858 diag::err_alignment_not_power_of_two)
4859 << Arg->getSourceRange();
4860
4861 if (Result < Context.getCharWidth())
4862 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4863 << (unsigned)Context.getCharWidth()
4864 << Arg->getSourceRange();
4865
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004866 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004867 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004868 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004869 << Arg->getSourceRange();
4870 }
4871
4872 return false;
4873}
4874
4875/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004876/// as (const void*, size_t, ...) and can take one optional constant int arg.
4877bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4878 unsigned NumArgs = TheCall->getNumArgs();
4879
4880 if (NumArgs > 3)
4881 return Diag(TheCall->getLocEnd(),
4882 diag::err_typecheck_call_too_many_args_at_most)
4883 << 0 /*function call*/ << 3 << NumArgs
4884 << TheCall->getSourceRange();
4885
4886 // The alignment must be a constant integer.
4887 Expr *Arg = TheCall->getArg(1);
4888
4889 // We can't check the value of a dependent argument.
4890 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4891 llvm::APSInt Result;
4892 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4893 return true;
4894
4895 if (!Result.isPowerOf2())
4896 return Diag(TheCall->getLocStart(),
4897 diag::err_alignment_not_power_of_two)
4898 << Arg->getSourceRange();
4899 }
4900
4901 if (NumArgs > 2) {
4902 ExprResult Arg(TheCall->getArg(2));
4903 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4904 Context.getSizeType(), false);
4905 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4906 if (Arg.isInvalid()) return true;
4907 TheCall->setArg(2, Arg.get());
4908 }
Hal Finkelf0417332014-07-17 14:25:55 +00004909
4910 return false;
4911}
4912
Mehdi Amini06d367c2016-10-24 20:39:34 +00004913bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4914 unsigned BuiltinID =
4915 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4916 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4917
4918 unsigned NumArgs = TheCall->getNumArgs();
4919 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4920 if (NumArgs < NumRequiredArgs) {
4921 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4922 << 0 /* function call */ << NumRequiredArgs << NumArgs
4923 << TheCall->getSourceRange();
4924 }
4925 if (NumArgs >= NumRequiredArgs + 0x100) {
4926 return Diag(TheCall->getLocEnd(),
4927 diag::err_typecheck_call_too_many_args_at_most)
4928 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4929 << TheCall->getSourceRange();
4930 }
4931 unsigned i = 0;
4932
4933 // For formatting call, check buffer arg.
4934 if (!IsSizeCall) {
4935 ExprResult Arg(TheCall->getArg(i));
4936 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4937 Context, Context.VoidPtrTy, false);
4938 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4939 if (Arg.isInvalid())
4940 return true;
4941 TheCall->setArg(i, Arg.get());
4942 i++;
4943 }
4944
4945 // Check string literal arg.
4946 unsigned FormatIdx = i;
4947 {
4948 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4949 if (Arg.isInvalid())
4950 return true;
4951 TheCall->setArg(i, Arg.get());
4952 i++;
4953 }
4954
4955 // Make sure variadic args are scalar.
4956 unsigned FirstDataArg = i;
4957 while (i < NumArgs) {
4958 ExprResult Arg = DefaultVariadicArgumentPromotion(
4959 TheCall->getArg(i), VariadicFunction, nullptr);
4960 if (Arg.isInvalid())
4961 return true;
4962 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4963 if (ArgSize.getQuantity() >= 0x100) {
4964 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4965 << i << (int)ArgSize.getQuantity() << 0xff
4966 << TheCall->getSourceRange();
4967 }
4968 TheCall->setArg(i, Arg.get());
4969 i++;
4970 }
4971
4972 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4973 // call to avoid duplicate diagnostics.
4974 if (!IsSizeCall) {
4975 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4976 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4977 bool Success = CheckFormatArguments(
4978 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4979 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4980 CheckedVarArgs);
4981 if (!Success)
4982 return true;
4983 }
4984
4985 if (IsSizeCall) {
4986 TheCall->setType(Context.getSizeType());
4987 } else {
4988 TheCall->setType(Context.VoidPtrTy);
4989 }
4990 return false;
4991}
4992
Eric Christopher8d0c6212010-04-17 02:26:23 +00004993/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4994/// TheCall is a constant expression.
4995bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4996 llvm::APSInt &Result) {
4997 Expr *Arg = TheCall->getArg(ArgNum);
4998 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4999 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5000
5001 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5002
5003 if (!Arg->isIntegerConstantExpr(Result, Context))
5004 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00005005 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00005006
Chris Lattnerd545ad12009-09-23 06:06:36 +00005007 return false;
5008}
5009
Richard Sandiford28940af2014-04-16 08:47:51 +00005010/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5011/// TheCall is a constant expression in the range [Low, High].
5012bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005013 int Low, int High, bool RangeIsError) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00005014 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005015
5016 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00005017 Expr *Arg = TheCall->getArg(ArgNum);
5018 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00005019 return false;
5020
Eric Christopher8d0c6212010-04-17 02:26:23 +00005021 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00005022 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00005023 return true;
5024
Chandler Carruth16e6bc22018-06-21 23:46:09 +00005025 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5026 if (RangeIsError)
5027 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
5028 << Result.toString(10) << Low << High << Arg->getSourceRange();
5029 else
5030 // Defer the warning until we know if the code will be emitted so that
5031 // dead code can ignore this.
5032 DiagRuntimeBehavior(TheCall->getLocStart(), TheCall,
5033 PDiag(diag::warn_argument_invalid_range)
5034 << Result.toString(10) << Low << High
5035 << Arg->getSourceRange());
5036 }
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00005037
5038 return false;
5039}
5040
Simon Dardis1f90f2d2016-10-19 17:50:52 +00005041/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5042/// TheCall is a constant expression is a multiple of Num..
5043bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5044 unsigned Num) {
5045 llvm::APSInt Result;
5046
5047 // We can't check the value of a dependent argument.
5048 Expr *Arg = TheCall->getArg(ArgNum);
5049 if (Arg->isTypeDependent() || Arg->isValueDependent())
5050 return false;
5051
5052 // Check constant-ness first.
5053 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5054 return true;
5055
5056 if (Result.getSExtValue() % Num != 0)
5057 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
5058 << Num << Arg->getSourceRange();
5059
5060 return false;
5061}
5062
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005063/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5064/// TheCall is an ARM/AArch64 special register string literal.
5065bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5066 int ArgNum, unsigned ExpectedFieldNum,
5067 bool AllowName) {
5068 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5069 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5070 BuiltinID == ARM::BI__builtin_arm_rsr ||
5071 BuiltinID == ARM::BI__builtin_arm_rsrp ||
5072 BuiltinID == ARM::BI__builtin_arm_wsr ||
5073 BuiltinID == ARM::BI__builtin_arm_wsrp;
5074 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5075 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5076 BuiltinID == AArch64::BI__builtin_arm_rsr ||
5077 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5078 BuiltinID == AArch64::BI__builtin_arm_wsr ||
5079 BuiltinID == AArch64::BI__builtin_arm_wsrp;
5080 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5081
5082 // We can't check the value of a dependent argument.
5083 Expr *Arg = TheCall->getArg(ArgNum);
5084 if (Arg->isTypeDependent() || Arg->isValueDependent())
5085 return false;
5086
5087 // Check if the argument is a string literal.
5088 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5089 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
5090 << Arg->getSourceRange();
5091
5092 // Check the type of special register given.
5093 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5094 SmallVector<StringRef, 6> Fields;
5095 Reg.split(Fields, ":");
5096
5097 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5098 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5099 << Arg->getSourceRange();
5100
5101 // If the string is the name of a register then we cannot check that it is
5102 // valid here but if the string is of one the forms described in ACLE then we
5103 // can check that the supplied fields are integers and within the valid
5104 // ranges.
5105 if (Fields.size() > 1) {
5106 bool FiveFields = Fields.size() == 5;
5107
5108 bool ValidString = true;
5109 if (IsARMBuiltin) {
5110 ValidString &= Fields[0].startswith_lower("cp") ||
5111 Fields[0].startswith_lower("p");
5112 if (ValidString)
5113 Fields[0] =
5114 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5115
5116 ValidString &= Fields[2].startswith_lower("c");
5117 if (ValidString)
5118 Fields[2] = Fields[2].drop_front(1);
5119
5120 if (FiveFields) {
5121 ValidString &= Fields[3].startswith_lower("c");
5122 if (ValidString)
5123 Fields[3] = Fields[3].drop_front(1);
5124 }
5125 }
5126
5127 SmallVector<int, 5> Ranges;
5128 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00005129 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005130 else
5131 Ranges.append({15, 7, 15});
5132
5133 for (unsigned i=0; i<Fields.size(); ++i) {
5134 int IntField;
5135 ValidString &= !Fields[i].getAsInteger(10, IntField);
5136 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5137 }
5138
5139 if (!ValidString)
5140 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
5141 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00005142 } else if (IsAArch64Builtin && Fields.size() == 1) {
5143 // If the register name is one of those that appear in the condition below
5144 // and the special register builtin being used is one of the write builtins,
5145 // then we require that the argument provided for writing to the register
5146 // is an integer constant expression. This is because it will be lowered to
5147 // an MSR (immediate) instruction, so we need to know the immediate at
5148 // compile time.
5149 if (TheCall->getNumArgs() != 2)
5150 return false;
5151
5152 std::string RegLower = Reg.lower();
5153 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5154 RegLower != "pan" && RegLower != "uao")
5155 return false;
5156
5157 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5158 }
5159
5160 return false;
5161}
5162
Eli Friedmanc97d0142009-05-03 06:04:26 +00005163/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005164/// This checks that the target supports __builtin_longjmp and
5165/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005166bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005167 if (!Context.getTargetInfo().hasSjLjLowering())
5168 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
5169 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5170
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005171 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00005172 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00005173
Eric Christopher8d0c6212010-04-17 02:26:23 +00005174 // TODO: This is less than ideal. Overload this to take a value.
5175 if (SemaBuiltinConstantArg(TheCall, 1, Result))
5176 return true;
5177
5178 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00005179 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
5180 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
5181
5182 return false;
5183}
5184
Joerg Sonnenberger27173282015-03-11 23:46:32 +00005185/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
5186/// This checks that the target supports __builtin_setjmp.
5187bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
5188 if (!Context.getTargetInfo().hasSjLjLowering())
5189 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
5190 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
5191 return false;
5192}
5193
Richard Smithd7293d72013-08-05 18:49:43 +00005194namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005195
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005196class UncoveredArgHandler {
5197 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005198
5199 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005200 SmallVector<const Expr *, 4> DiagnosticExprs;
5201
5202public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005203 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005204
5205 bool hasUncoveredArg() const {
5206 return (FirstUncoveredArg >= 0);
5207 }
5208
5209 unsigned getUncoveredArg() const {
5210 assert(hasUncoveredArg() && "no uncovered argument");
5211 return FirstUncoveredArg;
5212 }
5213
5214 void setAllCovered() {
5215 // A string has been found with all arguments covered, so clear out
5216 // the diagnostics.
5217 DiagnosticExprs.clear();
5218 FirstUncoveredArg = AllCovered;
5219 }
5220
5221 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5222 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5223
5224 // Don't update if a previous string covers all arguments.
5225 if (FirstUncoveredArg == AllCovered)
5226 return;
5227
5228 // UncoveredArgHandler tracks the highest uncovered argument index
5229 // and with it all the strings that match this index.
5230 if (NewFirstUncoveredArg == FirstUncoveredArg)
5231 DiagnosticExprs.push_back(StrExpr);
5232 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5233 DiagnosticExprs.clear();
5234 DiagnosticExprs.push_back(StrExpr);
5235 FirstUncoveredArg = NewFirstUncoveredArg;
5236 }
5237 }
5238
5239 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5240};
5241
Richard Smithd7293d72013-08-05 18:49:43 +00005242enum StringLiteralCheckType {
5243 SLCT_NotALiteral,
5244 SLCT_UncheckedLiteral,
5245 SLCT_CheckedLiteral
5246};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005247
5248} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005249
Stephen Hines648c3692016-09-16 01:07:04 +00005250static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5251 BinaryOperatorKind BinOpKind,
5252 bool AddendIsRight) {
5253 unsigned BitWidth = Offset.getBitWidth();
5254 unsigned AddendBitWidth = Addend.getBitWidth();
5255 // There might be negative interim results.
5256 if (Addend.isUnsigned()) {
5257 Addend = Addend.zext(++AddendBitWidth);
5258 Addend.setIsSigned(true);
5259 }
5260 // Adjust the bit width of the APSInts.
5261 if (AddendBitWidth > BitWidth) {
5262 Offset = Offset.sext(AddendBitWidth);
5263 BitWidth = AddendBitWidth;
5264 } else if (BitWidth > AddendBitWidth) {
5265 Addend = Addend.sext(BitWidth);
5266 }
5267
5268 bool Ov = false;
5269 llvm::APSInt ResOffset = Offset;
5270 if (BinOpKind == BO_Add)
5271 ResOffset = Offset.sadd_ov(Addend, Ov);
5272 else {
5273 assert(AddendIsRight && BinOpKind == BO_Sub &&
5274 "operator must be add or sub with addend on the right");
5275 ResOffset = Offset.ssub_ov(Addend, Ov);
5276 }
5277
5278 // We add an offset to a pointer here so we should support an offset as big as
5279 // possible.
5280 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005281 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5282 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005283 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005284 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5285 return;
5286 }
5287
5288 Offset = ResOffset;
5289}
5290
5291namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005292
Stephen Hines648c3692016-09-16 01:07:04 +00005293// This is a wrapper class around StringLiteral to support offsetted string
5294// literals as format strings. It takes the offset into account when returning
5295// the string and its length or the source locations to display notes correctly.
5296class FormatStringLiteral {
5297 const StringLiteral *FExpr;
5298 int64_t Offset;
5299
5300 public:
5301 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5302 : FExpr(fexpr), Offset(Offset) {}
5303
5304 StringRef getString() const {
5305 return FExpr->getString().drop_front(Offset);
5306 }
5307
5308 unsigned getByteLength() const {
5309 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5310 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005311
Stephen Hines648c3692016-09-16 01:07:04 +00005312 unsigned getLength() const { return FExpr->getLength() - Offset; }
5313 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5314
5315 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5316
5317 QualType getType() const { return FExpr->getType(); }
5318
5319 bool isAscii() const { return FExpr->isAscii(); }
5320 bool isWide() const { return FExpr->isWide(); }
5321 bool isUTF8() const { return FExpr->isUTF8(); }
5322 bool isUTF16() const { return FExpr->isUTF16(); }
5323 bool isUTF32() const { return FExpr->isUTF32(); }
5324 bool isPascal() const { return FExpr->isPascal(); }
5325
5326 SourceLocation getLocationOfByte(
5327 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5328 const TargetInfo &Target, unsigned *StartToken = nullptr,
5329 unsigned *StartTokenByteOffset = nullptr) const {
5330 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5331 StartToken, StartTokenByteOffset);
5332 }
5333
5334 SourceLocation getLocStart() const LLVM_READONLY {
5335 return FExpr->getLocStart().getLocWithOffset(Offset);
5336 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005337
Stephen Hines648c3692016-09-16 01:07:04 +00005338 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5339};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005340
5341} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005342
5343static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005344 const Expr *OrigFormatExpr,
5345 ArrayRef<const Expr *> Args,
5346 bool HasVAListArg, unsigned format_idx,
5347 unsigned firstDataArg,
5348 Sema::FormatStringType Type,
5349 bool inFunctionCall,
5350 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005351 llvm::SmallBitVector &CheckedVarArgs,
5352 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005353
Richard Smith55ce3522012-06-25 20:30:08 +00005354// Determine if an expression is a string literal or constant string.
5355// If this function returns false on the arguments to a function expecting a
5356// format string, we will usually need to emit a warning.
5357// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005358static StringLiteralCheckType
5359checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5360 bool HasVAListArg, unsigned format_idx,
5361 unsigned firstDataArg, Sema::FormatStringType Type,
5362 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005363 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005364 UncoveredArgHandler &UncoveredArg,
5365 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005366 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005367 assert(Offset.isSigned() && "invalid offset");
5368
Douglas Gregorc25f7662009-05-19 22:10:17 +00005369 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005370 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005371
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005372 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005373
Richard Smithd7293d72013-08-05 18:49:43 +00005374 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005375 // Technically -Wformat-nonliteral does not warn about this case.
5376 // The behavior of printf and friends in this case is implementation
5377 // dependent. Ideally if the format string cannot be null then
5378 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005379 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005380
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005381 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005382 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005383 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005384 // The expression is a literal if both sub-expressions were, and it was
5385 // completely checked only if both sub-expressions were checked.
5386 const AbstractConditionalOperator *C =
5387 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005388
5389 // Determine whether it is necessary to check both sub-expressions, for
5390 // example, because the condition expression is a constant that can be
5391 // evaluated at compile time.
5392 bool CheckLeft = true, CheckRight = true;
5393
5394 bool Cond;
5395 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5396 if (Cond)
5397 CheckRight = false;
5398 else
5399 CheckLeft = false;
5400 }
5401
Stephen Hines648c3692016-09-16 01:07:04 +00005402 // We need to maintain the offsets for the right and the left hand side
5403 // separately to check if every possible indexed expression is a valid
5404 // string literal. They might have different offsets for different string
5405 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005406 StringLiteralCheckType Left;
5407 if (!CheckLeft)
5408 Left = SLCT_UncheckedLiteral;
5409 else {
5410 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5411 HasVAListArg, format_idx, firstDataArg,
5412 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005413 CheckedVarArgs, UncoveredArg, Offset);
5414 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005415 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005416 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005417 }
5418
Richard Smith55ce3522012-06-25 20:30:08 +00005419 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005420 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005421 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005422 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005423 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005424
5425 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005426 }
5427
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005428 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005429 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5430 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005431
John McCallc07a0c72011-02-17 10:25:35 +00005432 case Stmt::OpaqueValueExprClass:
5433 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5434 E = src;
5435 goto tryAgain;
5436 }
Richard Smith55ce3522012-06-25 20:30:08 +00005437 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005438
Ted Kremeneka8890832011-02-24 23:03:04 +00005439 case Stmt::PredefinedExprClass:
5440 // While __func__, etc., are technically not string literals, they
5441 // cannot contain format specifiers and thus are not a security
5442 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005443 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005444
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005445 case Stmt::DeclRefExprClass: {
5446 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005447
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005448 // As an exception, do not flag errors for variables binding to
5449 // const string literals.
5450 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5451 bool isConstant = false;
5452 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005453
Richard Smithd7293d72013-08-05 18:49:43 +00005454 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5455 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005456 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005457 isConstant = T.isConstant(S.Context) &&
5458 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005459 } else if (T->isObjCObjectPointerType()) {
5460 // In ObjC, there is usually no "const ObjectPointer" type,
5461 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005462 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005463 }
Mike Stump11289f42009-09-09 15:08:12 +00005464
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005465 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005466 if (const Expr *Init = VD->getAnyInitializer()) {
5467 // Look through initializers like const char c[] = { "foo" }
5468 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5469 if (InitList->isStringLiteralInit())
5470 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5471 }
Richard Smithd7293d72013-08-05 18:49:43 +00005472 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005473 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005474 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005475 /*InFunctionCall*/ false, CheckedVarArgs,
5476 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005477 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005478 }
Mike Stump11289f42009-09-09 15:08:12 +00005479
Anders Carlssonb012ca92009-06-28 19:55:58 +00005480 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5481 // special check to see if the format string is a function parameter
5482 // of the function calling the printf function. If the function
5483 // has an attribute indicating it is a printf-like function, then we
5484 // should suppress warnings concerning non-literals being used in a call
5485 // to a vprintf function. For example:
5486 //
5487 // void
5488 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5489 // va_list ap;
5490 // va_start(ap, fmt);
5491 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5492 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005493 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005494 if (HasVAListArg) {
5495 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5496 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5497 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005498 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005499 // adjust for implicit parameter
5500 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5501 if (MD->isInstance())
5502 ++PVIndex;
5503 // We also check if the formats are compatible.
5504 // We can't pass a 'scanf' string to a 'printf' function.
5505 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005506 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005507 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005508 }
5509 }
5510 }
5511 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005512 }
Mike Stump11289f42009-09-09 15:08:12 +00005513
Richard Smith55ce3522012-06-25 20:30:08 +00005514 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005515 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005516
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005517 case Stmt::CallExprClass:
5518 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005519 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005520 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5521 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005522 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005523 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005524 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005525 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005526 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005527 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5528 unsigned BuiltinID = FD->getBuiltinID();
5529 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5530 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5531 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005532 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005533 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005534 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005535 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005536 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005537 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005538 }
5539 }
Mike Stump11289f42009-09-09 15:08:12 +00005540
Richard Smith55ce3522012-06-25 20:30:08 +00005541 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005542 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005543 case Stmt::ObjCMessageExprClass: {
5544 const auto *ME = cast<ObjCMessageExpr>(E);
5545 if (const auto *ND = ME->getMethodDecl()) {
5546 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005547 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005548 return checkFormatStringExpr(
5549 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5550 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5551 }
5552 }
5553
5554 return SLCT_NotALiteral;
5555 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005556 case Stmt::ObjCStringLiteralClass:
5557 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005558 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005559
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005560 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005561 StrE = ObjCFExpr->getString();
5562 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005563 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005564
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005565 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005566 if (Offset.isNegative() || Offset > StrE->getLength()) {
5567 // TODO: It would be better to have an explicit warning for out of
5568 // bounds literals.
5569 return SLCT_NotALiteral;
5570 }
5571 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5572 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005573 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005574 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005575 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005576 }
Mike Stump11289f42009-09-09 15:08:12 +00005577
Richard Smith55ce3522012-06-25 20:30:08 +00005578 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005579 }
Stephen Hines648c3692016-09-16 01:07:04 +00005580 case Stmt::BinaryOperatorClass: {
5581 llvm::APSInt LResult;
5582 llvm::APSInt RResult;
5583
5584 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5585
5586 // A string literal + an int offset is still a string literal.
5587 if (BinOp->isAdditiveOp()) {
5588 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5589 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5590
5591 if (LIsInt != RIsInt) {
5592 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5593
5594 if (LIsInt) {
5595 if (BinOpKind == BO_Add) {
5596 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5597 E = BinOp->getRHS();
5598 goto tryAgain;
5599 }
5600 } else {
5601 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5602 E = BinOp->getLHS();
5603 goto tryAgain;
5604 }
5605 }
Stephen Hines648c3692016-09-16 01:07:04 +00005606 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005607
5608 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005609 }
5610 case Stmt::UnaryOperatorClass: {
5611 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5612 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005613 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005614 llvm::APSInt IndexResult;
5615 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5616 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5617 E = ASE->getBase();
5618 goto tryAgain;
5619 }
5620 }
5621
5622 return SLCT_NotALiteral;
5623 }
Mike Stump11289f42009-09-09 15:08:12 +00005624
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005625 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005626 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005627 }
5628}
5629
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005630Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005631 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005632 .Case("scanf", FST_Scanf)
5633 .Cases("printf", "printf0", FST_Printf)
5634 .Cases("NSString", "CFString", FST_NSString)
5635 .Case("strftime", FST_Strftime)
5636 .Case("strfmon", FST_Strfmon)
5637 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5638 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5639 .Case("os_trace", FST_OSLog)
5640 .Case("os_log", FST_OSLog)
5641 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005642}
5643
Jordan Rose3e0ec582012-07-19 18:10:23 +00005644/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005645/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005646/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005647bool Sema::CheckFormatArguments(const FormatAttr *Format,
5648 ArrayRef<const Expr *> Args,
5649 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005650 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005651 SourceLocation Loc, SourceRange Range,
5652 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005653 FormatStringInfo FSI;
5654 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005655 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005656 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005657 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005658 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005659}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005660
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005661bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005662 bool HasVAListArg, unsigned format_idx,
5663 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005664 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005665 SourceLocation Loc, SourceRange Range,
5666 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005667 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005668 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005669 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005670 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005671 }
Mike Stump11289f42009-09-09 15:08:12 +00005672
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005673 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005674
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005675 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005676 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005677 // Dynamically generated format strings are difficult to
5678 // automatically vet at compile time. Requiring that format strings
5679 // are string literals: (1) permits the checking of format strings by
5680 // the compiler and thereby (2) can practically remove the source of
5681 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005682
Mike Stump11289f42009-09-09 15:08:12 +00005683 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005684 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005685 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005686 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005687 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005688 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005689 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5690 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005691 /*IsFunctionCall*/ true, CheckedVarArgs,
5692 UncoveredArg,
5693 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005694
5695 // Generate a diagnostic where an uncovered argument is detected.
5696 if (UncoveredArg.hasUncoveredArg()) {
5697 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5698 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5699 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5700 }
5701
Richard Smith55ce3522012-06-25 20:30:08 +00005702 if (CT != SLCT_NotALiteral)
5703 // Literal format string found, check done!
5704 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005705
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005706 // Strftime is particular as it always uses a single 'time' argument,
5707 // so it is safe to pass a non-literal string.
5708 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005709 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005710
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005711 // Do not emit diag when the string param is a macro expansion and the
5712 // format is either NSString or CFString. This is a hack to prevent
5713 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5714 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005715 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5716 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005717 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005718
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005719 // If there are no arguments specified, warn with -Wformat-security, otherwise
5720 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005721 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005722 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5723 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005724 switch (Type) {
5725 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005726 break;
5727 case FST_Kprintf:
5728 case FST_FreeBSDKPrintf:
5729 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005730 Diag(FormatLoc, diag::note_format_security_fixit)
5731 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005732 break;
5733 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005734 Diag(FormatLoc, diag::note_format_security_fixit)
5735 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005736 break;
5737 }
5738 } else {
5739 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005740 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005741 }
Richard Smith55ce3522012-06-25 20:30:08 +00005742 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005743}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005744
Ted Kremenekab278de2010-01-28 23:39:18 +00005745namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005746
Ted Kremenek02087932010-07-16 02:11:22 +00005747class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5748protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005749 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005750 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005751 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005752 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005753 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005754 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005755 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005756 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005757 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005758 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005759 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005760 bool usesPositionalArgs = false;
5761 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005762 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005763 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005764 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005765 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005766
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005767public:
Stephen Hines648c3692016-09-16 01:07:04 +00005768 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005769 const Expr *origFormatExpr,
5770 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005771 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005772 ArrayRef<const Expr *> Args, unsigned formatIdx,
5773 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005774 llvm::SmallBitVector &CheckedVarArgs,
5775 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005776 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5777 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5778 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005779 inFunctionCall(inFunctionCall), CallType(callType),
5780 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005781 CoveredArgs.resize(numDataArgs);
5782 CoveredArgs.reset();
5783 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005784
Ted Kremenek019d2242010-01-29 01:50:07 +00005785 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005786
Ted Kremenek02087932010-07-16 02:11:22 +00005787 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005788 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005789
Jordan Rose92303592012-09-08 04:00:03 +00005790 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005791 const analyze_format_string::FormatSpecifier &FS,
5792 const analyze_format_string::ConversionSpecifier &CS,
5793 const char *startSpecifier, unsigned specifierLen,
5794 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005795
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005796 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005797 const analyze_format_string::FormatSpecifier &FS,
5798 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005799
5800 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005801 const analyze_format_string::ConversionSpecifier &CS,
5802 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005803
Craig Toppere14c0f82014-03-12 04:55:44 +00005804 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005805
Craig Toppere14c0f82014-03-12 04:55:44 +00005806 void HandleInvalidPosition(const char *startSpecifier,
5807 unsigned specifierLen,
5808 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005809
Craig Toppere14c0f82014-03-12 04:55:44 +00005810 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005811
Craig Toppere14c0f82014-03-12 04:55:44 +00005812 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005813
Richard Trieu03cf7b72011-10-28 00:41:25 +00005814 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005815 static void
5816 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5817 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5818 bool IsStringLocation, Range StringRange,
5819 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005820
Ted Kremenek02087932010-07-16 02:11:22 +00005821protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005822 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5823 const char *startSpec,
5824 unsigned specifierLen,
5825 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005826
5827 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5828 const char *startSpec,
5829 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005830
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005831 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005832 CharSourceRange getSpecifierRange(const char *startSpecifier,
5833 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005834 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005835
Ted Kremenek5739de72010-01-29 01:06:55 +00005836 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005837
5838 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5839 const analyze_format_string::ConversionSpecifier &CS,
5840 const char *startSpecifier, unsigned specifierLen,
5841 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005842
5843 template <typename Range>
5844 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5845 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005846 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005847};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005848
5849} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005850
Ted Kremenek02087932010-07-16 02:11:22 +00005851SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005852 return OrigFormatExpr->getSourceRange();
5853}
5854
Ted Kremenek02087932010-07-16 02:11:22 +00005855CharSourceRange CheckFormatHandler::
5856getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005857 SourceLocation Start = getLocationOfByte(startSpecifier);
5858 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5859
5860 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005861 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005862
5863 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005864}
5865
Ted Kremenek02087932010-07-16 02:11:22 +00005866SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005867 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5868 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005869}
5870
Ted Kremenek02087932010-07-16 02:11:22 +00005871void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5872 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005873 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5874 getLocationOfByte(startSpecifier),
5875 /*IsStringLocation*/true,
5876 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005877}
5878
Jordan Rose92303592012-09-08 04:00:03 +00005879void CheckFormatHandler::HandleInvalidLengthModifier(
5880 const analyze_format_string::FormatSpecifier &FS,
5881 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005882 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005883 using namespace analyze_format_string;
5884
5885 const LengthModifier &LM = FS.getLengthModifier();
5886 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5887
5888 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005889 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005890 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005891 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005892 getLocationOfByte(LM.getStart()),
5893 /*IsStringLocation*/true,
5894 getSpecifierRange(startSpecifier, specifierLen));
5895
5896 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5897 << FixedLM->toString()
5898 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5899
5900 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005901 FixItHint Hint;
5902 if (DiagID == diag::warn_format_nonsensical_length)
5903 Hint = FixItHint::CreateRemoval(LMRange);
5904
5905 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005906 getLocationOfByte(LM.getStart()),
5907 /*IsStringLocation*/true,
5908 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005909 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005910 }
5911}
5912
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005913void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005914 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005915 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005916 using namespace analyze_format_string;
5917
5918 const LengthModifier &LM = FS.getLengthModifier();
5919 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5920
5921 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005922 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005923 if (FixedLM) {
5924 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5925 << LM.toString() << 0,
5926 getLocationOfByte(LM.getStart()),
5927 /*IsStringLocation*/true,
5928 getSpecifierRange(startSpecifier, specifierLen));
5929
5930 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5931 << FixedLM->toString()
5932 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5933
5934 } else {
5935 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5936 << LM.toString() << 0,
5937 getLocationOfByte(LM.getStart()),
5938 /*IsStringLocation*/true,
5939 getSpecifierRange(startSpecifier, specifierLen));
5940 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005941}
5942
5943void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5944 const analyze_format_string::ConversionSpecifier &CS,
5945 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005946 using namespace analyze_format_string;
5947
5948 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005949 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005950 if (FixedCS) {
5951 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5952 << CS.toString() << /*conversion specifier*/1,
5953 getLocationOfByte(CS.getStart()),
5954 /*IsStringLocation*/true,
5955 getSpecifierRange(startSpecifier, specifierLen));
5956
5957 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5958 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5959 << FixedCS->toString()
5960 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5961 } else {
5962 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5963 << CS.toString() << /*conversion specifier*/1,
5964 getLocationOfByte(CS.getStart()),
5965 /*IsStringLocation*/true,
5966 getSpecifierRange(startSpecifier, specifierLen));
5967 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005968}
5969
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005970void CheckFormatHandler::HandlePosition(const char *startPos,
5971 unsigned posLen) {
5972 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5973 getLocationOfByte(startPos),
5974 /*IsStringLocation*/true,
5975 getSpecifierRange(startPos, posLen));
5976}
5977
Ted Kremenekd1668192010-02-27 01:41:03 +00005978void
Ted Kremenek02087932010-07-16 02:11:22 +00005979CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5980 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005981 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5982 << (unsigned) p,
5983 getLocationOfByte(startPos), /*IsStringLocation*/true,
5984 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005985}
5986
Ted Kremenek02087932010-07-16 02:11:22 +00005987void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005988 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005989 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5990 getLocationOfByte(startPos),
5991 /*IsStringLocation*/true,
5992 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005993}
5994
Ted Kremenek02087932010-07-16 02:11:22 +00005995void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005996 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005997 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005998 EmitFormatDiagnostic(
5999 S.PDiag(diag::warn_printf_format_string_contains_null_char),
6000 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6001 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00006002 }
Ted Kremenek02087932010-07-16 02:11:22 +00006003}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006004
Jordan Rose58bbe422012-07-19 18:10:08 +00006005// Note that this may return NULL if there was an error parsing or building
6006// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00006007const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006008 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00006009}
6010
6011void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006012 // Does the number of data arguments exceed the number of
6013 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00006014 if (!HasVAListArg) {
6015 // Find any arguments that weren't covered.
6016 CoveredArgs.flip();
6017 signed notCoveredArg = CoveredArgs.find_first();
6018 if (notCoveredArg >= 0) {
6019 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006020 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6021 } else {
6022 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00006023 }
6024 }
6025}
6026
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006027void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6028 const Expr *ArgExpr) {
6029 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6030 "Invalid state");
6031
6032 if (!ArgExpr)
6033 return;
6034
6035 SourceLocation Loc = ArgExpr->getLocStart();
6036
6037 if (S.getSourceManager().isInSystemMacro(Loc))
6038 return;
6039
6040 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6041 for (auto E : DiagnosticExprs)
6042 PDiag << E->getSourceRange();
6043
6044 CheckFormatHandler::EmitFormatDiagnostic(
6045 S, IsFunctionCall, DiagnosticExprs[0],
6046 PDiag, Loc, /*IsStringLocation*/false,
6047 DiagnosticExprs[0]->getSourceRange());
6048}
6049
Ted Kremenekce815422010-07-19 21:25:57 +00006050bool
6051CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6052 SourceLocation Loc,
6053 const char *startSpec,
6054 unsigned specifierLen,
6055 const char *csStart,
6056 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00006057 bool keepGoing = true;
6058 if (argIndex < NumDataArgs) {
6059 // Consider the argument coverered, even though the specifier doesn't
6060 // make sense.
6061 CoveredArgs.set(argIndex);
6062 }
6063 else {
6064 // If argIndex exceeds the number of data arguments we
6065 // don't issue a warning because that is just a cascade of warnings (and
6066 // they may have intended '%%' anyway). We don't want to continue processing
6067 // the format string after this point, however, as we will like just get
6068 // gibberish when trying to match arguments.
6069 keepGoing = false;
6070 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006071
6072 StringRef Specifier(csStart, csLen);
6073
6074 // If the specifier in non-printable, it could be the first byte of a UTF-8
6075 // sequence. In that case, print the UTF-8 code point. If not, print the byte
6076 // hex value.
6077 std::string CodePointStr;
6078 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00006079 llvm::UTF32 CodePoint;
6080 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6081 const llvm::UTF8 *E =
6082 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6083 llvm::ConversionResult Result =
6084 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006085
Justin Lebar90910552016-09-30 00:38:45 +00006086 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006087 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00006088 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00006089 }
6090
6091 llvm::raw_string_ostream OS(CodePointStr);
6092 if (CodePoint < 256)
6093 OS << "\\x" << llvm::format("%02x", CodePoint);
6094 else if (CodePoint <= 0xFFFF)
6095 OS << "\\u" << llvm::format("%04x", CodePoint);
6096 else
6097 OS << "\\U" << llvm::format("%08x", CodePoint);
6098 OS.flush();
6099 Specifier = CodePointStr;
6100 }
6101
6102 EmitFormatDiagnostic(
6103 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6104 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6105
Ted Kremenekce815422010-07-19 21:25:57 +00006106 return keepGoing;
6107}
6108
Richard Trieu03cf7b72011-10-28 00:41:25 +00006109void
6110CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6111 const char *startSpec,
6112 unsigned specifierLen) {
6113 EmitFormatDiagnostic(
6114 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6115 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6116}
6117
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006118bool
6119CheckFormatHandler::CheckNumArgs(
6120 const analyze_format_string::FormatSpecifier &FS,
6121 const analyze_format_string::ConversionSpecifier &CS,
6122 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6123
6124 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006125 PartialDiagnostic PDiag = FS.usesPositionalArg()
6126 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6127 << (argIndex+1) << NumDataArgs)
6128 : S.PDiag(diag::warn_printf_insufficient_data_args);
6129 EmitFormatDiagnostic(
6130 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6131 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006132
6133 // Since more arguments than conversion tokens are given, by extension
6134 // all arguments are covered, so mark this as so.
6135 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006136 return false;
6137 }
6138 return true;
6139}
6140
Richard Trieu03cf7b72011-10-28 00:41:25 +00006141template<typename Range>
6142void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6143 SourceLocation Loc,
6144 bool IsStringLocation,
6145 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00006146 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00006147 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00006148 Loc, IsStringLocation, StringRange, FixIt);
6149}
6150
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006151/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00006152/// so that the function call and string are in diagnostic messages.
6153///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006154/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00006155/// call and only one diagnostic message will be produced. Otherwise, an
6156/// extra note will be emitted pointing to location of the format string.
6157///
6158/// \param ArgumentExpr the expression that is passed as the format string
6159/// argument in the function call. Used for getting locations when two
6160/// diagnostics are emitted.
6161///
6162/// \param PDiag the callee should already have provided any strings for the
6163/// diagnostic message. This function only adds locations and fixits
6164/// to diagnostics.
6165///
6166/// \param Loc primary location for diagnostic. If two diagnostics are
6167/// required, one will be at Loc and a new SourceLocation will be created for
6168/// the other one.
6169///
6170/// \param IsStringLocation if true, Loc points to the format string should be
6171/// used for the note. Otherwise, Loc points to the argument list and will
6172/// be used with PDiag.
6173///
6174/// \param StringRange some or all of the string to highlight. This is
6175/// templated so it can accept either a CharSourceRange or a SourceRange.
6176///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00006177/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00006178template <typename Range>
6179void CheckFormatHandler::EmitFormatDiagnostic(
6180 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
6181 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
6182 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00006183 if (InFunctionCall) {
6184 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
6185 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006186 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00006187 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006188 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
6189 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00006190
6191 const Sema::SemaDiagnosticBuilder &Note =
6192 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
6193 diag::note_format_string_defined);
6194
6195 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00006196 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00006197 }
6198}
6199
Ted Kremenek02087932010-07-16 02:11:22 +00006200//===--- CHECK: Printf format string checking ------------------------------===//
6201
6202namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006203
Ted Kremenek02087932010-07-16 02:11:22 +00006204class CheckPrintfHandler : public CheckFormatHandler {
6205public:
Stephen Hines648c3692016-09-16 01:07:04 +00006206 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006207 const Expr *origFormatExpr,
6208 const Sema::FormatStringType type, unsigned firstDataArg,
6209 unsigned numDataArgs, bool isObjC, const char *beg,
6210 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006211 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006212 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006213 llvm::SmallBitVector &CheckedVarArgs,
6214 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006215 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6216 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6217 inFunctionCall, CallType, CheckedVarArgs,
6218 UncoveredArg) {}
6219
6220 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6221
6222 /// Returns true if '%@' specifiers are allowed in the format string.
6223 bool allowsObjCArg() const {
6224 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6225 FSType == Sema::FST_OSTrace;
6226 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006227
Ted Kremenek02087932010-07-16 02:11:22 +00006228 bool HandleInvalidPrintfConversionSpecifier(
6229 const analyze_printf::PrintfSpecifier &FS,
6230 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006231 unsigned specifierLen) override;
6232
Ted Kremenek02087932010-07-16 02:11:22 +00006233 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6234 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006235 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006236 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6237 const char *StartSpecifier,
6238 unsigned SpecifierLen,
6239 const Expr *E);
6240
Ted Kremenek02087932010-07-16 02:11:22 +00006241 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6242 const char *startSpecifier, unsigned specifierLen);
6243 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6244 const analyze_printf::OptionalAmount &Amt,
6245 unsigned type,
6246 const char *startSpecifier, unsigned specifierLen);
6247 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6248 const analyze_printf::OptionalFlag &flag,
6249 const char *startSpecifier, unsigned specifierLen);
6250 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6251 const analyze_printf::OptionalFlag &ignoredFlag,
6252 const analyze_printf::OptionalFlag &flag,
6253 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006254 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006255 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006256
6257 void HandleEmptyObjCModifierFlag(const char *startFlag,
6258 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006259
Ted Kremenek2b417712015-07-02 05:39:16 +00006260 void HandleInvalidObjCModifierFlag(const char *startFlag,
6261 unsigned flagLen) override;
6262
6263 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6264 const char *flagsEnd,
6265 const char *conversionPosition)
6266 override;
6267};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006268
6269} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006270
6271bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6272 const analyze_printf::PrintfSpecifier &FS,
6273 const char *startSpecifier,
6274 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006275 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006276 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006277
Ted Kremenekce815422010-07-19 21:25:57 +00006278 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6279 getLocationOfByte(CS.getStart()),
6280 startSpecifier, specifierLen,
6281 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006282}
6283
Ted Kremenek02087932010-07-16 02:11:22 +00006284bool CheckPrintfHandler::HandleAmount(
6285 const analyze_format_string::OptionalAmount &Amt,
6286 unsigned k, const char *startSpecifier,
6287 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006288 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006289 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006290 unsigned argIndex = Amt.getArgIndex();
6291 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006292 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6293 << k,
6294 getLocationOfByte(Amt.getStart()),
6295 /*IsStringLocation*/true,
6296 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006297 // Don't do any more checking. We will just emit
6298 // spurious errors.
6299 return false;
6300 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006301
Ted Kremenek5739de72010-01-29 01:06:55 +00006302 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006303 // Although not in conformance with C99, we also allow the argument to be
6304 // an 'unsigned int' as that is a reasonably safe case. GCC also
6305 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006306 CoveredArgs.set(argIndex);
6307 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006308 if (!Arg)
6309 return false;
6310
Ted Kremenek5739de72010-01-29 01:06:55 +00006311 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006312
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006313 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6314 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006315
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006316 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006317 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006318 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006319 << T << Arg->getSourceRange(),
6320 getLocationOfByte(Amt.getStart()),
6321 /*IsStringLocation*/true,
6322 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006323 // Don't do any more checking. We will just emit
6324 // spurious errors.
6325 return false;
6326 }
6327 }
6328 }
6329 return true;
6330}
Ted Kremenek5739de72010-01-29 01:06:55 +00006331
Tom Careb49ec692010-06-17 19:00:27 +00006332void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006333 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006334 const analyze_printf::OptionalAmount &Amt,
6335 unsigned type,
6336 const char *startSpecifier,
6337 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006338 const analyze_printf::PrintfConversionSpecifier &CS =
6339 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006340
Richard Trieu03cf7b72011-10-28 00:41:25 +00006341 FixItHint fixit =
6342 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6343 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6344 Amt.getConstantLength()))
6345 : FixItHint();
6346
6347 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6348 << type << CS.toString(),
6349 getLocationOfByte(Amt.getStart()),
6350 /*IsStringLocation*/true,
6351 getSpecifierRange(startSpecifier, specifierLen),
6352 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006353}
6354
Ted Kremenek02087932010-07-16 02:11:22 +00006355void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006356 const analyze_printf::OptionalFlag &flag,
6357 const char *startSpecifier,
6358 unsigned specifierLen) {
6359 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006360 const analyze_printf::PrintfConversionSpecifier &CS =
6361 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006362 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6363 << flag.toString() << CS.toString(),
6364 getLocationOfByte(flag.getPosition()),
6365 /*IsStringLocation*/true,
6366 getSpecifierRange(startSpecifier, specifierLen),
6367 FixItHint::CreateRemoval(
6368 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006369}
6370
6371void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006372 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006373 const analyze_printf::OptionalFlag &ignoredFlag,
6374 const analyze_printf::OptionalFlag &flag,
6375 const char *startSpecifier,
6376 unsigned specifierLen) {
6377 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006378 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6379 << ignoredFlag.toString() << flag.toString(),
6380 getLocationOfByte(ignoredFlag.getPosition()),
6381 /*IsStringLocation*/true,
6382 getSpecifierRange(startSpecifier, specifierLen),
6383 FixItHint::CreateRemoval(
6384 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006385}
6386
Ted Kremenek2b417712015-07-02 05:39:16 +00006387void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6388 unsigned flagLen) {
6389 // Warn about an empty flag.
6390 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6391 getLocationOfByte(startFlag),
6392 /*IsStringLocation*/true,
6393 getSpecifierRange(startFlag, flagLen));
6394}
6395
6396void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6397 unsigned flagLen) {
6398 // Warn about an invalid flag.
6399 auto Range = getSpecifierRange(startFlag, flagLen);
6400 StringRef flag(startFlag, flagLen);
6401 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6402 getLocationOfByte(startFlag),
6403 /*IsStringLocation*/true,
6404 Range, FixItHint::CreateRemoval(Range));
6405}
6406
6407void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6408 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6409 // Warn about using '[...]' without a '@' conversion.
6410 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6411 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6412 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6413 getLocationOfByte(conversionPosition),
6414 /*IsStringLocation*/true,
6415 Range, FixItHint::CreateRemoval(Range));
6416}
6417
Richard Smith55ce3522012-06-25 20:30:08 +00006418// Determines if the specified is a C++ class or struct containing
6419// a member with the specified name and kind (e.g. a CXXMethodDecl named
6420// "c_str()").
6421template<typename MemberKind>
6422static llvm::SmallPtrSet<MemberKind*, 1>
6423CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6424 const RecordType *RT = Ty->getAs<RecordType>();
6425 llvm::SmallPtrSet<MemberKind*, 1> Results;
6426
6427 if (!RT)
6428 return Results;
6429 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006430 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006431 return Results;
6432
Alp Tokerb6cc5922014-05-03 03:45:55 +00006433 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006434 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006435 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006436
6437 // We just need to include all members of the right kind turned up by the
6438 // filter, at this point.
6439 if (S.LookupQualifiedName(R, RT->getDecl()))
6440 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6441 NamedDecl *decl = (*I)->getUnderlyingDecl();
6442 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6443 Results.insert(FK);
6444 }
6445 return Results;
6446}
6447
Richard Smith2868a732014-02-28 01:36:39 +00006448/// Check if we could call '.c_str()' on an object.
6449///
6450/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6451/// allow the call, or if it would be ambiguous).
6452bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006453 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6454
Richard Smith2868a732014-02-28 01:36:39 +00006455 MethodSet Results =
6456 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6457 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6458 MI != ME; ++MI)
6459 if ((*MI)->getMinRequiredArguments() == 0)
6460 return true;
6461 return false;
6462}
6463
Richard Smith55ce3522012-06-25 20:30:08 +00006464// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006465// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006466// Returns true when a c_str() conversion method is found.
6467bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006468 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006469 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006470
6471 MethodSet Results =
6472 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6473
6474 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6475 MI != ME; ++MI) {
6476 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006477 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006478 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006479 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006480 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006481 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6482 << "c_str()"
6483 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6484 return true;
6485 }
6486 }
6487
6488 return false;
6489}
6490
Ted Kremenekab278de2010-01-28 23:39:18 +00006491bool
Ted Kremenek02087932010-07-16 02:11:22 +00006492CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006493 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006494 const char *startSpecifier,
6495 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006496 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006497 using namespace analyze_printf;
6498
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006499 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006500
Ted Kremenek6cd69422010-07-19 22:01:06 +00006501 if (FS.consumesDataArgument()) {
6502 if (atFirstArg) {
6503 atFirstArg = false;
6504 usesPositionalArgs = FS.usesPositionalArg();
6505 }
6506 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006507 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6508 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006509 return false;
6510 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006511 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006512
Ted Kremenekd1668192010-02-27 01:41:03 +00006513 // First check if the field width, precision, and conversion specifier
6514 // have matching data arguments.
6515 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6516 startSpecifier, specifierLen)) {
6517 return false;
6518 }
6519
6520 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6521 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006522 return false;
6523 }
6524
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006525 if (!CS.consumesDataArgument()) {
6526 // FIXME: Technically specifying a precision or field width here
6527 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006528 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006529 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006530
Ted Kremenek4a49d982010-02-26 19:18:41 +00006531 // Consume the argument.
6532 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006533 if (argIndex < NumDataArgs) {
6534 // The check to see if the argIndex is valid will come later.
6535 // We set the bit here because we may exit early from this
6536 // function if we encounter some other error.
6537 CoveredArgs.set(argIndex);
6538 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006539
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006540 // FreeBSD kernel extensions.
6541 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6542 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6543 // We need at least two arguments.
6544 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6545 return false;
6546
6547 // Claim the second argument.
6548 CoveredArgs.set(argIndex + 1);
6549
6550 // Type check the first argument (int for %b, pointer for %D)
6551 const Expr *Ex = getDataArg(argIndex);
6552 const analyze_printf::ArgType &AT =
6553 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6554 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6555 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6556 EmitFormatDiagnostic(
6557 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6558 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6559 << false << Ex->getSourceRange(),
6560 Ex->getLocStart(), /*IsStringLocation*/false,
6561 getSpecifierRange(startSpecifier, specifierLen));
6562
6563 // Type check the second argument (char * for both %b and %D)
6564 Ex = getDataArg(argIndex + 1);
6565 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6566 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6567 EmitFormatDiagnostic(
6568 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6569 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6570 << false << Ex->getSourceRange(),
6571 Ex->getLocStart(), /*IsStringLocation*/false,
6572 getSpecifierRange(startSpecifier, specifierLen));
6573
6574 return true;
6575 }
6576
Ted Kremenek4a49d982010-02-26 19:18:41 +00006577 // Check for using an Objective-C specific conversion specifier
6578 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006579 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006580 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6581 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006582 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006583
Mehdi Amini06d367c2016-10-24 20:39:34 +00006584 // %P can only be used with os_log.
6585 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6586 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6587 specifierLen);
6588 }
6589
6590 // %n is not allowed with os_log.
6591 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6592 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6593 getLocationOfByte(CS.getStart()),
6594 /*IsStringLocation*/ false,
6595 getSpecifierRange(startSpecifier, specifierLen));
6596
6597 return true;
6598 }
6599
6600 // Only scalars are allowed for os_trace.
6601 if (FSType == Sema::FST_OSTrace &&
6602 (CS.getKind() == ConversionSpecifier::PArg ||
6603 CS.getKind() == ConversionSpecifier::sArg ||
6604 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6605 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6606 specifierLen);
6607 }
6608
6609 // Check for use of public/private annotation outside of os_log().
6610 if (FSType != Sema::FST_OSLog) {
6611 if (FS.isPublic().isSet()) {
6612 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6613 << "public",
6614 getLocationOfByte(FS.isPublic().getPosition()),
6615 /*IsStringLocation*/ false,
6616 getSpecifierRange(startSpecifier, specifierLen));
6617 }
6618 if (FS.isPrivate().isSet()) {
6619 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6620 << "private",
6621 getLocationOfByte(FS.isPrivate().getPosition()),
6622 /*IsStringLocation*/ false,
6623 getSpecifierRange(startSpecifier, specifierLen));
6624 }
6625 }
6626
Tom Careb49ec692010-06-17 19:00:27 +00006627 // Check for invalid use of field width
6628 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006629 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006630 startSpecifier, specifierLen);
6631 }
6632
6633 // Check for invalid use of precision
6634 if (!FS.hasValidPrecision()) {
6635 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6636 startSpecifier, specifierLen);
6637 }
6638
Mehdi Amini06d367c2016-10-24 20:39:34 +00006639 // Precision is mandatory for %P specifier.
6640 if (CS.getKind() == ConversionSpecifier::PArg &&
6641 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6642 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6643 getLocationOfByte(startSpecifier),
6644 /*IsStringLocation*/ false,
6645 getSpecifierRange(startSpecifier, specifierLen));
6646 }
6647
Tom Careb49ec692010-06-17 19:00:27 +00006648 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006649 if (!FS.hasValidThousandsGroupingPrefix())
6650 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006651 if (!FS.hasValidLeadingZeros())
6652 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6653 if (!FS.hasValidPlusPrefix())
6654 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006655 if (!FS.hasValidSpacePrefix())
6656 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006657 if (!FS.hasValidAlternativeForm())
6658 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6659 if (!FS.hasValidLeftJustified())
6660 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6661
6662 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006663 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6664 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6665 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006666 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6667 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6668 startSpecifier, specifierLen);
6669
6670 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006671 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006672 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6673 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006674 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006675 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006676 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006677 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6678 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006679
Jordan Rose92303592012-09-08 04:00:03 +00006680 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6681 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6682
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006683 // The remaining checks depend on the data arguments.
6684 if (HasVAListArg)
6685 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006686
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006687 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006688 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006689
Jordan Rose58bbe422012-07-19 18:10:08 +00006690 const Expr *Arg = getDataArg(argIndex);
6691 if (!Arg)
6692 return true;
6693
6694 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006695}
6696
Jordan Roseaee34382012-09-05 22:56:26 +00006697static bool requiresParensToAddCast(const Expr *E) {
6698 // FIXME: We should have a general way to reason about operator
6699 // precedence and whether parens are actually needed here.
6700 // Take care of a few common cases where they aren't.
6701 const Expr *Inside = E->IgnoreImpCasts();
6702 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6703 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6704
6705 switch (Inside->getStmtClass()) {
6706 case Stmt::ArraySubscriptExprClass:
6707 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006708 case Stmt::CharacterLiteralClass:
6709 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006710 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006711 case Stmt::FloatingLiteralClass:
6712 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006713 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006714 case Stmt::ObjCArrayLiteralClass:
6715 case Stmt::ObjCBoolLiteralExprClass:
6716 case Stmt::ObjCBoxedExprClass:
6717 case Stmt::ObjCDictionaryLiteralClass:
6718 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006719 case Stmt::ObjCIvarRefExprClass:
6720 case Stmt::ObjCMessageExprClass:
6721 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006722 case Stmt::ObjCStringLiteralClass:
6723 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006724 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006725 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006726 case Stmt::UnaryOperatorClass:
6727 return false;
6728 default:
6729 return true;
6730 }
6731}
6732
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006733static std::pair<QualType, StringRef>
6734shouldNotPrintDirectly(const ASTContext &Context,
6735 QualType IntendedTy,
6736 const Expr *E) {
6737 // Use a 'while' to peel off layers of typedefs.
6738 QualType TyTy = IntendedTy;
6739 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6740 StringRef Name = UserTy->getDecl()->getName();
6741 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006742 .Case("CFIndex", Context.getNSIntegerType())
6743 .Case("NSInteger", Context.getNSIntegerType())
6744 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006745 .Case("SInt32", Context.IntTy)
6746 .Case("UInt32", Context.UnsignedIntTy)
6747 .Default(QualType());
6748
6749 if (!CastTy.isNull())
6750 return std::make_pair(CastTy, Name);
6751
6752 TyTy = UserTy->desugar();
6753 }
6754
6755 // Strip parens if necessary.
6756 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6757 return shouldNotPrintDirectly(Context,
6758 PE->getSubExpr()->getType(),
6759 PE->getSubExpr());
6760
6761 // If this is a conditional expression, then its result type is constructed
6762 // via usual arithmetic conversions and thus there might be no necessary
6763 // typedef sugar there. Recurse to operands to check for NSInteger &
6764 // Co. usage condition.
6765 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6766 QualType TrueTy, FalseTy;
6767 StringRef TrueName, FalseName;
6768
6769 std::tie(TrueTy, TrueName) =
6770 shouldNotPrintDirectly(Context,
6771 CO->getTrueExpr()->getType(),
6772 CO->getTrueExpr());
6773 std::tie(FalseTy, FalseName) =
6774 shouldNotPrintDirectly(Context,
6775 CO->getFalseExpr()->getType(),
6776 CO->getFalseExpr());
6777
6778 if (TrueTy == FalseTy)
6779 return std::make_pair(TrueTy, TrueName);
6780 else if (TrueTy.isNull())
6781 return std::make_pair(FalseTy, FalseName);
6782 else if (FalseTy.isNull())
6783 return std::make_pair(TrueTy, TrueName);
6784 }
6785
6786 return std::make_pair(QualType(), StringRef());
6787}
6788
Richard Smith55ce3522012-06-25 20:30:08 +00006789bool
6790CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6791 const char *StartSpecifier,
6792 unsigned SpecifierLen,
6793 const Expr *E) {
6794 using namespace analyze_format_string;
6795 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006796
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006797 // Now type check the data expression that matches the
6798 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006799 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006800 if (!AT.isValid())
6801 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006802
Jordan Rose598ec092012-12-05 18:44:40 +00006803 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006804 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6805 ExprTy = TET->getUnderlyingExpr()->getType();
6806 }
6807
JF Bastienec7d7f32018-06-22 21:54:40 +00006808 const analyze_printf::ArgType::MatchKind Match =
6809 AT.matchesType(S.Context, ExprTy);
6810 bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
6811 if (Match == analyze_printf::ArgType::Match)
Jordan Rose22b74712012-09-05 22:56:19 +00006812 return true;
Jordan Rose98709982012-06-04 22:48:57 +00006813
Jordan Rose22b74712012-09-05 22:56:19 +00006814 // Look through argument promotions for our error message's reported type.
6815 // This includes the integral and floating promotions, but excludes array
6816 // and function pointer decay; seeing that an argument intended to be a
6817 // string has type 'char [6]' is probably more confusing than 'char *'.
6818 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6819 if (ICE->getCastKind() == CK_IntegralCast ||
6820 ICE->getCastKind() == CK_FloatingCast) {
6821 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006822 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006823
6824 // Check if we didn't match because of an implicit cast from a 'char'
6825 // or 'short' to an 'int'. This is done because printf is a varargs
6826 // function.
6827 if (ICE->getType() == S.Context.IntTy ||
6828 ICE->getType() == S.Context.UnsignedIntTy) {
6829 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006830 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006831 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006832 }
Jordan Rose98709982012-06-04 22:48:57 +00006833 }
Jordan Rose598ec092012-12-05 18:44:40 +00006834 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6835 // Special case for 'a', which has type 'int' in C.
6836 // Note, however, that we do /not/ want to treat multibyte constants like
6837 // 'MooV' as characters! This form is deprecated but still exists.
6838 if (ExprTy == S.Context.IntTy)
6839 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6840 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006841 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006842
Jordan Rosebc53ed12014-05-31 04:12:14 +00006843 // Look through enums to their underlying type.
6844 bool IsEnum = false;
6845 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6846 ExprTy = EnumTy->getDecl()->getIntegerType();
6847 IsEnum = true;
6848 }
6849
Jordan Rose0e5badd2012-12-05 18:44:49 +00006850 // %C in an Objective-C context prints a unichar, not a wchar_t.
6851 // If the argument is an integer of some kind, believe the %C and suggest
6852 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006853 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006854 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006855 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6856 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6857 !ExprTy->isCharType()) {
6858 // 'unichar' is defined as a typedef of unsigned short, but we should
6859 // prefer using the typedef if it is visible.
6860 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006861
6862 // While we are here, check if the value is an IntegerLiteral that happens
6863 // to be within the valid range.
6864 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6865 const llvm::APInt &V = IL->getValue();
6866 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6867 return true;
6868 }
6869
Jordan Rose0e5badd2012-12-05 18:44:49 +00006870 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6871 Sema::LookupOrdinaryName);
6872 if (S.LookupName(Result, S.getCurScope())) {
6873 NamedDecl *ND = Result.getFoundDecl();
6874 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6875 if (TD->getUnderlyingType() == IntendedTy)
6876 IntendedTy = S.Context.getTypedefType(TD);
6877 }
6878 }
6879 }
6880
6881 // Special-case some of Darwin's platform-independence types by suggesting
6882 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006883 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006884 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006885 QualType CastTy;
6886 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6887 if (!CastTy.isNull()) {
JF Bastienec7d7f32018-06-22 21:54:40 +00006888 // %zi/%zu are OK to use for NSInteger/NSUInteger of type int
6889 // (long in ASTContext). Only complain to pedants.
6890 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
6891 AT.isSizeT() && AT.matchesType(S.Context, CastTy))
6892 Pedantic = true;
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006893 IntendedTy = CastTy;
6894 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006895 }
6896 }
6897
Jordan Rose22b74712012-09-05 22:56:19 +00006898 // We may be able to offer a FixItHint if it is a supported type.
6899 PrintfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00006900 bool Success =
Mehdi Amini06d367c2016-10-24 20:39:34 +00006901 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006902
JF Bastienec7d7f32018-06-22 21:54:40 +00006903 if (Success) {
Jordan Rose22b74712012-09-05 22:56:19 +00006904 // Get the fix string from the fixed format specifier
6905 SmallString<16> buf;
6906 llvm::raw_svector_ostream os(buf);
6907 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006908
Jordan Roseaee34382012-09-05 22:56:26 +00006909 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6910
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006911 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
JF Bastienec7d7f32018-06-22 21:54:40 +00006912 unsigned Diag =
6913 Pedantic
6914 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
6915 : diag::warn_format_conversion_argument_type_mismatch;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006916 // In this case, the specifier is wrong and should be changed to match
6917 // the argument.
JF Bastienec7d7f32018-06-22 21:54:40 +00006918 EmitFormatDiagnostic(S.PDiag(Diag)
Daniel Jasperad8d8492015-03-04 14:18:20 +00006919 << AT.getRepresentativeTypeName(S.Context)
6920 << IntendedTy << IsEnum << E->getSourceRange(),
6921 E->getLocStart(),
6922 /*IsStringLocation*/ false, SpecRange,
6923 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006924 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006925 // The canonical type for formatting this value is different from the
6926 // actual type of the expression. (This occurs, for example, with Darwin's
6927 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6928 // should be printed as 'long' for 64-bit compatibility.)
6929 // Rather than emitting a normal format/argument mismatch, we want to
6930 // add a cast to the recommended type (and correct the format string
6931 // if necessary).
6932 SmallString<16> CastBuf;
6933 llvm::raw_svector_ostream CastFix(CastBuf);
6934 CastFix << "(";
6935 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6936 CastFix << ")";
6937
6938 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006939 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006940 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6941
6942 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6943 // If there's already a cast present, just replace it.
6944 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6945 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6946
6947 } else if (!requiresParensToAddCast(E)) {
6948 // If the expression has high enough precedence,
6949 // just write the C-style cast.
6950 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6951 CastFix.str()));
6952 } else {
6953 // Otherwise, add parens around the expression as well as the cast.
6954 CastFix << "(";
6955 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6956 CastFix.str()));
6957
Alp Tokerb6cc5922014-05-03 03:45:55 +00006958 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006959 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6960 }
6961
Jordan Rose0e5badd2012-12-05 18:44:49 +00006962 if (ShouldNotPrintDirectly) {
6963 // The expression has a type that should not be printed directly.
6964 // We extract the name from the typedef because we don't want to show
6965 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006966 StringRef Name;
6967 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6968 Name = TypedefTy->getDecl()->getName();
6969 else
6970 Name = CastTyName;
JF Bastienec7d7f32018-06-22 21:54:40 +00006971 unsigned Diag = Pedantic
6972 ? diag::warn_format_argument_needs_cast_pedantic
6973 : diag::warn_format_argument_needs_cast;
6974 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
6975 << E->getSourceRange(),
Jordan Rose0e5badd2012-12-05 18:44:49 +00006976 E->getLocStart(), /*IsStringLocation=*/false,
6977 SpecRange, Hints);
6978 } else {
6979 // In this case, the expression could be printed using a different
6980 // specifier, but we've decided that the specifier is probably correct
6981 // and we should cast instead. Just use the normal warning message.
6982 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006983 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6984 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006985 << E->getSourceRange(),
6986 E->getLocStart(), /*IsStringLocation*/false,
6987 SpecRange, Hints);
6988 }
Jordan Roseaee34382012-09-05 22:56:26 +00006989 }
Jordan Rose22b74712012-09-05 22:56:19 +00006990 } else {
6991 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6992 SpecifierLen);
6993 // Since the warning for passing non-POD types to variadic functions
6994 // was deferred until now, we emit a warning for non-POD
6995 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006996 switch (S.isValidVarArgType(ExprTy)) {
6997 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006998 case Sema::VAK_ValidInCXX11: {
JF Bastienec7d7f32018-06-22 21:54:40 +00006999 unsigned Diag =
7000 Pedantic
7001 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7002 : diag::warn_format_conversion_argument_type_mismatch;
Richard Smithd7293d72013-08-05 18:49:43 +00007003
Seth Cantrellb4802962015-03-04 03:12:10 +00007004 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00007005 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
Seth Cantrellb4802962015-03-04 03:12:10 +00007006 << IsEnum << CSR << E->getSourceRange(),
7007 E->getLocStart(), /*IsStringLocation*/ false, CSR);
7008 break;
7009 }
Richard Smithd7293d72013-08-05 18:49:43 +00007010 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00007011 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00007012 EmitFormatDiagnostic(
7013 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007014 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00007015 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00007016 << CallType
7017 << AT.getRepresentativeTypeName(S.Context)
7018 << CSR
7019 << E->getSourceRange(),
7020 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00007021 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00007022 break;
7023
7024 case Sema::VAK_Invalid:
7025 if (ExprTy->isObjCObjectType())
7026 EmitFormatDiagnostic(
7027 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7028 << S.getLangOpts().CPlusPlus11
7029 << ExprTy
7030 << CallType
7031 << AT.getRepresentativeTypeName(S.Context)
7032 << CSR
7033 << E->getSourceRange(),
7034 E->getLocStart(), /*IsStringLocation*/false, CSR);
7035 else
7036 // FIXME: If this is an initializer list, suggest removing the braces
7037 // or inserting a cast to the target type.
7038 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
7039 << isa<InitListExpr>(E) << ExprTy << CallType
7040 << AT.getRepresentativeTypeName(S.Context)
7041 << E->getSourceRange();
7042 break;
7043 }
7044
7045 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7046 "format string specifier index out of range");
7047 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00007048 }
7049
Ted Kremenekab278de2010-01-28 23:39:18 +00007050 return true;
7051}
7052
Ted Kremenek02087932010-07-16 02:11:22 +00007053//===--- CHECK: Scanf format string checking ------------------------------===//
7054
7055namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007056
Ted Kremenek02087932010-07-16 02:11:22 +00007057class CheckScanfHandler : public CheckFormatHandler {
7058public:
Stephen Hines648c3692016-09-16 01:07:04 +00007059 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00007060 const Expr *origFormatExpr, Sema::FormatStringType type,
7061 unsigned firstDataArg, unsigned numDataArgs,
7062 const char *beg, bool hasVAListArg,
7063 ArrayRef<const Expr *> Args, unsigned formatIdx,
7064 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007065 llvm::SmallBitVector &CheckedVarArgs,
7066 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00007067 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7068 numDataArgs, beg, hasVAListArg, Args, formatIdx,
7069 inFunctionCall, CallType, CheckedVarArgs,
7070 UncoveredArg) {}
7071
Ted Kremenek02087932010-07-16 02:11:22 +00007072 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7073 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007074 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00007075
7076 bool HandleInvalidScanfConversionSpecifier(
7077 const analyze_scanf::ScanfSpecifier &FS,
7078 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00007079 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007080
Craig Toppere14c0f82014-03-12 04:55:44 +00007081 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00007082};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007083
7084} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00007085
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007086void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7087 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007088 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7089 getLocationOfByte(end), /*IsStringLocation*/true,
7090 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00007091}
7092
Ted Kremenekce815422010-07-19 21:25:57 +00007093bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7094 const analyze_scanf::ScanfSpecifier &FS,
7095 const char *startSpecifier,
7096 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007097 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00007098 FS.getConversionSpecifier();
7099
7100 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7101 getLocationOfByte(CS.getStart()),
7102 startSpecifier, specifierLen,
7103 CS.getStart(), CS.getLength());
7104}
7105
Ted Kremenek02087932010-07-16 02:11:22 +00007106bool CheckScanfHandler::HandleScanfSpecifier(
7107 const analyze_scanf::ScanfSpecifier &FS,
7108 const char *startSpecifier,
7109 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00007110 using namespace analyze_scanf;
7111 using namespace analyze_format_string;
7112
Ted Kremenekf03e6d852010-07-20 20:04:27 +00007113 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00007114
Ted Kremenek6cd69422010-07-19 22:01:06 +00007115 // Handle case where '%' and '*' don't consume an argument. These shouldn't
7116 // be used to decide if we are using positional arguments consistently.
7117 if (FS.consumesDataArgument()) {
7118 if (atFirstArg) {
7119 atFirstArg = false;
7120 usesPositionalArgs = FS.usesPositionalArg();
7121 }
7122 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007123 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7124 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00007125 return false;
7126 }
Ted Kremenek02087932010-07-16 02:11:22 +00007127 }
7128
7129 // Check if the field with is non-zero.
7130 const OptionalAmount &Amt = FS.getFieldWidth();
7131 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7132 if (Amt.getConstantAmount() == 0) {
7133 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7134 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00007135 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7136 getLocationOfByte(Amt.getStart()),
7137 /*IsStringLocation*/true, R,
7138 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00007139 }
7140 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007141
Ted Kremenek02087932010-07-16 02:11:22 +00007142 if (!FS.consumesDataArgument()) {
7143 // FIXME: Technically specifying a precision or field width here
7144 // makes no sense. Worth issuing a warning at some point.
7145 return true;
7146 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007147
Ted Kremenek02087932010-07-16 02:11:22 +00007148 // Consume the argument.
7149 unsigned argIndex = FS.getArgIndex();
7150 if (argIndex < NumDataArgs) {
7151 // The check to see if the argIndex is valid will come later.
7152 // We set the bit here because we may exit early from this
7153 // function if we encounter some other error.
7154 CoveredArgs.set(argIndex);
7155 }
Seth Cantrellb4802962015-03-04 03:12:10 +00007156
Ted Kremenek4407ea42010-07-20 20:04:47 +00007157 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00007158 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00007159 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7160 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00007161 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007162 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00007163 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00007164 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7165 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00007166
Jordan Rose92303592012-09-08 04:00:03 +00007167 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7168 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7169
Ted Kremenek02087932010-07-16 02:11:22 +00007170 // The remaining checks depend on the data arguments.
7171 if (HasVAListArg)
7172 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00007173
Ted Kremenek6adb7e32010-07-26 19:45:42 +00007174 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00007175 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00007176
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007177 // Check that the argument type matches the format specifier.
7178 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00007179 if (!Ex)
7180 return true;
7181
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00007182 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00007183
7184 if (!AT.isValid()) {
7185 return true;
7186 }
7187
JF Bastienec7d7f32018-06-22 21:54:40 +00007188 analyze_format_string::ArgType::MatchKind Match =
Seth Cantrellb4802962015-03-04 03:12:10 +00007189 AT.matchesType(S.Context, Ex->getType());
JF Bastienec7d7f32018-06-22 21:54:40 +00007190 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
7191 if (Match == analyze_format_string::ArgType::Match)
Seth Cantrell79340072015-03-04 05:58:08 +00007192 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00007193
Seth Cantrell79340072015-03-04 05:58:08 +00007194 ScanfSpecifier fixedFS = FS;
JF Bastienec7d7f32018-06-22 21:54:40 +00007195 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
Seth Cantrell79340072015-03-04 05:58:08 +00007196 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007197
JF Bastienec7d7f32018-06-22 21:54:40 +00007198 unsigned Diag =
7199 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7200 : diag::warn_format_conversion_argument_type_mismatch;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007201
JF Bastienec7d7f32018-06-22 21:54:40 +00007202 if (Success) {
Seth Cantrell79340072015-03-04 05:58:08 +00007203 // Get the fix string from the fixed format specifier.
7204 SmallString<128> buf;
7205 llvm::raw_svector_ostream os(buf);
7206 fixedFS.toString(os);
7207
7208 EmitFormatDiagnostic(
JF Bastienec7d7f32018-06-22 21:54:40 +00007209 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
Seth Cantrell79340072015-03-04 05:58:08 +00007210 << Ex->getType() << false << Ex->getSourceRange(),
7211 Ex->getLocStart(),
7212 /*IsStringLocation*/ false,
7213 getSpecifierRange(startSpecifier, specifierLen),
7214 FixItHint::CreateReplacement(
7215 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7216 } else {
JF Bastienec7d7f32018-06-22 21:54:40 +00007217 EmitFormatDiagnostic(S.PDiag(Diag)
Seth Cantrell79340072015-03-04 05:58:08 +00007218 << AT.getRepresentativeTypeName(S.Context)
7219 << Ex->getType() << false << Ex->getSourceRange(),
7220 Ex->getLocStart(),
7221 /*IsStringLocation*/ false,
7222 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007223 }
7224
Ted Kremenek02087932010-07-16 02:11:22 +00007225 return true;
7226}
7227
Stephen Hines648c3692016-09-16 01:07:04 +00007228static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007229 const Expr *OrigFormatExpr,
7230 ArrayRef<const Expr *> Args,
7231 bool HasVAListArg, unsigned format_idx,
7232 unsigned firstDataArg,
7233 Sema::FormatStringType Type,
7234 bool inFunctionCall,
7235 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007236 llvm::SmallBitVector &CheckedVarArgs,
7237 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007238 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007239 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007240 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007241 S, inFunctionCall, Args[format_idx],
7242 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007243 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007244 return;
7245 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007246
Ted Kremenekab278de2010-01-28 23:39:18 +00007247 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007248 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007249 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007250 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007251 const ConstantArrayType *T =
7252 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007253 assert(T && "String literal not of constant array type!");
7254 size_t TypeSize = T->getSize().getZExtValue();
7255 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007256 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007257
7258 // Emit a warning if the string literal is truncated and does not contain an
7259 // embedded null character.
7260 if (TypeSize <= StrRef.size() &&
7261 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7262 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007263 S, inFunctionCall, Args[format_idx],
7264 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007265 FExpr->getLocStart(),
7266 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7267 return;
7268 }
7269
Ted Kremenekab278de2010-01-28 23:39:18 +00007270 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007271 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007272 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007273 S, inFunctionCall, Args[format_idx],
7274 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007275 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007276 return;
7277 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007278
7279 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007280 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7281 Type == Sema::FST_OSTrace) {
7282 CheckPrintfHandler H(
7283 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7284 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7285 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7286 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007287
Hans Wennborg23926bd2011-12-15 10:25:47 +00007288 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007289 S.getLangOpts(),
7290 S.Context.getTargetInfo(),
7291 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007292 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007293 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007294 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7295 numDataArgs, Str, HasVAListArg, Args, format_idx,
7296 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007297
Hans Wennborg23926bd2011-12-15 10:25:47 +00007298 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007299 S.getLangOpts(),
7300 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007301 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007302 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007303}
7304
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007305bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7306 // Str - The format string. NOTE: this is NOT null-terminated!
7307 StringRef StrRef = FExpr->getString();
7308 const char *Str = StrRef.data();
7309 // Account for cases where the string literal is truncated in a declaration.
7310 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7311 assert(T && "String literal not of constant array type!");
7312 size_t TypeSize = T->getSize().getZExtValue();
7313 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7314 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7315 getLangOpts(),
7316 Context.getTargetInfo());
7317}
7318
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007319//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7320
7321// Returns the related absolute value function that is larger, of 0 if one
7322// does not exist.
7323static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7324 switch (AbsFunction) {
7325 default:
7326 return 0;
7327
7328 case Builtin::BI__builtin_abs:
7329 return Builtin::BI__builtin_labs;
7330 case Builtin::BI__builtin_labs:
7331 return Builtin::BI__builtin_llabs;
7332 case Builtin::BI__builtin_llabs:
7333 return 0;
7334
7335 case Builtin::BI__builtin_fabsf:
7336 return Builtin::BI__builtin_fabs;
7337 case Builtin::BI__builtin_fabs:
7338 return Builtin::BI__builtin_fabsl;
7339 case Builtin::BI__builtin_fabsl:
7340 return 0;
7341
7342 case Builtin::BI__builtin_cabsf:
7343 return Builtin::BI__builtin_cabs;
7344 case Builtin::BI__builtin_cabs:
7345 return Builtin::BI__builtin_cabsl;
7346 case Builtin::BI__builtin_cabsl:
7347 return 0;
7348
7349 case Builtin::BIabs:
7350 return Builtin::BIlabs;
7351 case Builtin::BIlabs:
7352 return Builtin::BIllabs;
7353 case Builtin::BIllabs:
7354 return 0;
7355
7356 case Builtin::BIfabsf:
7357 return Builtin::BIfabs;
7358 case Builtin::BIfabs:
7359 return Builtin::BIfabsl;
7360 case Builtin::BIfabsl:
7361 return 0;
7362
7363 case Builtin::BIcabsf:
7364 return Builtin::BIcabs;
7365 case Builtin::BIcabs:
7366 return Builtin::BIcabsl;
7367 case Builtin::BIcabsl:
7368 return 0;
7369 }
7370}
7371
7372// Returns the argument type of the absolute value function.
7373static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7374 unsigned AbsType) {
7375 if (AbsType == 0)
7376 return QualType();
7377
7378 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7379 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7380 if (Error != ASTContext::GE_None)
7381 return QualType();
7382
7383 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7384 if (!FT)
7385 return QualType();
7386
7387 if (FT->getNumParams() != 1)
7388 return QualType();
7389
7390 return FT->getParamType(0);
7391}
7392
7393// Returns the best absolute value function, or zero, based on type and
7394// current absolute value function.
7395static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7396 unsigned AbsFunctionKind) {
7397 unsigned BestKind = 0;
7398 uint64_t ArgSize = Context.getTypeSize(ArgType);
7399 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7400 Kind = getLargerAbsoluteValueFunction(Kind)) {
7401 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7402 if (Context.getTypeSize(ParamType) >= ArgSize) {
7403 if (BestKind == 0)
7404 BestKind = Kind;
7405 else if (Context.hasSameType(ParamType, ArgType)) {
7406 BestKind = Kind;
7407 break;
7408 }
7409 }
7410 }
7411 return BestKind;
7412}
7413
7414enum AbsoluteValueKind {
7415 AVK_Integer,
7416 AVK_Floating,
7417 AVK_Complex
7418};
7419
7420static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7421 if (T->isIntegralOrEnumerationType())
7422 return AVK_Integer;
7423 if (T->isRealFloatingType())
7424 return AVK_Floating;
7425 if (T->isAnyComplexType())
7426 return AVK_Complex;
7427
7428 llvm_unreachable("Type not integer, floating, or complex");
7429}
7430
7431// Changes the absolute value function to a different type. Preserves whether
7432// the function is a builtin.
7433static unsigned changeAbsFunction(unsigned AbsKind,
7434 AbsoluteValueKind ValueKind) {
7435 switch (ValueKind) {
7436 case AVK_Integer:
7437 switch (AbsKind) {
7438 default:
7439 return 0;
7440 case Builtin::BI__builtin_fabsf:
7441 case Builtin::BI__builtin_fabs:
7442 case Builtin::BI__builtin_fabsl:
7443 case Builtin::BI__builtin_cabsf:
7444 case Builtin::BI__builtin_cabs:
7445 case Builtin::BI__builtin_cabsl:
7446 return Builtin::BI__builtin_abs;
7447 case Builtin::BIfabsf:
7448 case Builtin::BIfabs:
7449 case Builtin::BIfabsl:
7450 case Builtin::BIcabsf:
7451 case Builtin::BIcabs:
7452 case Builtin::BIcabsl:
7453 return Builtin::BIabs;
7454 }
7455 case AVK_Floating:
7456 switch (AbsKind) {
7457 default:
7458 return 0;
7459 case Builtin::BI__builtin_abs:
7460 case Builtin::BI__builtin_labs:
7461 case Builtin::BI__builtin_llabs:
7462 case Builtin::BI__builtin_cabsf:
7463 case Builtin::BI__builtin_cabs:
7464 case Builtin::BI__builtin_cabsl:
7465 return Builtin::BI__builtin_fabsf;
7466 case Builtin::BIabs:
7467 case Builtin::BIlabs:
7468 case Builtin::BIllabs:
7469 case Builtin::BIcabsf:
7470 case Builtin::BIcabs:
7471 case Builtin::BIcabsl:
7472 return Builtin::BIfabsf;
7473 }
7474 case AVK_Complex:
7475 switch (AbsKind) {
7476 default:
7477 return 0;
7478 case Builtin::BI__builtin_abs:
7479 case Builtin::BI__builtin_labs:
7480 case Builtin::BI__builtin_llabs:
7481 case Builtin::BI__builtin_fabsf:
7482 case Builtin::BI__builtin_fabs:
7483 case Builtin::BI__builtin_fabsl:
7484 return Builtin::BI__builtin_cabsf;
7485 case Builtin::BIabs:
7486 case Builtin::BIlabs:
7487 case Builtin::BIllabs:
7488 case Builtin::BIfabsf:
7489 case Builtin::BIfabs:
7490 case Builtin::BIfabsl:
7491 return Builtin::BIcabsf;
7492 }
7493 }
7494 llvm_unreachable("Unable to convert function");
7495}
7496
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007497static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007498 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7499 if (!FnInfo)
7500 return 0;
7501
7502 switch (FDecl->getBuiltinID()) {
7503 default:
7504 return 0;
7505 case Builtin::BI__builtin_abs:
7506 case Builtin::BI__builtin_fabs:
7507 case Builtin::BI__builtin_fabsf:
7508 case Builtin::BI__builtin_fabsl:
7509 case Builtin::BI__builtin_labs:
7510 case Builtin::BI__builtin_llabs:
7511 case Builtin::BI__builtin_cabs:
7512 case Builtin::BI__builtin_cabsf:
7513 case Builtin::BI__builtin_cabsl:
7514 case Builtin::BIabs:
7515 case Builtin::BIlabs:
7516 case Builtin::BIllabs:
7517 case Builtin::BIfabs:
7518 case Builtin::BIfabsf:
7519 case Builtin::BIfabsl:
7520 case Builtin::BIcabs:
7521 case Builtin::BIcabsf:
7522 case Builtin::BIcabsl:
7523 return FDecl->getBuiltinID();
7524 }
7525 llvm_unreachable("Unknown Builtin type");
7526}
7527
7528// If the replacement is valid, emit a note with replacement function.
7529// Additionally, suggest including the proper header if not already included.
7530static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007531 unsigned AbsKind, QualType ArgType) {
7532 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007533 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007534 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007535 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7536 FunctionName = "std::abs";
7537 if (ArgType->isIntegralOrEnumerationType()) {
7538 HeaderName = "cstdlib";
7539 } else if (ArgType->isRealFloatingType()) {
7540 HeaderName = "cmath";
7541 } else {
7542 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007543 }
Richard Trieubeffb832014-04-15 23:47:53 +00007544
7545 // Lookup all std::abs
7546 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007547 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007548 R.suppressDiagnostics();
7549 S.LookupQualifiedName(R, Std);
7550
7551 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007552 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007553 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7554 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7555 } else {
7556 FDecl = dyn_cast<FunctionDecl>(I);
7557 }
7558 if (!FDecl)
7559 continue;
7560
7561 // Found std::abs(), check that they are the right ones.
7562 if (FDecl->getNumParams() != 1)
7563 continue;
7564
7565 // Check that the parameter type can handle the argument.
7566 QualType ParamType = FDecl->getParamDecl(0)->getType();
7567 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7568 S.Context.getTypeSize(ArgType) <=
7569 S.Context.getTypeSize(ParamType)) {
7570 // Found a function, don't need the header hint.
7571 EmitHeaderHint = false;
7572 break;
7573 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007574 }
Richard Trieubeffb832014-04-15 23:47:53 +00007575 }
7576 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007577 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007578 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7579
7580 if (HeaderName) {
7581 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7582 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7583 R.suppressDiagnostics();
7584 S.LookupName(R, S.getCurScope());
7585
7586 if (R.isSingleResult()) {
7587 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7588 if (FD && FD->getBuiltinID() == AbsKind) {
7589 EmitHeaderHint = false;
7590 } else {
7591 return;
7592 }
7593 } else if (!R.empty()) {
7594 return;
7595 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007596 }
7597 }
7598
7599 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007600 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007601
Richard Trieubeffb832014-04-15 23:47:53 +00007602 if (!HeaderName)
7603 return;
7604
7605 if (!EmitHeaderHint)
7606 return;
7607
Alp Toker5d96e0a2014-07-11 20:53:51 +00007608 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7609 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007610}
7611
Richard Trieua7f30b12016-12-06 01:42:28 +00007612template <std::size_t StrLen>
7613static bool IsStdFunction(const FunctionDecl *FDecl,
7614 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007615 if (!FDecl)
7616 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007617 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007618 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007619 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007620 return false;
7621
7622 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007623}
7624
7625// Warn when using the wrong abs() function.
7626void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007627 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007628 if (Call->getNumArgs() != 1)
7629 return;
7630
7631 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007632 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007633 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007634 return;
7635
7636 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7637 QualType ParamType = Call->getArg(0)->getType();
7638
Alp Toker5d96e0a2014-07-11 20:53:51 +00007639 // Unsigned types cannot be negative. Suggest removing the absolute value
7640 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007641 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007642 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007643 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007644 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7645 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007646 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007647 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7648 return;
7649 }
7650
David Majnemer7f77eb92015-11-15 03:04:34 +00007651 // Taking the absolute value of a pointer is very suspicious, they probably
7652 // wanted to index into an array, dereference a pointer, call a function, etc.
7653 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7654 unsigned DiagType = 0;
7655 if (ArgType->isFunctionType())
7656 DiagType = 1;
7657 else if (ArgType->isArrayType())
7658 DiagType = 2;
7659
7660 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7661 return;
7662 }
7663
Richard Trieubeffb832014-04-15 23:47:53 +00007664 // std::abs has overloads which prevent most of the absolute value problems
7665 // from occurring.
7666 if (IsStdAbs)
7667 return;
7668
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007669 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7670 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7671
7672 // The argument and parameter are the same kind. Check if they are the right
7673 // size.
7674 if (ArgValueKind == ParamValueKind) {
7675 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7676 return;
7677
7678 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7679 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7680 << FDecl << ArgType << ParamType;
7681
7682 if (NewAbsKind == 0)
7683 return;
7684
7685 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007686 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007687 return;
7688 }
7689
7690 // ArgValueKind != ParamValueKind
7691 // The wrong type of absolute value function was used. Attempt to find the
7692 // proper one.
7693 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7694 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7695 if (NewAbsKind == 0)
7696 return;
7697
7698 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7699 << FDecl << ParamValueKind << ArgValueKind;
7700
7701 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007702 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007703}
7704
Richard Trieu67c00712016-12-05 23:41:46 +00007705//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007706void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7707 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007708 if (!Call || !FDecl) return;
7709
7710 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007711 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007712 if (Call->getExprLoc().isMacroID()) return;
7713
7714 // Only care about the one template argument, two function parameter std::max
7715 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007716 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007717 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7718 if (!ArgList) return;
7719 if (ArgList->size() != 1) return;
7720
7721 // Check that template type argument is unsigned integer.
7722 const auto& TA = ArgList->get(0);
7723 if (TA.getKind() != TemplateArgument::Type) return;
7724 QualType ArgType = TA.getAsType();
7725 if (!ArgType->isUnsignedIntegerType()) return;
7726
7727 // See if either argument is a literal zero.
7728 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7729 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7730 if (!MTE) return false;
7731 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7732 if (!Num) return false;
7733 if (Num->getValue() != 0) return false;
7734 return true;
7735 };
7736
7737 const Expr *FirstArg = Call->getArg(0);
7738 const Expr *SecondArg = Call->getArg(1);
7739 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7740 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7741
7742 // Only warn when exactly one argument is zero.
7743 if (IsFirstArgZero == IsSecondArgZero) return;
7744
7745 SourceRange FirstRange = FirstArg->getSourceRange();
7746 SourceRange SecondRange = SecondArg->getSourceRange();
7747
7748 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7749
7750 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7751 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7752
7753 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7754 SourceRange RemovalRange;
7755 if (IsFirstArgZero) {
7756 RemovalRange = SourceRange(FirstRange.getBegin(),
7757 SecondRange.getBegin().getLocWithOffset(-1));
7758 } else {
7759 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7760 SecondRange.getEnd());
7761 }
7762
7763 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7764 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7765 << FixItHint::CreateRemoval(RemovalRange);
7766}
7767
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007768//===--- CHECK: Standard memory functions ---------------------------------===//
7769
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007770/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007771/// such as memcmp, strncat, etc and warns if it's a comparison.
7772///
7773/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7774static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7775 IdentifierInfo *FnName,
7776 SourceLocation FnLoc,
7777 SourceLocation RParenLoc) {
7778 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7779 if (!Size)
7780 return false;
7781
Richard Smithc70f1d62017-12-14 15:16:18 +00007782 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7783 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007784 return false;
7785
Nico Weber0e6daef2013-12-26 23:38:39 +00007786 SourceRange SizeRange = Size->getSourceRange();
7787 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7788 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007789 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007790 << FnName << FixItHint::CreateInsertion(
7791 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007792 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007793 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007794 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007795 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7796 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007797
7798 return true;
7799}
7800
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007801/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007802/// (e.g., whether it has a vtable).
7803static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7804 bool &IsContained) {
7805 // Look through array types while ignoring qualifiers.
7806 const Type *Ty = T->getBaseElementTypeUnsafe();
7807 IsContained = false;
7808
7809 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7810 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007811 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007812 return nullptr;
7813
7814 if (RD->isDynamicClass())
7815 return RD;
7816
7817 // Check all the fields. If any bases were dynamic, the class is dynamic.
7818 // It's impossible for a class to transitively contain itself by value, so
7819 // infinite recursion is impossible.
7820 for (auto *FD : RD->fields()) {
7821 bool SubContained;
7822 if (const CXXRecordDecl *ContainedRD =
7823 getContainedDynamicClass(FD->getType(), SubContained)) {
7824 IsContained = true;
7825 return ContainedRD;
7826 }
7827 }
7828
7829 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007830}
7831
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007832/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007833/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007834static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007835 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007836 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007837 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007838 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007839
Craig Topperc3ec1492014-05-26 06:22:03 +00007840 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007841}
7842
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007843/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007844static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007845 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7846 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007847 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007848 return SizeOf->getTypeOfArgument();
7849
7850 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007851}
7852
Akira Hatanaka2be04412018-04-17 19:13:41 +00007853namespace {
7854
7855struct SearchNonTrivialToInitializeField
7856 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7857 using Super =
7858 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7859
7860 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7861
7862 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7863 SourceLocation SL) {
7864 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7865 asDerived().visitArray(PDIK, AT, SL);
7866 return;
7867 }
7868
7869 Super::visitWithKind(PDIK, FT, SL);
7870 }
7871
7872 void visitARCStrong(QualType FT, SourceLocation SL) {
7873 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7874 }
7875 void visitARCWeak(QualType FT, SourceLocation SL) {
7876 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7877 }
7878 void visitStruct(QualType FT, SourceLocation SL) {
7879 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7880 visit(FD->getType(), FD->getLocation());
7881 }
7882 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7883 const ArrayType *AT, SourceLocation SL) {
7884 visit(getContext().getBaseElementType(AT), SL);
7885 }
7886 void visitTrivial(QualType FT, SourceLocation SL) {}
7887
7888 static void diag(QualType RT, const Expr *E, Sema &S) {
7889 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7890 }
7891
7892 ASTContext &getContext() { return S.getASTContext(); }
7893
7894 const Expr *E;
7895 Sema &S;
7896};
7897
7898struct SearchNonTrivialToCopyField
7899 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7900 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7901
7902 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7903
7904 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7905 SourceLocation SL) {
7906 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7907 asDerived().visitArray(PCK, AT, SL);
7908 return;
7909 }
7910
7911 Super::visitWithKind(PCK, FT, SL);
7912 }
7913
7914 void visitARCStrong(QualType FT, SourceLocation SL) {
7915 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7916 }
7917 void visitARCWeak(QualType FT, SourceLocation SL) {
7918 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7919 }
7920 void visitStruct(QualType FT, SourceLocation SL) {
7921 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7922 visit(FD->getType(), FD->getLocation());
7923 }
7924 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7925 SourceLocation SL) {
7926 visit(getContext().getBaseElementType(AT), SL);
7927 }
7928 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7929 SourceLocation SL) {}
7930 void visitTrivial(QualType FT, SourceLocation SL) {}
7931 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7932
7933 static void diag(QualType RT, const Expr *E, Sema &S) {
7934 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7935 }
7936
7937 ASTContext &getContext() { return S.getASTContext(); }
7938
7939 const Expr *E;
7940 Sema &S;
7941};
7942
7943}
7944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007945/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007946///
Chandler Carruthac687262011-06-03 06:23:57 +00007947/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007948/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7949/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007950///
7951/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007952void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007953 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007954 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007955 assert(BId != 0);
7956
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007957 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007958 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007959 unsigned ExpectedNumArgs =
7960 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007961 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007962 return;
7963
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007964 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007965 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007966 unsigned LenArg =
7967 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007968 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007969
Nico Weber0e6daef2013-12-26 23:38:39 +00007970 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7971 Call->getLocStart(), Call->getRParenLoc()))
7972 return;
7973
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007974 // We have special checking when the length is a sizeof expression.
7975 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7976 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7977 llvm::FoldingSetNodeID SizeOfArgID;
7978
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007979 // Although widely used, 'bzero' is not a standard function. Be more strict
7980 // with the argument types before allowing diagnostics and only allow the
7981 // form bzero(ptr, sizeof(...)).
7982 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7983 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7984 return;
7985
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007986 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7987 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007988 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007989
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007990 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007991 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007992 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007993 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007994
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007995 // Never warn about void type pointers. This can be used to suppress
7996 // false positives.
7997 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007998 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007999
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008000 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
8001 // actually comparing the expressions for equality. Because computing the
8002 // expression IDs can be expensive, we only do this if the diagnostic is
8003 // enabled.
8004 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008005 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
8006 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008007 // We only compute IDs for expressions if the warning is enabled, and
8008 // cache the sizeof arg's ID.
8009 if (SizeOfArgID == llvm::FoldingSetNodeID())
8010 SizeOfArg->Profile(SizeOfArgID, Context, true);
8011 llvm::FoldingSetNodeID DestID;
8012 Dest->Profile(DestID, Context, true);
8013 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00008014 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
8015 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008016 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00008017 StringRef ReadableName = FnName->getName();
8018
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008019 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00008020 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008021 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00008022 if (!PointeeTy->isIncompleteType() &&
8023 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008024 ActionIdx = 2; // If the pointee's size is sizeof(char),
8025 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00008026
8027 // If the function is defined as a builtin macro, do not show macro
8028 // expansion.
8029 SourceLocation SL = SizeOfArg->getExprLoc();
8030 SourceRange DSR = Dest->getSourceRange();
8031 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008032 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00008033
8034 if (SM.isMacroArgExpansion(SL)) {
8035 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
8036 SL = SM.getSpellingLoc(SL);
8037 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8038 SM.getSpellingLoc(DSR.getEnd()));
8039 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8040 SM.getSpellingLoc(SSR.getEnd()));
8041 }
8042
Anna Zaksd08d9152012-05-30 23:14:52 +00008043 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008044 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00008045 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00008046 << PointeeTy
8047 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00008048 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00008049 << SSR);
8050 DiagRuntimeBehavior(SL, SizeOfArg,
8051 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8052 << ActionIdx
8053 << SSR);
8054
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00008055 break;
8056 }
8057 }
8058
8059 // Also check for cases where the sizeof argument is the exact same
8060 // type as the memory argument, and where it points to a user-defined
8061 // record type.
8062 if (SizeOfArgTy != QualType()) {
8063 if (PointeeTy->isRecordType() &&
8064 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8065 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8066 PDiag(diag::warn_sizeof_pointer_type_memaccess)
8067 << FnName << SizeOfArgTy << ArgIdx
8068 << PointeeTy << Dest->getSourceRange()
8069 << LenExpr->getSourceRange());
8070 break;
8071 }
Nico Weberc5e73862011-06-14 16:14:58 +00008072 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00008073 } else if (DestTy->isArrayType()) {
8074 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00008075 }
Nico Weberc5e73862011-06-14 16:14:58 +00008076
Nico Weberc44b35e2015-03-21 17:37:46 +00008077 if (PointeeTy == QualType())
8078 continue;
Anna Zaks22122702012-01-17 00:37:07 +00008079
Nico Weberc44b35e2015-03-21 17:37:46 +00008080 // Always complain about dynamic classes.
8081 bool IsContained;
8082 if (const CXXRecordDecl *ContainedRD =
8083 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00008084
Nico Weberc44b35e2015-03-21 17:37:46 +00008085 unsigned OperationType = 0;
8086 // "overwritten" if we're warning about the destination for any call
8087 // but memcmp; otherwise a verb appropriate to the call.
8088 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
8089 if (BId == Builtin::BImemcpy)
8090 OperationType = 1;
8091 else if(BId == Builtin::BImemmove)
8092 OperationType = 2;
8093 else if (BId == Builtin::BImemcmp)
8094 OperationType = 3;
8095 }
8096
John McCall31168b02011-06-15 23:02:42 +00008097 DiagRuntimeBehavior(
8098 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00008099 PDiag(diag::warn_dyn_class_memaccess)
8100 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
8101 << FnName << IsContained << ContainedRD << OperationType
8102 << Call->getCallee()->getSourceRange());
8103 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
8104 BId != Builtin::BImemset)
8105 DiagRuntimeBehavior(
8106 Dest->getExprLoc(), Dest,
8107 PDiag(diag::warn_arc_object_memaccess)
8108 << ArgIdx << FnName << PointeeTy
8109 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00008110 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
8111 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
8112 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
8113 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8114 PDiag(diag::warn_cstruct_memaccess)
8115 << ArgIdx << FnName << PointeeTy << 0);
8116 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
8117 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
8118 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
8119 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
8120 PDiag(diag::warn_cstruct_memaccess)
8121 << ArgIdx << FnName << PointeeTy << 1);
8122 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
8123 } else {
8124 continue;
8125 }
8126 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00008127 continue;
8128
8129 DiagRuntimeBehavior(
8130 Dest->getExprLoc(), Dest,
8131 PDiag(diag::note_bad_memaccess_silence)
8132 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
8133 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00008134 }
8135}
8136
Ted Kremenek6865f772011-08-18 20:55:45 +00008137// A little helper routine: ignore addition and subtraction of integer literals.
8138// This intentionally does not ignore all integer constant expressions because
8139// we don't want to remove sizeof().
8140static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
8141 Ex = Ex->IgnoreParenCasts();
8142
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008143 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00008144 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
8145 if (!BO || !BO->isAdditiveOp())
8146 break;
8147
8148 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
8149 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
8150
8151 if (isa<IntegerLiteral>(RHS))
8152 Ex = LHS;
8153 else if (isa<IntegerLiteral>(LHS))
8154 Ex = RHS;
8155 else
8156 break;
8157 }
8158
8159 return Ex;
8160}
8161
Anna Zaks13b08572012-08-08 21:42:23 +00008162static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
8163 ASTContext &Context) {
8164 // Only handle constant-sized or VLAs, but not flexible members.
8165 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
8166 // Only issue the FIXIT for arrays of size > 1.
8167 if (CAT->getSize().getSExtValue() <= 1)
8168 return false;
8169 } else if (!Ty->isVariableArrayType()) {
8170 return false;
8171 }
8172 return true;
8173}
8174
Ted Kremenek6865f772011-08-18 20:55:45 +00008175// Warn if the user has made the 'size' argument to strlcpy or strlcat
8176// be the size of the source, instead of the destination.
8177void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
8178 IdentifierInfo *FnName) {
8179
8180 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00008181 unsigned NumArgs = Call->getNumArgs();
8182 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00008183 return;
8184
8185 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
8186 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00008187 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00008188
8189 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
8190 Call->getLocStart(), Call->getRParenLoc()))
8191 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00008192
8193 // Look for 'strlcpy(dst, x, sizeof(x))'
8194 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
8195 CompareWithSrc = Ex;
8196 else {
8197 // Look for 'strlcpy(dst, x, strlen(x))'
8198 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00008199 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
8200 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00008201 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
8202 }
8203 }
8204
8205 if (!CompareWithSrc)
8206 return;
8207
8208 // Determine if the argument to sizeof/strlen is equal to the source
8209 // argument. In principle there's all kinds of things you could do
8210 // here, for instance creating an == expression and evaluating it with
8211 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8212 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8213 if (!SrcArgDRE)
8214 return;
8215
8216 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8217 if (!CompareWithSrcDRE ||
8218 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8219 return;
8220
8221 const Expr *OriginalSizeArg = Call->getArg(2);
8222 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8223 << OriginalSizeArg->getSourceRange() << FnName;
8224
8225 // Output a FIXIT hint if the destination is an array (rather than a
8226 // pointer to an array). This could be enhanced to handle some
8227 // pointers if we know the actual size, like if DstArg is 'array+2'
8228 // we could say 'sizeof(array)-2'.
8229 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008230 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008231 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008232
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008233 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008234 llvm::raw_svector_ostream OS(sizeString);
8235 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008236 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008237 OS << ")";
8238
8239 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8240 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8241 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008242}
8243
Anna Zaks314cd092012-02-01 19:08:57 +00008244/// Check if two expressions refer to the same declaration.
8245static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8246 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8247 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8248 return D1->getDecl() == D2->getDecl();
8249 return false;
8250}
8251
8252static const Expr *getStrlenExprArg(const Expr *E) {
8253 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8254 const FunctionDecl *FD = CE->getDirectCallee();
8255 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008256 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008257 return CE->getArg(0)->IgnoreParenCasts();
8258 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008259 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008260}
8261
8262// Warn on anti-patterns as the 'size' argument to strncat.
8263// The correct size argument should look like following:
8264// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8265void Sema::CheckStrncatArguments(const CallExpr *CE,
8266 IdentifierInfo *FnName) {
8267 // Don't crash if the user has the wrong number of arguments.
8268 if (CE->getNumArgs() < 3)
8269 return;
8270 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8271 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8272 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8273
Nico Weber0e6daef2013-12-26 23:38:39 +00008274 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8275 CE->getRParenLoc()))
8276 return;
8277
Anna Zaks314cd092012-02-01 19:08:57 +00008278 // Identify common expressions, which are wrongly used as the size argument
8279 // to strncat and may lead to buffer overflows.
8280 unsigned PatternType = 0;
8281 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8282 // - sizeof(dst)
8283 if (referToTheSameDecl(SizeOfArg, DstArg))
8284 PatternType = 1;
8285 // - sizeof(src)
8286 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8287 PatternType = 2;
8288 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8289 if (BE->getOpcode() == BO_Sub) {
8290 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8291 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8292 // - sizeof(dst) - strlen(dst)
8293 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8294 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8295 PatternType = 1;
8296 // - sizeof(src) - (anything)
8297 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8298 PatternType = 2;
8299 }
8300 }
8301
8302 if (PatternType == 0)
8303 return;
8304
Anna Zaks5069aa32012-02-03 01:27:37 +00008305 // Generate the diagnostic.
8306 SourceLocation SL = LenArg->getLocStart();
8307 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008308 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008309
8310 // If the function is defined as a builtin macro, do not show macro expansion.
8311 if (SM.isMacroArgExpansion(SL)) {
8312 SL = SM.getSpellingLoc(SL);
8313 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8314 SM.getSpellingLoc(SR.getEnd()));
8315 }
8316
Anna Zaks13b08572012-08-08 21:42:23 +00008317 // Check if the destination is an array (rather than a pointer to an array).
8318 QualType DstTy = DstArg->getType();
8319 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8320 Context);
8321 if (!isKnownSizeArray) {
8322 if (PatternType == 1)
8323 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8324 else
8325 Diag(SL, diag::warn_strncat_src_size) << SR;
8326 return;
8327 }
8328
Anna Zaks314cd092012-02-01 19:08:57 +00008329 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008330 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008331 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008332 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008333
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008334 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008335 llvm::raw_svector_ostream OS(sizeString);
8336 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008337 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008338 OS << ") - ";
8339 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008340 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008341 OS << ") - 1";
8342
Anna Zaks5069aa32012-02-03 01:27:37 +00008343 Diag(SL, diag::note_strncat_wrong_size)
8344 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008345}
8346
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008347//===--- CHECK: Return Address of Stack Variable --------------------------===//
8348
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008349static const Expr *EvalVal(const Expr *E,
8350 SmallVectorImpl<const DeclRefExpr *> &refVars,
8351 const Decl *ParentDecl);
8352static const Expr *EvalAddr(const Expr *E,
8353 SmallVectorImpl<const DeclRefExpr *> &refVars,
8354 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008355
8356/// CheckReturnStackAddr - Check if a return statement returns the address
8357/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008358static void
8359CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8360 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008361 const Expr *stackE = nullptr;
8362 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008363
8364 // Perform checking for returned stack addresses, local blocks,
8365 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008366 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008367 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008368 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008369 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008370 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008371 }
8372
Craig Topperc3ec1492014-05-26 06:22:03 +00008373 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008374 return; // Nothing suspicious was found.
8375
Simon Pilgrim750bde62017-03-31 11:00:53 +00008376 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008377 // of a parameter reference doesn't need a warning.
8378 for (auto *DRE : refVars)
8379 if (isa<ParmVarDecl>(DRE->getDecl()))
8380 return;
8381
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008382 SourceLocation diagLoc;
8383 SourceRange diagRange;
8384 if (refVars.empty()) {
8385 diagLoc = stackE->getLocStart();
8386 diagRange = stackE->getSourceRange();
8387 } else {
8388 // We followed through a reference variable. 'stackE' contains the
8389 // problematic expression but we will warn at the return statement pointing
8390 // at the reference variable. We will later display the "trail" of
8391 // reference variables using notes.
8392 diagLoc = refVars[0]->getLocStart();
8393 diagRange = refVars[0]->getSourceRange();
8394 }
8395
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008396 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8397 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008398 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008399 << DR->getDecl()->getDeclName() << diagRange;
8400 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008401 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008402 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008403 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008404 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008405 // If there is an LValue->RValue conversion, then the value of the
8406 // reference type is used, not the reference.
8407 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8408 if (ICE->getCastKind() == CK_LValueToRValue) {
8409 return;
8410 }
8411 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008412 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8413 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008414 }
8415
8416 // Display the "trail" of reference variables that we followed until we
8417 // found the problematic expression using notes.
8418 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008419 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008420 // If this var binds to another reference var, show the range of the next
8421 // var, otherwise the var binds to the problematic expression, in which case
8422 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008423 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8424 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008425 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8426 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008427 }
8428}
8429
8430/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8431/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008432/// to a location on the stack, a local block, an address of a label, or a
8433/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008434/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008435/// encounter a subexpression that (1) clearly does not lead to one of the
8436/// above problematic expressions (2) is something we cannot determine leads to
8437/// a problematic expression based on such local checking.
8438///
8439/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8440/// the expression that they point to. Such variables are added to the
8441/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008442///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008443/// EvalAddr processes expressions that are pointers that are used as
8444/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008445/// At the base case of the recursion is a check for the above problematic
8446/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008447///
8448/// This implementation handles:
8449///
8450/// * pointer-to-pointer casts
8451/// * implicit conversions from array references to pointers
8452/// * taking the address of fields
8453/// * arbitrary interplay between "&" and "*" operators
8454/// * pointer arithmetic from an address of a stack variable
8455/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008456static const Expr *EvalAddr(const Expr *E,
8457 SmallVectorImpl<const DeclRefExpr *> &refVars,
8458 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008459 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008460 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008461
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008462 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008463 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008464 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008465 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008466 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008467
Peter Collingbourne91147592011-04-15 00:35:48 +00008468 E = E->IgnoreParens();
8469
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008470 // Our "symbolic interpreter" is just a dispatch off the currently
8471 // viewed AST node. We then recursively traverse the AST by calling
8472 // EvalAddr and EvalVal appropriately.
8473 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008474 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008475 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008476
Richard Smith40f08eb2014-01-30 22:05:38 +00008477 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008478 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008479 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008480
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008481 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008482 // If this is a reference variable, follow through to the expression that
8483 // it points to.
8484 if (V->hasLocalStorage() &&
8485 V->getType()->isReferenceType() && V->hasInit()) {
8486 // Add the reference variable to the "trail".
8487 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008488 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008489 }
8490
Craig Topperc3ec1492014-05-26 06:22:03 +00008491 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008492 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008493
Chris Lattner934edb22007-12-28 05:31:15 +00008494 case Stmt::UnaryOperatorClass: {
8495 // The only unary operator that make sense to handle here
8496 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008497 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008498
John McCalle3027922010-08-25 11:45:40 +00008499 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008500 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008501 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008502 }
Mike Stump11289f42009-09-09 15:08:12 +00008503
Chris Lattner934edb22007-12-28 05:31:15 +00008504 case Stmt::BinaryOperatorClass: {
8505 // Handle pointer arithmetic. All other binary operators are not valid
8506 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008507 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008508 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008509
John McCalle3027922010-08-25 11:45:40 +00008510 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008511 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008512
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008513 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008514
8515 // Determine which argument is the real pointer base. It could be
8516 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008517 if (!Base->getType()->isPointerType())
8518 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008519
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008520 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008521 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008522 }
Steve Naroff2752a172008-09-10 19:17:48 +00008523
Chris Lattner934edb22007-12-28 05:31:15 +00008524 // For conditional operators we need to see if either the LHS or RHS are
8525 // valid DeclRefExpr*s. If one of them is valid, we return it.
8526 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008527 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008528
Chris Lattner934edb22007-12-28 05:31:15 +00008529 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008530 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008531 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008532 // In C++, we can have a throw-expression, which has 'void' type.
8533 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008534 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008535 return LHS;
8536 }
Chris Lattner934edb22007-12-28 05:31:15 +00008537
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008538 // In C++, we can have a throw-expression, which has 'void' type.
8539 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008540 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008541
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008542 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008543 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008544
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008545 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008546 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008547 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008548 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008549
8550 case Stmt::AddrLabelExprClass:
8551 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008552
John McCall28fc7092011-11-10 05:35:25 +00008553 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008554 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8555 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008556
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008557 // For casts, we need to handle conversions from arrays to
8558 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008559 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008560 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008561 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008562 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008563 case Stmt::CXXStaticCastExprClass:
8564 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008565 case Stmt::CXXConstCastExprClass:
8566 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008567 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008568 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008569 case CK_LValueToRValue:
8570 case CK_NoOp:
8571 case CK_BaseToDerived:
8572 case CK_DerivedToBase:
8573 case CK_UncheckedDerivedToBase:
8574 case CK_Dynamic:
8575 case CK_CPointerToObjCPointerCast:
8576 case CK_BlockPointerToObjCPointerCast:
8577 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008578 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008579
8580 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008581 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008582
Richard Trieudadefde2014-07-02 04:39:38 +00008583 case CK_BitCast:
8584 if (SubExpr->getType()->isAnyPointerType() ||
8585 SubExpr->getType()->isBlockPointerType() ||
8586 SubExpr->getType()->isObjCQualifiedIdType())
8587 return EvalAddr(SubExpr, refVars, ParentDecl);
8588 else
8589 return nullptr;
8590
Eli Friedman8195ad72012-02-23 23:04:32 +00008591 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008592 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008593 }
Chris Lattner934edb22007-12-28 05:31:15 +00008594 }
Mike Stump11289f42009-09-09 15:08:12 +00008595
Douglas Gregorfe314812011-06-21 17:03:29 +00008596 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008597 if (const Expr *Result =
8598 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8599 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008600 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008601 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008602
Chris Lattner934edb22007-12-28 05:31:15 +00008603 // Everything else: we simply don't reason about them.
8604 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008605 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008606 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008607}
Mike Stump11289f42009-09-09 15:08:12 +00008608
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008609/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8610/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008611static const Expr *EvalVal(const Expr *E,
8612 SmallVectorImpl<const DeclRefExpr *> &refVars,
8613 const Decl *ParentDecl) {
8614 do {
8615 // We should only be called for evaluating non-pointer expressions, or
8616 // expressions with a pointer type that are not used as references but
8617 // instead
8618 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008619
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008620 // Our "symbolic interpreter" is just a dispatch off the currently
8621 // viewed AST node. We then recursively traverse the AST by calling
8622 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008623
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008624 E = E->IgnoreParens();
8625 switch (E->getStmtClass()) {
8626 case Stmt::ImplicitCastExprClass: {
8627 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8628 if (IE->getValueKind() == VK_LValue) {
8629 E = IE->getSubExpr();
8630 continue;
8631 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008632 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008633 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008634
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008635 case Stmt::ExprWithCleanupsClass:
8636 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8637 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008638
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008639 case Stmt::DeclRefExprClass: {
8640 // When we hit a DeclRefExpr we are looking at code that refers to a
8641 // variable's name. If it's not a reference variable we check if it has
8642 // local storage within the function, and if so, return the expression.
8643 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8644
8645 // If we leave the immediate function, the lifetime isn't about to end.
8646 if (DR->refersToEnclosingVariableOrCapture())
8647 return nullptr;
8648
8649 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8650 // Check if it refers to itself, e.g. "int& i = i;".
8651 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008652 return DR;
8653
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008654 if (V->hasLocalStorage()) {
8655 if (!V->getType()->isReferenceType())
8656 return DR;
8657
8658 // Reference variable, follow through to the expression that
8659 // it points to.
8660 if (V->hasInit()) {
8661 // Add the reference variable to the "trail".
8662 refVars.push_back(DR);
8663 return EvalVal(V->getInit(), refVars, V);
8664 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008665 }
8666 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008667
8668 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008669 }
Mike Stump11289f42009-09-09 15:08:12 +00008670
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008671 case Stmt::UnaryOperatorClass: {
8672 // The only unary operator that make sense to handle here
8673 // is Deref. All others don't resolve to a "name." This includes
8674 // handling all sorts of rvalues passed to a unary operator.
8675 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008676
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008677 if (U->getOpcode() == UO_Deref)
8678 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008679
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008680 return nullptr;
8681 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008682
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008683 case Stmt::ArraySubscriptExprClass: {
8684 // Array subscripts are potential references to data on the stack. We
8685 // retrieve the DeclRefExpr* for the array variable if it indeed
8686 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008687 const auto *ASE = cast<ArraySubscriptExpr>(E);
8688 if (ASE->isTypeDependent())
8689 return nullptr;
8690 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008691 }
Mike Stump11289f42009-09-09 15:08:12 +00008692
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008693 case Stmt::OMPArraySectionExprClass: {
8694 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8695 ParentDecl);
8696 }
Mike Stump11289f42009-09-09 15:08:12 +00008697
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008698 case Stmt::ConditionalOperatorClass: {
8699 // For conditional operators we need to see if either the LHS or RHS are
8700 // non-NULL Expr's. If one is non-NULL, we return it.
8701 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008702
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008703 // Handle the GNU extension for missing LHS.
8704 if (const Expr *LHSExpr = C->getLHS()) {
8705 // In C++, we can have a throw-expression, which has 'void' type.
8706 if (!LHSExpr->getType()->isVoidType())
8707 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8708 return LHS;
8709 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008710
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008711 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008712 if (C->getRHS()->getType()->isVoidType())
8713 return nullptr;
8714
8715 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008716 }
8717
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008718 // Accesses to members are potential references to data on the stack.
8719 case Stmt::MemberExprClass: {
8720 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008721
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008722 // Check for indirect access. We only want direct field accesses.
8723 if (M->isArrow())
8724 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008725
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008726 // Check whether the member type is itself a reference, in which case
8727 // we're not going to refer to the member, but to what the member refers
8728 // to.
8729 if (M->getMemberDecl()->getType()->isReferenceType())
8730 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008731
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008732 return EvalVal(M->getBase(), refVars, ParentDecl);
8733 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008734
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008735 case Stmt::MaterializeTemporaryExprClass:
8736 if (const Expr *Result =
8737 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8738 refVars, ParentDecl))
8739 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008740 return E;
8741
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008742 default:
8743 // Check that we don't return or take the address of a reference to a
8744 // temporary. This is only useful in C++.
8745 if (!E->isTypeDependent() && E->isRValue())
8746 return E;
8747
8748 // Everything else: we simply don't reason about them.
8749 return nullptr;
8750 }
8751 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008752}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008753
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008754void
8755Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8756 SourceLocation ReturnLoc,
8757 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008758 const AttrVec *Attrs,
8759 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008760 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8761
8762 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008763 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8764 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008765 CheckNonNullExpr(*this, RetValExp))
8766 Diag(ReturnLoc, diag::warn_null_ret)
8767 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008768
8769 // C++11 [basic.stc.dynamic.allocation]p4:
8770 // If an allocation function declared with a non-throwing
8771 // exception-specification fails to allocate storage, it shall return
8772 // a null pointer. Any other allocation function that fails to allocate
8773 // storage shall indicate failure only by throwing an exception [...]
8774 if (FD) {
8775 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8776 if (Op == OO_New || Op == OO_Array_New) {
8777 const FunctionProtoType *Proto
8778 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008779 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008780 CheckNonNullExpr(*this, RetValExp))
8781 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8782 << FD << getLangOpts().CPlusPlus11;
8783 }
8784 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008785}
8786
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008787//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8788
8789/// Check for comparisons of floating point operands using != and ==.
8790/// Issue a warning if these are no self-comparisons, as they are not likely
8791/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008792void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008793 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8794 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008795
8796 // Special case: check for x == x (which is OK).
8797 // Do not emit warnings for such cases.
8798 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8799 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8800 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008801 return;
Mike Stump11289f42009-09-09 15:08:12 +00008802
Ted Kremenekeda40e22007-11-29 00:59:04 +00008803 // Special case: check for comparisons against literals that can be exactly
8804 // represented by APFloat. In such cases, do not emit a warning. This
8805 // is a heuristic: often comparison against such literals are used to
8806 // detect if a value in a variable has not changed. This clearly can
8807 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008808 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8809 if (FLL->isExact())
8810 return;
8811 } else
8812 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8813 if (FLR->isExact())
8814 return;
Mike Stump11289f42009-09-09 15:08:12 +00008815
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008816 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008817 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008818 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008819 return;
Mike Stump11289f42009-09-09 15:08:12 +00008820
David Blaikie1f4ff152012-07-16 20:47:22 +00008821 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008822 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008823 return;
Mike Stump11289f42009-09-09 15:08:12 +00008824
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008825 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008826 Diag(Loc, diag::warn_floatingpoint_eq)
8827 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008828}
John McCallca01b222010-01-04 23:21:16 +00008829
John McCall70aa5392010-01-06 05:24:50 +00008830//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8831//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008832
John McCall70aa5392010-01-06 05:24:50 +00008833namespace {
John McCallca01b222010-01-04 23:21:16 +00008834
John McCall70aa5392010-01-06 05:24:50 +00008835/// Structure recording the 'active' range of an integer-valued
8836/// expression.
8837struct IntRange {
8838 /// The number of bits active in the int.
8839 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008840
John McCall70aa5392010-01-06 05:24:50 +00008841 /// True if the int is known not to have negative values.
8842 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008843
John McCall70aa5392010-01-06 05:24:50 +00008844 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008845 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008846
John McCall817d4af2010-11-10 23:38:19 +00008847 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008848 static IntRange forBoolType() {
8849 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008850 }
8851
John McCall817d4af2010-11-10 23:38:19 +00008852 /// Returns the range of an opaque value of the given integral type.
8853 static IntRange forValueOfType(ASTContext &C, QualType T) {
8854 return forValueOfCanonicalType(C,
8855 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008856 }
8857
John McCall817d4af2010-11-10 23:38:19 +00008858 /// Returns the range of an opaque value of a canonical integral type.
8859 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008860 assert(T->isCanonicalUnqualified());
8861
8862 if (const VectorType *VT = dyn_cast<VectorType>(T))
8863 T = VT->getElementType().getTypePtr();
8864 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8865 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008866 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8867 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008868
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008869 if (!C.getLangOpts().CPlusPlus) {
8870 // For enum types in C code, use the underlying datatype.
8871 if (const EnumType *ET = dyn_cast<EnumType>(T))
8872 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8873 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8874 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008875 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008876 // In C++11, enums can have a fixed underlying type. Use this type to
8877 // compute the range.
8878 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008879 return IntRange(C.getIntWidth(QualType(T, 0)),
8880 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008881 }
John McCall18a2c2c2010-11-09 22:22:12 +00008882
David Majnemer6a426652013-06-07 22:07:20 +00008883 unsigned NumPositive = Enum->getNumPositiveBits();
8884 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008885
David Majnemer6a426652013-06-07 22:07:20 +00008886 if (NumNegative == 0)
8887 return IntRange(NumPositive, true/*NonNegative*/);
8888 else
8889 return IntRange(std::max(NumPositive + 1, NumNegative),
8890 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008891 }
John McCall70aa5392010-01-06 05:24:50 +00008892
8893 const BuiltinType *BT = cast<BuiltinType>(T);
8894 assert(BT->isInteger());
8895
8896 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8897 }
8898
John McCall817d4af2010-11-10 23:38:19 +00008899 /// Returns the "target" range of a canonical integral type, i.e.
8900 /// the range of values expressible in the type.
8901 ///
8902 /// This matches forValueOfCanonicalType except that enums have the
8903 /// full range of their type, not the range of their enumerators.
8904 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8905 assert(T->isCanonicalUnqualified());
8906
8907 if (const VectorType *VT = dyn_cast<VectorType>(T))
8908 T = VT->getElementType().getTypePtr();
8909 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8910 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008911 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8912 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008913 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008914 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008915
8916 const BuiltinType *BT = cast<BuiltinType>(T);
8917 assert(BT->isInteger());
8918
8919 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8920 }
8921
8922 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008923 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008924 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008925 L.NonNegative && R.NonNegative);
8926 }
8927
John McCall817d4af2010-11-10 23:38:19 +00008928 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008929 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008930 return IntRange(std::min(L.Width, R.Width),
8931 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008932 }
8933};
8934
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008935} // namespace
8936
8937static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8938 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008939 if (value.isSigned() && value.isNegative())
8940 return IntRange(value.getMinSignedBits(), false);
8941
8942 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008943 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008944
8945 // isNonNegative() just checks the sign bit without considering
8946 // signedness.
8947 return IntRange(value.getActiveBits(), true);
8948}
8949
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008950static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8951 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008952 if (result.isInt())
8953 return GetValueRange(C, result.getInt(), MaxWidth);
8954
8955 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008956 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8957 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8958 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8959 R = IntRange::join(R, El);
8960 }
John McCall70aa5392010-01-06 05:24:50 +00008961 return R;
8962 }
8963
8964 if (result.isComplexInt()) {
8965 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8966 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8967 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008968 }
8969
8970 // This can happen with lossless casts to intptr_t of "based" lvalues.
8971 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008972 // FIXME: The only reason we need to pass the type in here is to get
8973 // the sign right on this one case. It would be nice if APValue
8974 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008975 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008976 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008977}
John McCall70aa5392010-01-06 05:24:50 +00008978
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008979static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008980 QualType Ty = E->getType();
8981 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8982 Ty = AtomicRHS->getValueType();
8983 return Ty;
8984}
8985
John McCall70aa5392010-01-06 05:24:50 +00008986/// Pseudo-evaluate the given integer expression, estimating the
8987/// range of values it might take.
8988///
8989/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008990static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008991 E = E->IgnoreParens();
8992
8993 // Try a full evaluation first.
8994 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008995 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008996 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008997
8998 // I think we only want to look through implicit casts here; if the
8999 // user has an explicit widening cast, we should treat the value as
9000 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009001 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00009002 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00009003 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9004
Eli Friedmane6d33952013-07-08 20:20:06 +00009005 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00009006
George Burgess IVdf1ed002016-01-13 01:52:39 +00009007 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9008 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00009009
John McCall70aa5392010-01-06 05:24:50 +00009010 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00009011 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00009012 return OutputTypeRange;
9013
9014 IntRange SubRange
9015 = GetExprRange(C, CE->getSubExpr(),
9016 std::min(MaxWidth, OutputTypeRange.Width));
9017
9018 // Bail out if the subexpr's range is as wide as the cast type.
9019 if (SubRange.Width >= OutputTypeRange.Width)
9020 return OutputTypeRange;
9021
9022 // Otherwise, we take the smaller width, and we're non-negative if
9023 // either the output type or the subexpr is.
9024 return IntRange(SubRange.Width,
9025 SubRange.NonNegative || OutputTypeRange.NonNegative);
9026 }
9027
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009028 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009029 // If we can fold the condition, just take that operand.
9030 bool CondResult;
9031 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9032 return GetExprRange(C, CondResult ? CO->getTrueExpr()
9033 : CO->getFalseExpr(),
9034 MaxWidth);
9035
9036 // Otherwise, conservatively merge.
9037 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9038 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9039 return IntRange::join(L, R);
9040 }
9041
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009042 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009043 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00009044 case BO_Cmp:
9045 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00009046
9047 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00009048 case BO_LAnd:
9049 case BO_LOr:
9050 case BO_LT:
9051 case BO_GT:
9052 case BO_LE:
9053 case BO_GE:
9054 case BO_EQ:
9055 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00009056 return IntRange::forBoolType();
9057
John McCallc3688382011-07-13 06:35:24 +00009058 // The type of the assignments is the type of the LHS, so the RHS
9059 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00009060 case BO_MulAssign:
9061 case BO_DivAssign:
9062 case BO_RemAssign:
9063 case BO_AddAssign:
9064 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00009065 case BO_XorAssign:
9066 case BO_OrAssign:
9067 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00009068 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00009069
John McCallc3688382011-07-13 06:35:24 +00009070 // Simple assignments just pass through the RHS, which will have
9071 // been coerced to the LHS type.
9072 case BO_Assign:
9073 // TODO: bitfields?
9074 return GetExprRange(C, BO->getRHS(), MaxWidth);
9075
John McCall70aa5392010-01-06 05:24:50 +00009076 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009077 case BO_PtrMemD:
9078 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00009079 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009080
John McCall2ce81ad2010-01-06 22:07:33 +00009081 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00009082 case BO_And:
9083 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00009084 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9085 GetExprRange(C, BO->getRHS(), MaxWidth));
9086
John McCall70aa5392010-01-06 05:24:50 +00009087 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00009088 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00009089 // ...except that we want to treat '1 << (blah)' as logically
9090 // positive. It's an important idiom.
9091 if (IntegerLiteral *I
9092 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9093 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009094 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00009095 return IntRange(R.Width, /*NonNegative*/ true);
9096 }
9097 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00009098 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00009099
John McCalle3027922010-08-25 11:45:40 +00009100 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00009101 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009102
John McCall2ce81ad2010-01-06 22:07:33 +00009103 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00009104 case BO_Shr:
9105 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00009106 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9107
9108 // If the shift amount is a positive constant, drop the width by
9109 // that much.
9110 llvm::APSInt shift;
9111 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9112 shift.isNonNegative()) {
9113 unsigned zext = shift.getZExtValue();
9114 if (zext >= L.Width)
9115 L.Width = (L.NonNegative ? 0 : 1);
9116 else
9117 L.Width -= zext;
9118 }
9119
9120 return L;
9121 }
9122
9123 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00009124 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00009125 return GetExprRange(C, BO->getRHS(), MaxWidth);
9126
John McCall2ce81ad2010-01-06 22:07:33 +00009127 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00009128 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00009129 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00009130 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009131 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00009132
John McCall51431812011-07-14 22:39:48 +00009133 // The width of a division result is mostly determined by the size
9134 // of the LHS.
9135 case BO_Div: {
9136 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009137 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009138 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9139
9140 // If the divisor is constant, use that.
9141 llvm::APSInt divisor;
9142 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9143 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9144 if (log2 >= L.Width)
9145 L.Width = (L.NonNegative ? 0 : 1);
9146 else
9147 L.Width = std::min(L.Width - log2, MaxWidth);
9148 return L;
9149 }
9150
9151 // Otherwise, just use the LHS's width.
9152 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9153 return IntRange(L.Width, L.NonNegative && R.NonNegative);
9154 }
9155
9156 // The result of a remainder can't be larger than the result of
9157 // either side.
9158 case BO_Rem: {
9159 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00009160 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00009161 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9162 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9163
9164 IntRange meet = IntRange::meet(L, R);
9165 meet.Width = std::min(meet.Width, MaxWidth);
9166 return meet;
9167 }
9168
9169 // The default behavior is okay for these.
9170 case BO_Mul:
9171 case BO_Add:
9172 case BO_Xor:
9173 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00009174 break;
9175 }
9176
John McCall51431812011-07-14 22:39:48 +00009177 // The default case is to treat the operation as if it were closed
9178 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00009179 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9180 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9181 return IntRange::join(L, R);
9182 }
9183
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009184 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00009185 switch (UO->getOpcode()) {
9186 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00009187 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00009188 return IntRange::forBoolType();
9189
9190 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00009191 case UO_Deref:
9192 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00009193 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009194
9195 default:
9196 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9197 }
9198 }
9199
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009200 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00009201 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9202
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00009203 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00009204 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00009205 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00009206
Eli Friedmane6d33952013-07-08 20:20:06 +00009207 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00009208}
John McCall263a48b2010-01-04 23:31:57 +00009209
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009210static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009211 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009212}
9213
John McCall263a48b2010-01-04 23:31:57 +00009214/// Checks whether the given value, which currently has the given
9215/// source semantics, has the same value when coerced through the
9216/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009217static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9218 const llvm::fltSemantics &Src,
9219 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009220 llvm::APFloat truncated = value;
9221
9222 bool ignored;
9223 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9224 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9225
9226 return truncated.bitwiseIsEqual(value);
9227}
9228
9229/// Checks whether the given value, which currently has the given
9230/// source semantics, has the same value when coerced through the
9231/// target semantics.
9232///
9233/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009234static bool IsSameFloatAfterCast(const APValue &value,
9235 const llvm::fltSemantics &Src,
9236 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009237 if (value.isFloat())
9238 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9239
9240 if (value.isVector()) {
9241 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9242 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9243 return false;
9244 return true;
9245 }
9246
9247 assert(value.isComplexFloat());
9248 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9249 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9250}
9251
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009252static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009253
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009254static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009255 // Suppress cases where we are comparing against an enum constant.
9256 if (const DeclRefExpr *DR =
9257 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9258 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009259 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009260
9261 // Suppress cases where the '0' value is expanded from a macro.
9262 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009263 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009264
Roman Lebedev6de129e2017-10-15 20:13:17 +00009265 return false;
9266}
9267
Richard Smith692f66ab2017-12-06 19:23:19 +00009268static bool isKnownToHaveUnsignedValue(Expr *E) {
9269 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009270 (!E->getType()->isSignedIntegerType() ||
9271 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9272}
9273
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009274namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009275/// The promoted range of values of a type. In general this has the
9276/// following structure:
9277///
9278/// |-----------| . . . |-----------|
9279/// ^ ^ ^ ^
9280/// Min HoleMin HoleMax Max
9281///
9282/// ... where there is only a hole if a signed type is promoted to unsigned
9283/// (in which case Min and Max are the smallest and largest representable
9284/// values).
9285struct PromotedRange {
9286 // Min, or HoleMax if there is a hole.
9287 llvm::APSInt PromotedMin;
9288 // Max, or HoleMin if there is a hole.
9289 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009290
Richard Smitha5370fb2017-12-08 22:57:11 +00009291 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9292 if (R.Width == 0)
9293 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9294 else if (R.Width >= BitWidth && !Unsigned) {
9295 // Promotion made the type *narrower*. This happens when promoting
9296 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9297 // Treat all values of 'signed int' as being in range for now.
9298 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9299 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9300 } else {
9301 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9302 .extOrTrunc(BitWidth);
9303 PromotedMin.setIsUnsigned(Unsigned);
9304
9305 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9306 .extOrTrunc(BitWidth);
9307 PromotedMax.setIsUnsigned(Unsigned);
9308 }
9309 }
9310
9311 // Determine whether this range is contiguous (has no hole).
9312 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9313
9314 // Where a constant value is within the range.
9315 enum ComparisonResult {
9316 LT = 0x1,
9317 LE = 0x2,
9318 GT = 0x4,
9319 GE = 0x8,
9320 EQ = 0x10,
9321 NE = 0x20,
9322 InRangeFlag = 0x40,
9323
9324 Less = LE | LT | NE,
9325 Min = LE | InRangeFlag,
9326 InRange = InRangeFlag,
9327 Max = GE | InRangeFlag,
9328 Greater = GE | GT | NE,
9329
9330 OnlyValue = LE | GE | EQ | InRangeFlag,
9331 InHole = NE
9332 };
9333
9334 ComparisonResult compare(const llvm::APSInt &Value) const {
9335 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9336 Value.isUnsigned() == PromotedMin.isUnsigned());
9337 if (!isContiguous()) {
9338 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9339 if (Value.isMinValue()) return Min;
9340 if (Value.isMaxValue()) return Max;
9341 if (Value >= PromotedMin) return InRange;
9342 if (Value <= PromotedMax) return InRange;
9343 return InHole;
9344 }
9345
9346 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9347 case -1: return Less;
9348 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9349 case 1:
9350 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9351 case -1: return InRange;
9352 case 0: return Max;
9353 case 1: return Greater;
9354 }
9355 }
9356
9357 llvm_unreachable("impossible compare result");
9358 }
9359
Richard Smithc70f1d62017-12-14 15:16:18 +00009360 static llvm::Optional<StringRef>
9361 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9362 if (Op == BO_Cmp) {
9363 ComparisonResult LTFlag = LT, GTFlag = GT;
9364 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9365
9366 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9367 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9368 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9369 return llvm::None;
9370 }
9371
Richard Smitha5370fb2017-12-08 22:57:11 +00009372 ComparisonResult TrueFlag, FalseFlag;
9373 if (Op == BO_EQ) {
9374 TrueFlag = EQ;
9375 FalseFlag = NE;
9376 } else if (Op == BO_NE) {
9377 TrueFlag = NE;
9378 FalseFlag = EQ;
9379 } else {
9380 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9381 TrueFlag = LT;
9382 FalseFlag = GE;
9383 } else {
9384 TrueFlag = GT;
9385 FalseFlag = LE;
9386 }
9387 if (Op == BO_GE || Op == BO_LE)
9388 std::swap(TrueFlag, FalseFlag);
9389 }
9390 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009391 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009392 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009393 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009394 return llvm::None;
9395 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009396};
John McCallcc7e5bf2010-05-06 08:58:33 +00009397}
9398
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009399static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009400 // Strip off implicit integral promotions.
9401 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009402 if (ICE->getCastKind() != CK_IntegralCast &&
9403 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009404 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009405 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009406 }
9407
9408 return E->getType()->isEnumeralType();
9409}
9410
Richard Smith692f66ab2017-12-06 19:23:19 +00009411static int classifyConstantValue(Expr *Constant) {
9412 // The values of this enumeration are used in the diagnostics
9413 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9414 enum ConstantValueKind {
9415 Miscellaneous = 0,
9416 LiteralTrue,
9417 LiteralFalse
9418 };
9419 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9420 return BL->getValue() ? ConstantValueKind::LiteralTrue
9421 : ConstantValueKind::LiteralFalse;
9422 return ConstantValueKind::Miscellaneous;
9423}
9424
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009425static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9426 Expr *Constant, Expr *Other,
9427 const llvm::APSInt &Value,
9428 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009429 if (S.inTemplateInstantiation())
9430 return false;
9431
Richard Smitha5370fb2017-12-08 22:57:11 +00009432 Expr *OriginalOther = Other;
9433
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009434 Constant = Constant->IgnoreParenImpCasts();
9435 Other = Other->IgnoreParenImpCasts();
9436
Richard Smitha5370fb2017-12-08 22:57:11 +00009437 // Suppress warnings on tautological comparisons between values of the same
9438 // enumeration type. There are only two ways we could warn on this:
9439 // - If the constant is outside the range of representable values of
9440 // the enumeration. In such a case, we should warn about the cast
9441 // to enumeration type, not about the comparison.
9442 // - If the constant is the maximum / minimum in-range value. For an
9443 // enumeratin type, such comparisons can be meaningful and useful.
9444 if (Constant->getType()->isEnumeralType() &&
9445 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9446 return false;
9447
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009448 // TODO: Investigate using GetExprRange() to get tighter bounds
9449 // on the bit ranges.
9450 QualType OtherT = Other->getType();
9451 if (const auto *AT = OtherT->getAs<AtomicType>())
9452 OtherT = AT->getValueType();
9453 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9454
9455 // Whether we're treating Other as being a bool because of the form of
9456 // expression despite it having another type (typically 'int' in C).
9457 bool OtherIsBooleanDespiteType =
9458 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9459 if (OtherIsBooleanDespiteType)
9460 OtherRange = IntRange::forBoolType();
9461
Richard Smitha5370fb2017-12-08 22:57:11 +00009462 // Determine the promoted range of the other type and see if a comparison of
9463 // the constant against that range is tautological.
9464 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9465 Value.isUnsigned());
9466 auto Cmp = OtherPromotedRange.compare(Value);
9467 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9468 if (!Result)
9469 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009470
Richard Smitha5370fb2017-12-08 22:57:11 +00009471 // Suppress the diagnostic for an in-range comparison if the constant comes
9472 // from a macro or enumerator. We don't want to diagnose
9473 //
9474 // some_long_value <= INT_MAX
9475 //
9476 // when sizeof(int) == sizeof(long).
9477 bool InRange = Cmp & PromotedRange::InRangeFlag;
9478 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9479 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009480
9481 // If this is a comparison to an enum constant, include that
9482 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009483 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009484 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9485 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9486
Richard Smitha5370fb2017-12-08 22:57:11 +00009487 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009488 SmallString<64> PrettySourceValue;
9489 llvm::raw_svector_ostream OS(PrettySourceValue);
9490 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009491 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009492 else
9493 OS << Value;
9494
Richard Smitha5370fb2017-12-08 22:57:11 +00009495 // FIXME: We use a somewhat different formatting for the in-range cases and
9496 // cases involving boolean values for historical reasons. We should pick a
9497 // consistent way of presenting these diagnostics.
9498 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9499 S.DiagRuntimeBehavior(
9500 E->getOperatorLoc(), E,
9501 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9502 : diag::warn_tautological_bool_compare)
9503 << OS.str() << classifyConstantValue(Constant)
9504 << OtherT << OtherIsBooleanDespiteType << *Result
9505 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9506 } else {
9507 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9508 ? (HasEnumType(OriginalOther)
9509 ? diag::warn_unsigned_enum_always_true_comparison
9510 : diag::warn_unsigned_always_true_comparison)
9511 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009512
Richard Smitha5370fb2017-12-08 22:57:11 +00009513 S.Diag(E->getOperatorLoc(), Diag)
9514 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9515 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9516 }
9517
9518 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009519}
9520
John McCallcc7e5bf2010-05-06 08:58:33 +00009521/// Analyze the operands of the given comparison. Implements the
9522/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009523static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009524 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9525 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009526}
John McCall263a48b2010-01-04 23:31:57 +00009527
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009528/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009529///
Richard Trieu82402a02011-09-15 21:56:47 +00009530/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009531static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009532 // The type the comparison is being performed in.
9533 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009534
9535 // Only analyze comparison operators where both sides have been converted to
9536 // the same type.
9537 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9538 return AnalyzeImpConvsInComparison(S, E);
9539
9540 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009541 if (E->isValueDependent())
9542 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009543
Roman Lebedev6de129e2017-10-15 20:13:17 +00009544 Expr *LHS = E->getLHS();
9545 Expr *RHS = E->getRHS();
9546
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009547 if (T->isIntegralType(S.Context)) {
9548 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009549 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009550
Roman Lebedev6de129e2017-10-15 20:13:17 +00009551 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9552 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009553
Roman Lebedev6de129e2017-10-15 20:13:17 +00009554 // We don't care about expressions whose result is a constant.
9555 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9556 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009557
Roman Lebedev6de129e2017-10-15 20:13:17 +00009558 // We only care about expressions where just one side is literal
9559 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9560 // Is the constant on the RHS or LHS?
9561 const bool RhsConstant = IsRHSIntegralLiteral;
9562 Expr *Const = RhsConstant ? RHS : LHS;
9563 Expr *Other = RhsConstant ? LHS : RHS;
9564 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9565
9566 // Check whether an integer constant comparison results in a value
9567 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009568 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9569 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009570 }
9571 }
9572
9573 if (!T->hasUnsignedIntegerRepresentation()) {
9574 // We don't do anything special if this isn't an unsigned integral
9575 // comparison: we're only interested in integral comparisons, and
9576 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009577 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009578 }
9579
9580 LHS = LHS->IgnoreParenImpCasts();
9581 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009582
Alex Lorenzb57409f2018-02-07 20:45:39 +00009583 if (!S.getLangOpts().CPlusPlus) {
9584 // Avoid warning about comparison of integers with different signs when
9585 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9586 // the type of `E`.
9587 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9588 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9589 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9590 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9591 }
9592
John McCallcc7e5bf2010-05-06 08:58:33 +00009593 // Check to see if one of the (unmodified) operands is of different
9594 // signedness.
9595 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009596 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9597 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009598 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009599 signedOperand = LHS;
9600 unsignedOperand = RHS;
9601 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9602 signedOperand = RHS;
9603 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009604 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009605 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009606 }
9607
John McCallcc7e5bf2010-05-06 08:58:33 +00009608 // Otherwise, calculate the effective range of the signed operand.
9609 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009610
John McCallcc7e5bf2010-05-06 08:58:33 +00009611 // Go ahead and analyze implicit conversions in the operands. Note
9612 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009613 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9614 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009615
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009616 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009617 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009618 return;
John McCallca01b222010-01-04 23:21:16 +00009619
9620 // For (in)equality comparisons, if the unsigned operand is a
9621 // constant which cannot collide with a overflowed signed operand,
9622 // then reinterpreting the signed operand as unsigned will not
9623 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009624 if (E->isEqualityOp()) {
9625 unsigned comparisonWidth = S.Context.getIntWidth(T);
9626 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009627
John McCallcc7e5bf2010-05-06 08:58:33 +00009628 // We should never be unable to prove that the unsigned operand is
9629 // non-negative.
9630 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9631
9632 if (unsignedRange.Width < comparisonWidth)
9633 return;
9634 }
9635
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009636 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9637 S.PDiag(diag::warn_mixed_sign_comparison)
9638 << LHS->getType() << RHS->getType()
9639 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009640}
9641
John McCall1f425642010-11-11 03:21:53 +00009642/// Analyzes an attempt to assign the given value to a bitfield.
9643///
9644/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009645static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9646 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009647 assert(Bitfield->isBitField());
9648 if (Bitfield->isInvalidDecl())
9649 return false;
9650
John McCalldeebbcf2010-11-11 05:33:51 +00009651 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009652 QualType BitfieldType = Bitfield->getType();
9653 if (BitfieldType->isBooleanType())
9654 return false;
9655
9656 if (BitfieldType->isEnumeralType()) {
9657 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9658 // If the underlying enum type was not explicitly specified as an unsigned
9659 // type and the enum contain only positive values, MSVC++ will cause an
9660 // inconsistency by storing this as a signed type.
9661 if (S.getLangOpts().CPlusPlus11 &&
9662 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9663 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9664 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9665 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9666 << BitfieldEnumDecl->getNameAsString();
9667 }
9668 }
9669
John McCalldeebbcf2010-11-11 05:33:51 +00009670 if (Bitfield->getType()->isBooleanType())
9671 return false;
9672
Douglas Gregor789adec2011-02-04 13:09:01 +00009673 // Ignore value- or type-dependent expressions.
9674 if (Bitfield->getBitWidth()->isValueDependent() ||
9675 Bitfield->getBitWidth()->isTypeDependent() ||
9676 Init->isValueDependent() ||
9677 Init->isTypeDependent())
9678 return false;
9679
John McCall1f425642010-11-11 03:21:53 +00009680 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009681 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009682
Richard Smith5fab0c92011-12-28 19:48:30 +00009683 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009684 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9685 Expr::SE_AllowSideEffects)) {
9686 // The RHS is not constant. If the RHS has an enum type, make sure the
9687 // bitfield is wide enough to hold all the values of the enum without
9688 // truncation.
9689 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9690 EnumDecl *ED = EnumTy->getDecl();
9691 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9692
9693 // Enum types are implicitly signed on Windows, so check if there are any
9694 // negative enumerators to see if the enum was intended to be signed or
9695 // not.
9696 bool SignedEnum = ED->getNumNegativeBits() > 0;
9697
9698 // Check for surprising sign changes when assigning enum values to a
9699 // bitfield of different signedness. If the bitfield is signed and we
9700 // have exactly the right number of bits to store this unsigned enum,
9701 // suggest changing the enum to an unsigned type. This typically happens
9702 // on Windows where unfixed enums always use an underlying type of 'int'.
9703 unsigned DiagID = 0;
9704 if (SignedEnum && !SignedBitfield) {
9705 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9706 } else if (SignedBitfield && !SignedEnum &&
9707 ED->getNumPositiveBits() == FieldWidth) {
9708 DiagID = diag::warn_signed_bitfield_enum_conversion;
9709 }
9710
9711 if (DiagID) {
9712 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9713 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9714 SourceRange TypeRange =
9715 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9716 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9717 << SignedEnum << TypeRange;
9718 }
9719
9720 // Compute the required bitwidth. If the enum has negative values, we need
9721 // one more bit than the normal number of positive bits to represent the
9722 // sign bit.
9723 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9724 ED->getNumNegativeBits())
9725 : ED->getNumPositiveBits();
9726
9727 // Check the bitwidth.
9728 if (BitsNeeded > FieldWidth) {
9729 Expr *WidthExpr = Bitfield->getBitWidth();
9730 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9731 << Bitfield << ED;
9732 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9733 << BitsNeeded << ED << WidthExpr->getSourceRange();
9734 }
9735 }
9736
John McCall1f425642010-11-11 03:21:53 +00009737 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009738 }
John McCall1f425642010-11-11 03:21:53 +00009739
John McCall1f425642010-11-11 03:21:53 +00009740 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009741
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009742 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009743 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009744 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9745 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009746
John McCall1f425642010-11-11 03:21:53 +00009747 if (OriginalWidth <= FieldWidth)
9748 return false;
9749
Eli Friedmanc267a322012-01-26 23:11:39 +00009750 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009751 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009752 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009753
Eli Friedmanc267a322012-01-26 23:11:39 +00009754 // Check whether the stored value is equal to the original value.
9755 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009756 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009757 return false;
9758
Eli Friedmanc267a322012-01-26 23:11:39 +00009759 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009760 // therefore don't strictly fit into a signed bitfield of width 1.
9761 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009762 return false;
9763
John McCall1f425642010-11-11 03:21:53 +00009764 std::string PrettyValue = Value.toString(10);
9765 std::string PrettyTrunc = TruncatedValue.toString(10);
9766
9767 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9768 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9769 << Init->getSourceRange();
9770
9771 return true;
9772}
9773
John McCalld2a53122010-11-09 23:24:47 +00009774/// Analyze the given simple or compound assignment for warning-worthy
9775/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009776static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009777 // Just recurse on the LHS.
9778 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9779
9780 // We want to recurse on the RHS as normal unless we're assigning to
9781 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009782 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009783 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009784 E->getOperatorLoc())) {
9785 // Recurse, ignoring any implicit conversions on the RHS.
9786 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9787 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009788 }
9789 }
9790
9791 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9792}
9793
John McCall263a48b2010-01-04 23:31:57 +00009794/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009795static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9796 SourceLocation CContext, unsigned diag,
9797 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009798 if (pruneControlFlow) {
9799 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9800 S.PDiag(diag)
9801 << SourceType << T << E->getSourceRange()
9802 << SourceRange(CContext));
9803 return;
9804 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009805 S.Diag(E->getExprLoc(), diag)
9806 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9807}
9808
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009809/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009810static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9811 SourceLocation CContext,
9812 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009813 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009814}
9815
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009816/// Analyze the given compound assignment for the possible losing of
9817/// floating-point precision.
9818static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9819 assert(isa<CompoundAssignOperator>(E) &&
9820 "Must be compound assignment operation");
9821 // Recurse on the LHS and RHS in here
9822 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9823 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9824
9825 // Now check the outermost expression
9826 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9827 const auto *RBT = cast<CompoundAssignOperator>(E)
9828 ->getComputationResultType()
9829 ->getAs<BuiltinType>();
9830
9831 // If both source and target are floating points.
9832 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9833 // Builtin FP kinds are ordered by increasing FP rank.
9834 if (ResultBT->getKind() < RBT->getKind())
9835 // We don't want to warn for system macro.
9836 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9837 // warn about dropping FP rank.
9838 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9839 E->getOperatorLoc(),
9840 diag::warn_impcast_float_result_precision);
9841}
Richard Trieube234c32016-04-21 21:04:55 +00009842
9843/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009844static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9845 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009846 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009847 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009848
9849 Expr *InnerE = E->IgnoreParenImpCasts();
9850 // We also want to warn on, e.g., "int i = -1.234"
9851 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9852 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9853 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9854
9855 const bool IsLiteral =
9856 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9857
9858 llvm::APFloat Value(0.0);
9859 bool IsConstant =
9860 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9861 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009862 return DiagnoseImpCast(S, E, T, CContext,
9863 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009864 }
9865
Chandler Carruth016ef402011-04-10 08:36:24 +00009866 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009867
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009868 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9869 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009870 llvm::APFloat::opStatus Result = Value.convertToInteger(
9871 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9872
9873 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009874 if (IsLiteral) return;
9875 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9876 PruneWarnings);
9877 }
9878
Erich Keanea4c48c62018-05-08 21:26:21 +00009879 // Conversion of a floating-point value to a non-bool integer where the
9880 // integral part cannot be represented by the integer type is undefined.
9881 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9882 return DiagnoseImpCast(
9883 S, E, T, CContext,
9884 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
Richard Trieua2b8fe62018-05-14 23:21:48 +00009885 : diag::warn_impcast_float_to_integer_out_of_range,
9886 PruneWarnings);
Erich Keanea4c48c62018-05-08 21:26:21 +00009887
Richard Trieube234c32016-04-21 21:04:55 +00009888 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009889 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009890 // Warn on floating point literal to integer.
9891 DiagID = diag::warn_impcast_literal_float_to_integer;
9892 } else if (IntegerValue == 0) {
9893 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9894 return DiagnoseImpCast(S, E, T, CContext,
9895 diag::warn_impcast_float_integer, PruneWarnings);
9896 }
9897 // Warn on non-zero to zero conversion.
9898 DiagID = diag::warn_impcast_float_to_integer_zero;
9899 } else {
9900 if (IntegerValue.isUnsigned()) {
9901 if (!IntegerValue.isMaxValue()) {
9902 return DiagnoseImpCast(S, E, T, CContext,
9903 diag::warn_impcast_float_integer, PruneWarnings);
9904 }
9905 } else { // IntegerValue.isSigned()
9906 if (!IntegerValue.isMaxSignedValue() &&
9907 !IntegerValue.isMinSignedValue()) {
9908 return DiagnoseImpCast(S, E, T, CContext,
9909 diag::warn_impcast_float_integer, PruneWarnings);
9910 }
9911 }
9912 // Warn on evaluatable floating point expression to integer conversion.
9913 DiagID = diag::warn_impcast_float_to_integer;
9914 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009915
Eli Friedman07185912013-08-29 23:44:43 +00009916 // FIXME: Force the precision of the source value down so we don't print
9917 // digits which are usually useless (we don't really care here if we
9918 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9919 // would automatically print the shortest representation, but it's a bit
9920 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009921 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009922 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9923 precision = (precision * 59 + 195) / 196;
9924 Value.toString(PrettySourceValue, precision);
9925
David Blaikie9b88cc02012-05-15 17:18:27 +00009926 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009927 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009928 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009929 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009930 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009931
Richard Trieube234c32016-04-21 21:04:55 +00009932 if (PruneWarnings) {
9933 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9934 S.PDiag(DiagID)
9935 << E->getType() << T.getUnqualifiedType()
9936 << PrettySourceValue << PrettyTargetValue
9937 << E->getSourceRange() << SourceRange(CContext));
9938 } else {
9939 S.Diag(E->getExprLoc(), DiagID)
9940 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9941 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9942 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009943}
9944
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009945static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9946 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009947 if (!Range.Width) return "0";
9948
9949 llvm::APSInt ValueInRange = Value;
9950 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009951 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009952 return ValueInRange.toString(10);
9953}
9954
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009955static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009956 if (!isa<ImplicitCastExpr>(Ex))
9957 return false;
9958
9959 Expr *InnerE = Ex->IgnoreParenImpCasts();
9960 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9961 const Type *Source =
9962 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9963 if (Target->isDependentType())
9964 return false;
9965
9966 const BuiltinType *FloatCandidateBT =
9967 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9968 const Type *BoolCandidateType = ToBool ? Target : Source;
9969
9970 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9971 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9972}
9973
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009974static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9975 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009976 unsigned NumArgs = TheCall->getNumArgs();
9977 for (unsigned i = 0; i < NumArgs; ++i) {
9978 Expr *CurrA = TheCall->getArg(i);
9979 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9980 continue;
9981
9982 bool IsSwapped = ((i > 0) &&
9983 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9984 IsSwapped |= ((i < (NumArgs - 1)) &&
9985 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9986 if (IsSwapped) {
9987 // Warn on this floating-point to bool conversion.
9988 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9989 CurrA->getType(), CC,
9990 diag::warn_impcast_floating_point_to_bool);
9991 }
9992 }
9993}
9994
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009995static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9996 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009997 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9998 E->getExprLoc()))
9999 return;
10000
Richard Trieu09d6b802016-01-08 23:35:06 +000010001 // Don't warn on functions which have return type nullptr_t.
10002 if (isa<CallExpr>(E))
10003 return;
10004
Richard Trieu5b993502014-10-15 03:42:06 +000010005 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10006 const Expr::NullPointerConstantKind NullKind =
10007 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10008 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10009 return;
10010
10011 // Return if target type is a safe conversion.
10012 if (T->isAnyPointerType() || T->isBlockPointerType() ||
10013 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10014 return;
10015
10016 SourceLocation Loc = E->getSourceRange().getBegin();
10017
Richard Trieu0a5e1662016-02-13 00:58:53 +000010018 // Venture through the macro stacks to get to the source of macro arguments.
10019 // The new location is a better location than the complete location that was
10020 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +000010021 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10022 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +000010023
Richard Trieu5b993502014-10-15 03:42:06 +000010024 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +000010025 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10026 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10027 Loc, S.SourceMgr, S.getLangOpts());
10028 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +000010029 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +000010030 }
10031
10032 // Only warn if the null and context location are in the same macro expansion.
10033 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10034 return;
10035
10036 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010037 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +000010038 << FixItHint::CreateReplacement(Loc,
10039 S.getFixItZeroLiteralForType(T, Loc));
10040}
10041
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010042static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10043 ObjCArrayLiteral *ArrayLiteral);
10044
10045static void
10046checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10047 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +000010048
10049/// Check a single element within a collection literal against the
10050/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010051static void checkObjCCollectionLiteralElement(Sema &S,
10052 QualType TargetElementType,
10053 Expr *Element,
10054 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010055 // Skip a bitcast to 'id' or qualified 'id'.
10056 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10057 if (ICE->getCastKind() == CK_BitCast &&
10058 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10059 Element = ICE->getSubExpr();
10060 }
10061
10062 QualType ElementType = Element->getType();
10063 ExprResult ElementResult(Element);
10064 if (ElementType->getAs<ObjCObjectPointerType>() &&
10065 S.CheckSingleAssignmentConstraints(TargetElementType,
10066 ElementResult,
10067 false, false)
10068 != Sema::Compatible) {
10069 S.Diag(Element->getLocStart(),
10070 diag::warn_objc_collection_literal_element)
10071 << ElementType << ElementKind << TargetElementType
10072 << Element->getSourceRange();
10073 }
10074
10075 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10076 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10077 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10078 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10079}
10080
10081/// Check an Objective-C array literal being converted to the given
10082/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010083static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10084 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010085 if (!S.NSArrayDecl)
10086 return;
10087
10088 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10089 if (!TargetObjCPtr)
10090 return;
10091
10092 if (TargetObjCPtr->isUnspecialized() ||
10093 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10094 != S.NSArrayDecl->getCanonicalDecl())
10095 return;
10096
10097 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10098 if (TypeArgs.size() != 1)
10099 return;
10100
10101 QualType TargetElementType = TypeArgs[0];
10102 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10103 checkObjCCollectionLiteralElement(S, TargetElementType,
10104 ArrayLiteral->getElement(I),
10105 0);
10106 }
10107}
10108
10109/// Check an Objective-C dictionary literal being converted to the given
10110/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010111static void
10112checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10113 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +000010114 if (!S.NSDictionaryDecl)
10115 return;
10116
10117 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10118 if (!TargetObjCPtr)
10119 return;
10120
10121 if (TargetObjCPtr->isUnspecialized() ||
10122 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10123 != S.NSDictionaryDecl->getCanonicalDecl())
10124 return;
10125
10126 auto TypeArgs = TargetObjCPtr->getTypeArgs();
10127 if (TypeArgs.size() != 2)
10128 return;
10129
10130 QualType TargetKeyType = TypeArgs[0];
10131 QualType TargetObjectType = TypeArgs[1];
10132 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10133 auto Element = DictionaryLiteral->getKeyValueElement(I);
10134 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10135 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10136 }
10137}
10138
Richard Trieufc404c72016-02-05 23:02:38 +000010139// Helper function to filter out cases for constant width constant conversion.
10140// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010141static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10142 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +000010143 // If initializing from a constant, and the constant starts with '0',
10144 // then it is a binary, octal, or hexadecimal. Allow these constants
10145 // to fill all the bits, even if there is a sign change.
10146 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10147 const char FirstLiteralCharacter =
10148 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
10149 if (FirstLiteralCharacter == '0')
10150 return false;
10151 }
10152
10153 // If the CC location points to a '{', and the type is char, then assume
10154 // assume it is an array initialization.
10155 if (CC.isValid() && T->isCharType()) {
10156 const char FirstContextCharacter =
10157 S.getSourceManager().getCharacterData(CC)[0];
10158 if (FirstContextCharacter == '{')
10159 return false;
10160 }
10161
10162 return true;
10163}
10164
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010165static void
10166CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10167 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010168 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +000010169
John McCallcc7e5bf2010-05-06 08:58:33 +000010170 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10171 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10172 if (Source == Target) return;
10173 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +000010174
Chandler Carruthc22845a2011-07-26 05:40:03 +000010175 // If the conversion context location is invalid don't complain. We also
10176 // don't want to emit a warning if the issue occurs from the expansion of
10177 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10178 // delay this check as long as possible. Once we detect we are in that
10179 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010180 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +000010181 return;
10182
Richard Trieu021baa32011-09-23 20:10:00 +000010183 // Diagnose implicit casts to bool.
10184 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10185 if (isa<StringLiteral>(E))
10186 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +000010187 // and expressions, for instance, assert(0 && "error here"), are
10188 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +000010189 return DiagnoseImpCast(S, E, T, CC,
10190 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +000010191 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10192 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10193 // This covers the literal expressions that evaluate to Objective-C
10194 // objects.
10195 return DiagnoseImpCast(S, E, T, CC,
10196 diag::warn_impcast_objective_c_literal_to_bool);
10197 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010198 if (Source->isPointerType() || Source->canDecayToPointerType()) {
10199 // Warn on pointer to bool conversion that is always true.
10200 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10201 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +000010202 }
Richard Trieu021baa32011-09-23 20:10:00 +000010203 }
John McCall263a48b2010-01-04 23:31:57 +000010204
Douglas Gregor5054cb02015-07-07 03:58:22 +000010205 // Check implicit casts from Objective-C collection literals to specialized
10206 // collection types, e.g., NSArray<NSString *> *.
10207 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10208 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10209 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10210 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10211
John McCall263a48b2010-01-04 23:31:57 +000010212 // Strip vector types.
10213 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010214 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010215 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010216 return;
John McCallacf0ee52010-10-08 02:01:28 +000010217 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010218 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010219
Chris Lattneree7286f2011-06-14 04:51:15 +000010220 // If the vector cast is cast between two vectors of the same size, it is
10221 // a bitcast, not a conversion.
10222 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10223 return;
John McCall263a48b2010-01-04 23:31:57 +000010224
10225 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10226 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10227 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010228 if (auto VecTy = dyn_cast<VectorType>(Target))
10229 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010230
10231 // Strip complex types.
10232 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010233 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010234 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010235 return;
10236
Tim Northover02416372017-08-08 23:18:05 +000010237 return DiagnoseImpCast(S, E, T, CC,
10238 S.getLangOpts().CPlusPlus
10239 ? diag::err_impcast_complex_scalar
10240 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010241 }
John McCall263a48b2010-01-04 23:31:57 +000010242
10243 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10244 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10245 }
10246
10247 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10248 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10249
10250 // If the source is floating point...
10251 if (SourceBT && SourceBT->isFloatingPoint()) {
10252 // ...and the target is floating point...
10253 if (TargetBT && TargetBT->isFloatingPoint()) {
10254 // ...then warn if we're dropping FP rank.
10255
10256 // Builtin FP kinds are ordered by increasing FP rank.
10257 if (SourceBT->getKind() > TargetBT->getKind()) {
10258 // Don't warn about float constants that are precisely
10259 // representable in the target type.
10260 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010261 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010262 // Value might be a float, a float vector, or a float complex.
10263 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010264 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10265 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010266 return;
10267 }
10268
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010269 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010270 return;
10271
John McCallacf0ee52010-10-08 02:01:28 +000010272 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010273 }
10274 // ... or possibly if we're increasing rank, too
10275 else if (TargetBT->getKind() > SourceBT->getKind()) {
10276 if (S.SourceMgr.isInSystemMacro(CC))
10277 return;
10278
10279 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010280 }
10281 return;
10282 }
10283
Richard Trieube234c32016-04-21 21:04:55 +000010284 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010285 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010286 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010287 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010288
Richard Trieube234c32016-04-21 21:04:55 +000010289 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010290 }
John McCall263a48b2010-01-04 23:31:57 +000010291
Richard Smith54894fd2015-12-30 01:06:52 +000010292 // Detect the case where a call result is converted from floating-point to
10293 // to bool, and the final argument to the call is converted from bool, to
10294 // discover this typo:
10295 //
10296 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10297 //
10298 // FIXME: This is an incredibly special case; is there some more general
10299 // way to detect this class of misplaced-parentheses bug?
10300 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010301 // Check last argument of function call to see if it is an
10302 // implicit cast from a type matching the type the result
10303 // is being cast to.
10304 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010305 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010306 Expr *LastA = CEx->getArg(NumArgs - 1);
10307 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010308 if (isa<ImplicitCastExpr>(LastA) &&
10309 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010310 // Warn on this floating-point to bool conversion
10311 DiagnoseImpCast(S, E, T, CC,
10312 diag::warn_impcast_floating_point_to_bool);
10313 }
10314 }
10315 }
John McCall263a48b2010-01-04 23:31:57 +000010316 return;
10317 }
10318
Richard Trieu5b993502014-10-15 03:42:06 +000010319 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010320
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010321 S.DiscardMisalignedMemberAddress(Target, E);
10322
David Blaikie9366d2b2012-06-19 21:19:06 +000010323 if (!Source->isIntegerType() || !Target->isIntegerType())
10324 return;
10325
David Blaikie7555b6a2012-05-15 16:56:36 +000010326 // TODO: remove this early return once the false positives for constant->bool
10327 // in templates, macros, etc, are reduced or removed.
10328 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10329 return;
10330
John McCallcc7e5bf2010-05-06 08:58:33 +000010331 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010332 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010333
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010334 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010335 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010336 // TODO: this should happen for bitfield stores, too.
10337 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010338 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010339 if (S.SourceMgr.isInSystemMacro(CC))
10340 return;
10341
John McCall18a2c2c2010-11-09 22:22:12 +000010342 std::string PrettySourceValue = Value.toString(10);
10343 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010344
Ted Kremenek33ba9952011-10-22 02:37:33 +000010345 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10346 S.PDiag(diag::warn_impcast_integer_precision_constant)
10347 << PrettySourceValue << PrettyTargetValue
10348 << E->getType() << T << E->getSourceRange()
10349 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010350 return;
10351 }
10352
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010353 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10354 if (S.SourceMgr.isInSystemMacro(CC))
10355 return;
10356
David Blaikie9455da02012-04-12 22:40:54 +000010357 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010358 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10359 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010360 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010361 }
10362
Richard Trieudcb55572016-01-29 23:51:16 +000010363 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10364 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10365 // Warn when doing a signed to signed conversion, warn if the positive
10366 // source value is exactly the width of the target type, which will
10367 // cause a negative value to be stored.
10368
10369 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010370 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10371 !S.SourceMgr.isInSystemMacro(CC)) {
10372 if (isSameWidthConstantConversion(S, E, T, CC)) {
10373 std::string PrettySourceValue = Value.toString(10);
10374 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010375
Richard Trieufc404c72016-02-05 23:02:38 +000010376 S.DiagRuntimeBehavior(
10377 E->getExprLoc(), E,
10378 S.PDiag(diag::warn_impcast_integer_precision_constant)
10379 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10380 << E->getSourceRange() << clang::SourceRange(CC));
10381 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010382 }
10383 }
Richard Trieufc404c72016-02-05 23:02:38 +000010384
Richard Trieudcb55572016-01-29 23:51:16 +000010385 // Fall through for non-constants to give a sign conversion warning.
10386 }
10387
John McCallcc7e5bf2010-05-06 08:58:33 +000010388 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10389 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10390 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010391 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010392 return;
10393
John McCallcc7e5bf2010-05-06 08:58:33 +000010394 unsigned DiagID = diag::warn_impcast_integer_sign;
10395
10396 // Traditionally, gcc has warned about this under -Wsign-compare.
10397 // We also want to warn about it in -Wconversion.
10398 // So if -Wconversion is off, use a completely identical diagnostic
10399 // in the sign-compare group.
10400 // The conditional-checking code will
10401 if (ICContext) {
10402 DiagID = diag::warn_impcast_integer_sign_conditional;
10403 *ICContext = true;
10404 }
10405
John McCallacf0ee52010-10-08 02:01:28 +000010406 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010407 }
10408
Douglas Gregora78f1932011-02-22 02:45:07 +000010409 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010410 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10411 // type, to give us better diagnostics.
10412 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010413 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010414 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10415 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10416 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10417 SourceType = S.Context.getTypeDeclType(Enum);
10418 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10419 }
10420 }
10421
Douglas Gregora78f1932011-02-22 02:45:07 +000010422 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10423 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010424 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10425 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010426 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010427 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010428 return;
10429
Douglas Gregor364f7db2011-03-12 00:14:31 +000010430 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010431 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010432 }
John McCall263a48b2010-01-04 23:31:57 +000010433}
10434
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010435static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10436 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010437
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010438static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10439 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010440 E = E->IgnoreParenImpCasts();
10441
10442 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010443 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010444
John McCallacf0ee52010-10-08 02:01:28 +000010445 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010446 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010447 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010448}
10449
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010450static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10451 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010452 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010453
10454 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010455 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10456 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010457
10458 // If -Wconversion would have warned about either of the candidates
10459 // for a signedness conversion to the context type...
10460 if (!Suspicious) return;
10461
10462 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010463 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010464 return;
10465
John McCallcc7e5bf2010-05-06 08:58:33 +000010466 // ...then check whether it would have warned about either of the
10467 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010468 if (E->getType() == T) return;
10469
10470 Suspicious = false;
10471 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10472 E->getType(), CC, &Suspicious);
10473 if (!Suspicious)
10474 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010475 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010476}
10477
Richard Trieu65724892014-11-15 06:37:39 +000010478/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10479/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010480static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010481 if (S.getLangOpts().Bool)
10482 return;
10483 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10484}
10485
John McCallcc7e5bf2010-05-06 08:58:33 +000010486/// AnalyzeImplicitConversions - Find and report any interesting
10487/// implicit conversions in the given expression. There are a couple
10488/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010489static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10490 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010491 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010492 Expr *E = OrigE->IgnoreParenImpCasts();
10493
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010494 if (E->isTypeDependent() || E->isValueDependent())
10495 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010496
John McCallcc7e5bf2010-05-06 08:58:33 +000010497 // For conditional operators, we analyze the arguments as if they
10498 // were being fed directly into the output.
10499 if (isa<ConditionalOperator>(E)) {
10500 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010501 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010502 return;
10503 }
10504
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010505 // Check implicit argument conversions for function calls.
10506 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10507 CheckImplicitArgumentConversions(S, Call, CC);
10508
John McCallcc7e5bf2010-05-06 08:58:33 +000010509 // Go ahead and check any implicit conversions we might have skipped.
10510 // The non-canonical typecheck is just an optimization;
10511 // CheckImplicitConversion will filter out dead implicit conversions.
10512 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010513 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010514
10515 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010516
10517 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10518 // The bound subexpressions in a PseudoObjectExpr are not reachable
10519 // as transitive children.
10520 // FIXME: Use a more uniform representation for this.
10521 for (auto *SE : POE->semantics())
10522 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10523 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010524 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010525
John McCallcc7e5bf2010-05-06 08:58:33 +000010526 // Skip past explicit casts.
10527 if (isa<ExplicitCastExpr>(E)) {
10528 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010529 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010530 }
10531
John McCalld2a53122010-11-09 23:24:47 +000010532 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10533 // Do a somewhat different check with comparison operators.
10534 if (BO->isComparisonOp())
10535 return AnalyzeComparison(S, BO);
10536
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010537 // And with simple assignments.
10538 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010539 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010540 // And with compound assignments.
10541 if (BO->isAssignmentOp())
10542 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010543 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010544
10545 // These break the otherwise-useful invariant below. Fortunately,
10546 // we don't really need to recurse into them, because any internal
10547 // expressions should have been analyzed already when they were
10548 // built into statements.
10549 if (isa<StmtExpr>(E)) return;
10550
10551 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010552 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010553
10554 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010555 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010556 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010557 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010558 for (Stmt *SubStmt : E->children()) {
10559 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010560 if (!ChildExpr)
10561 continue;
10562
Richard Trieu955231d2014-01-25 01:10:35 +000010563 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010564 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010565 // Ignore checking string literals that are in logical and operators.
10566 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010567 continue;
10568 AnalyzeImplicitConversions(S, ChildExpr, CC);
10569 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010570
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010571 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010572 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10573 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010574 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010575
10576 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10577 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010578 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010579 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010580
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010581 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10582 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010583 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010584}
10585
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010586/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010587static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10588 // Taking into account implicit conversions,
10589 // allow any integer.
10590 if (!E->getType()->isIntegerType()) {
10591 S.Diag(E->getLocStart(),
10592 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10593 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010594 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010595 // Potentially emit standard warnings for implicit conversions if enabled
10596 // using -Wconversion.
10597 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10598 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010599}
10600
Richard Trieuc1888e02014-06-28 23:25:37 +000010601// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10602// Returns true when emitting a warning about taking the address of a reference.
10603static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010604 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010605 E = E->IgnoreParenImpCasts();
10606
10607 const FunctionDecl *FD = nullptr;
10608
10609 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10610 if (!DRE->getDecl()->getType()->isReferenceType())
10611 return false;
10612 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10613 if (!M->getMemberDecl()->getType()->isReferenceType())
10614 return false;
10615 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010616 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010617 return false;
10618 FD = Call->getDirectCallee();
10619 } else {
10620 return false;
10621 }
10622
10623 SemaRef.Diag(E->getExprLoc(), PD);
10624
10625 // If possible, point to location of function.
10626 if (FD) {
10627 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10628 }
10629
10630 return true;
10631}
10632
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010633// Returns true if the SourceLocation is expanded from any macro body.
10634// Returns false if the SourceLocation is invalid, is from not in a macro
10635// expansion, or is from expanded from a top-level macro argument.
10636static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10637 if (Loc.isInvalid())
10638 return false;
10639
10640 while (Loc.isMacroID()) {
10641 if (SM.isMacroBodyExpansion(Loc))
10642 return true;
10643 Loc = SM.getImmediateMacroCallerLoc(Loc);
10644 }
10645
10646 return false;
10647}
10648
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010649/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010650/// \param E the expression containing the pointer
10651/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10652/// compared to a null pointer
10653/// \param IsEqual True when the comparison is equal to a null pointer
10654/// \param Range Extra SourceRange to highlight in the diagnostic
10655void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10656 Expr::NullPointerConstantKind NullKind,
10657 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010658 if (!E)
10659 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010660
10661 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010662 if (E->getExprLoc().isMacroID()) {
10663 const SourceManager &SM = getSourceManager();
10664 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10665 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010666 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010667 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010668 E = E->IgnoreImpCasts();
10669
10670 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10671
Richard Trieuf7432752014-06-06 21:39:26 +000010672 if (isa<CXXThisExpr>(E)) {
10673 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10674 : diag::warn_this_bool_conversion;
10675 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10676 return;
10677 }
10678
Richard Trieu3bb8b562014-02-26 02:36:06 +000010679 bool IsAddressOf = false;
10680
10681 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10682 if (UO->getOpcode() != UO_AddrOf)
10683 return;
10684 IsAddressOf = true;
10685 E = UO->getSubExpr();
10686 }
10687
Richard Trieuc1888e02014-06-28 23:25:37 +000010688 if (IsAddressOf) {
10689 unsigned DiagID = IsCompare
10690 ? diag::warn_address_of_reference_null_compare
10691 : diag::warn_address_of_reference_bool_conversion;
10692 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10693 << IsEqual;
10694 if (CheckForReference(*this, E, PD)) {
10695 return;
10696 }
10697 }
10698
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010699 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10700 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010701 std::string Str;
10702 llvm::raw_string_ostream S(Str);
10703 E->printPretty(S, nullptr, getPrintingPolicy());
10704 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10705 : diag::warn_cast_nonnull_to_bool;
10706 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10707 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010708 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010709 };
10710
10711 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10712 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10713 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010714 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10715 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010716 return;
10717 }
10718 }
10719 }
10720
Richard Trieu3bb8b562014-02-26 02:36:06 +000010721 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010722 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010723 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10724 D = R->getDecl();
10725 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10726 D = M->getMemberDecl();
10727 }
10728
10729 // Weak Decls can be null.
10730 if (!D || D->isWeak())
10731 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010732
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010733 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010734 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10735 if (getCurFunction() &&
10736 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010737 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10738 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010739 return;
10740 }
10741
10742 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010743 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010744 assert(ParamIter != FD->param_end());
10745 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10746
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010747 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10748 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010749 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010750 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010751 }
George Burgess IV850269a2015-12-08 22:02:00 +000010752
Joel E. Denny81508102018-03-13 14:51:22 +000010753 for (const ParamIdx &ArgNo : NonNull->args()) {
10754 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010755 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010756 return;
10757 }
George Burgess IV850269a2015-12-08 22:02:00 +000010758 }
10759 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010760 }
10761 }
George Burgess IV850269a2015-12-08 22:02:00 +000010762 }
10763
Richard Trieu3bb8b562014-02-26 02:36:06 +000010764 QualType T = D->getType();
10765 const bool IsArray = T->isArrayType();
10766 const bool IsFunction = T->isFunctionType();
10767
Richard Trieuc1888e02014-06-28 23:25:37 +000010768 // Address of function is used to silence the function warning.
10769 if (IsAddressOf && IsFunction) {
10770 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010771 }
10772
10773 // Found nothing.
10774 if (!IsAddressOf && !IsFunction && !IsArray)
10775 return;
10776
10777 // Pretty print the expression for the diagnostic.
10778 std::string Str;
10779 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010780 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010781
10782 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10783 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010784 enum {
10785 AddressOf,
10786 FunctionPointer,
10787 ArrayPointer
10788 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010789 if (IsAddressOf)
10790 DiagType = AddressOf;
10791 else if (IsFunction)
10792 DiagType = FunctionPointer;
10793 else if (IsArray)
10794 DiagType = ArrayPointer;
10795 else
10796 llvm_unreachable("Could not determine diagnostic.");
10797 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10798 << Range << IsEqual;
10799
10800 if (!IsFunction)
10801 return;
10802
10803 // Suggest '&' to silence the function warning.
10804 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10805 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10806
10807 // Check to see if '()' fixit should be emitted.
10808 QualType ReturnType;
10809 UnresolvedSet<4> NonTemplateOverloads;
10810 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10811 if (ReturnType.isNull())
10812 return;
10813
10814 if (IsCompare) {
10815 // There are two cases here. If there is null constant, the only suggest
10816 // for a pointer return type. If the null is 0, then suggest if the return
10817 // type is a pointer or an integer type.
10818 if (!ReturnType->isPointerType()) {
10819 if (NullKind == Expr::NPCK_ZeroExpression ||
10820 NullKind == Expr::NPCK_ZeroLiteral) {
10821 if (!ReturnType->isIntegerType())
10822 return;
10823 } else {
10824 return;
10825 }
10826 }
10827 } else { // !IsCompare
10828 // For function to bool, only suggest if the function pointer has bool
10829 // return type.
10830 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10831 return;
10832 }
10833 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010834 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010835}
10836
John McCallcc7e5bf2010-05-06 08:58:33 +000010837/// Diagnoses "dangerous" implicit conversions within the given
10838/// expression (which is a full expression). Implements -Wconversion
10839/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010840///
10841/// \param CC the "context" location of the implicit conversion, i.e.
10842/// the most location of the syntactic entity requiring the implicit
10843/// conversion
10844void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010845 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010846 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010847 return;
10848
10849 // Don't diagnose for value- or type-dependent expressions.
10850 if (E->isTypeDependent() || E->isValueDependent())
10851 return;
10852
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010853 // Check for array bounds violations in cases where the check isn't triggered
10854 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10855 // ArraySubscriptExpr is on the RHS of a variable initialization.
10856 CheckArrayAccess(E);
10857
John McCallacf0ee52010-10-08 02:01:28 +000010858 // This is not the right CC for (e.g.) a variable initialization.
10859 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010860}
10861
Richard Trieu65724892014-11-15 06:37:39 +000010862/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10863/// Input argument E is a logical expression.
10864void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10865 ::CheckBoolLikeConversion(*this, E, CC);
10866}
10867
Richard Smith9f7df0c2017-06-26 23:19:32 +000010868/// Diagnose when expression is an integer constant expression and its evaluation
10869/// results in integer overflow
10870void Sema::CheckForIntOverflow (Expr *E) {
10871 // Use a work list to deal with nested struct initializers.
10872 SmallVector<Expr *, 2> Exprs(1, E);
10873
10874 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010875 Expr *OriginalE = Exprs.pop_back_val();
10876 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010877
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010878 if (isa<BinaryOperator>(E)) {
10879 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010880 continue;
10881 }
10882
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010883 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010884 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010885 else if (isa<ObjCBoxedExpr>(OriginalE))
10886 E->EvaluateForOverflow(Context);
10887 else if (auto Call = dyn_cast<CallExpr>(E))
10888 Exprs.append(Call->arg_begin(), Call->arg_end());
10889 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10890 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010891 } while (!Exprs.empty());
10892}
10893
Richard Smithc406cb72013-01-17 01:17:56 +000010894namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010895
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010896/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010897/// same object.
10898class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010899 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010900
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010901 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010902 /// unsequenced if one is an ancestor or a descendent of the other. When we
10903 /// finish processing an expression with sequencing, such as a comma
10904 /// expression, we fold its tree nodes into its parent, since they are
10905 /// unsequenced with respect to nodes we will visit later.
10906 class SequenceTree {
10907 struct Value {
10908 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10909 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010910 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010911 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010912 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010913
10914 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010915 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010916 /// to some other region.
10917 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010918 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010919
10920 unsigned Index = 0;
10921
10922 explicit Seq(unsigned N) : Index(N) {}
10923
Richard Smithc406cb72013-01-17 01:17:56 +000010924 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010925 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010926 };
10927
10928 SequenceTree() { Values.push_back(Value(0)); }
10929 Seq root() const { return Seq(0); }
10930
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010931 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010932 /// subset of \p Parent. This sequence of operations is sequenced with
10933 /// respect to other children of \p Parent.
10934 Seq allocate(Seq Parent) {
10935 Values.push_back(Value(Parent.Index));
10936 return Seq(Values.size() - 1);
10937 }
10938
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010939 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010940 void merge(Seq S) {
10941 Values[S.Index].Merged = true;
10942 }
10943
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010944 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010945 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10946 /// should have been merged into its parent as appropriate.
10947 bool isUnsequenced(Seq Cur, Seq Old) {
10948 unsigned C = representative(Cur.Index);
10949 unsigned Target = representative(Old.Index);
10950 while (C >= Target) {
10951 if (C == Target)
10952 return true;
10953 C = Values[C].Parent;
10954 }
10955 return false;
10956 }
10957
10958 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010959 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010960 unsigned representative(unsigned K) {
10961 if (Values[K].Merged)
10962 // Perform path compression as we go.
10963 return Values[K].Parent = representative(Values[K].Parent);
10964 return K;
10965 }
10966 };
10967
10968 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010969 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010970
10971 /// Different flavors of object usage which we track. We only track the
10972 /// least-sequenced usage of each kind.
10973 enum UsageKind {
10974 /// A read of an object. Multiple unsequenced reads are OK.
10975 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010976
Richard Smithc406cb72013-01-17 01:17:56 +000010977 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010978 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010979 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010980
Richard Smithc406cb72013-01-17 01:17:56 +000010981 /// A modification of an object which is not sequenced before the value
10982 /// computation of the expression, such as n++.
10983 UK_ModAsSideEffect,
10984
10985 UK_Count = UK_ModAsSideEffect + 1
10986 };
10987
10988 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010989 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010990 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010991
10992 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010993 };
10994
10995 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010996 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010997
Richard Smithc406cb72013-01-17 01:17:56 +000010998 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010999 bool Diagnosed = false;
11000
11001 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000011002 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011003 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000011004
11005 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011006
Richard Smithc406cb72013-01-17 01:17:56 +000011007 /// Sequenced regions within the expression.
11008 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011009
Richard Smithc406cb72013-01-17 01:17:56 +000011010 /// Declaration modifications and references which we have seen.
11011 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011012
Richard Smithc406cb72013-01-17 01:17:56 +000011013 /// The region we are currently within.
11014 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011015
Richard Smithc406cb72013-01-17 01:17:56 +000011016 /// Filled in with declarations which were modified as a side-effect
11017 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011018 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11019
Richard Smithd33f5202013-01-17 23:18:09 +000011020 /// Expressions to check later. We defer checking these to reduce
11021 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011022 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000011023
11024 /// RAII object wrapping the visitation of a sequenced subexpression of an
11025 /// expression. At the end of this process, the side-effects of the evaluation
11026 /// become sequenced with respect to the value computation of the result, so
11027 /// we downgrade any UK_ModAsSideEffect within the evaluation to
11028 /// UK_ModAsValue.
11029 struct SequencedSubexpression {
11030 SequencedSubexpression(SequenceChecker &Self)
11031 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11032 Self.ModAsSideEffect = &ModAsSideEffect;
11033 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011034
Richard Smithc406cb72013-01-17 01:17:56 +000011035 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000011036 for (auto &M : llvm::reverse(ModAsSideEffect)) {
11037 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000011038 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000011039 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11040 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000011041 }
11042 Self.ModAsSideEffect = OldModAsSideEffect;
11043 }
11044
11045 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011046 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011047 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000011048 };
11049
Richard Smith40238f02013-06-20 22:21:56 +000011050 /// RAII object wrapping the visitation of a subexpression which we might
11051 /// choose to evaluate as a constant. If any subexpression is evaluated and
11052 /// found to be non-constant, this allows us to suppress the evaluation of
11053 /// the outer expression.
11054 class EvaluationTracker {
11055 public:
11056 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011057 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000011058 Self.EvalTracker = this;
11059 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011060
Richard Smith40238f02013-06-20 22:21:56 +000011061 ~EvaluationTracker() {
11062 Self.EvalTracker = Prev;
11063 if (Prev)
11064 Prev->EvalOK &= EvalOK;
11065 }
11066
11067 bool evaluate(const Expr *E, bool &Result) {
11068 if (!EvalOK || E->isValueDependent())
11069 return false;
11070 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11071 return EvalOK;
11072 }
11073
11074 private:
11075 SequenceChecker &Self;
11076 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011077 bool EvalOK = true;
11078 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000011079
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011080 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000011081 /// if any.
11082 Object getObject(Expr *E, bool Mod) const {
11083 E = E->IgnoreParenCasts();
11084 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11085 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11086 return getObject(UO->getSubExpr(), Mod);
11087 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11088 if (BO->getOpcode() == BO_Comma)
11089 return getObject(BO->getRHS(), Mod);
11090 if (Mod && BO->isAssignmentOp())
11091 return getObject(BO->getLHS(), Mod);
11092 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11093 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11094 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11095 return ME->getMemberDecl();
11096 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11097 // FIXME: If this is a reference, map through to its value.
11098 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000011099 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000011100 }
11101
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011102 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000011103 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11104 Usage &U = UI.Uses[UK];
11105 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11106 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11107 ModAsSideEffect->push_back(std::make_pair(O, U));
11108 U.Use = Ref;
11109 U.Seq = Region;
11110 }
11111 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011112
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011113 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000011114 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11115 bool IsModMod) {
11116 if (UI.Diagnosed)
11117 return;
11118
11119 const Usage &U = UI.Uses[OtherKind];
11120 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11121 return;
11122
11123 Expr *Mod = U.Use;
11124 Expr *ModOrUse = Ref;
11125 if (OtherKind == UK_Use)
11126 std::swap(Mod, ModOrUse);
11127
11128 SemaRef.Diag(Mod->getExprLoc(),
11129 IsModMod ? diag::warn_unsequenced_mod_mod
11130 : diag::warn_unsequenced_mod_use)
11131 << O << SourceRange(ModOrUse->getExprLoc());
11132 UI.Diagnosed = true;
11133 }
11134
11135 void notePreUse(Object O, Expr *Use) {
11136 UsageInfo &U = UsageMap[O];
11137 // Uses conflict with other modifications.
11138 checkUsage(O, U, Use, UK_ModAsValue, false);
11139 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011140
Richard Smithc406cb72013-01-17 01:17:56 +000011141 void notePostUse(Object O, Expr *Use) {
11142 UsageInfo &U = UsageMap[O];
11143 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11144 addUsage(U, O, Use, UK_Use);
11145 }
11146
11147 void notePreMod(Object O, Expr *Mod) {
11148 UsageInfo &U = UsageMap[O];
11149 // Modifications conflict with other modifications and with uses.
11150 checkUsage(O, U, Mod, UK_ModAsValue, true);
11151 checkUsage(O, U, Mod, UK_Use, false);
11152 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011153
Richard Smithc406cb72013-01-17 01:17:56 +000011154 void notePostMod(Object O, Expr *Use, UsageKind UK) {
11155 UsageInfo &U = UsageMap[O];
11156 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11157 addUsage(U, O, Use, UK);
11158 }
11159
11160public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011161 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011162 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000011163 Visit(E);
11164 }
11165
11166 void VisitStmt(Stmt *S) {
11167 // Skip all statements which aren't expressions for now.
11168 }
11169
11170 void VisitExpr(Expr *E) {
11171 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000011172 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000011173 }
11174
11175 void VisitCastExpr(CastExpr *E) {
11176 Object O = Object();
11177 if (E->getCastKind() == CK_LValueToRValue)
11178 O = getObject(E->getSubExpr(), false);
11179
11180 if (O)
11181 notePreUse(O, E);
11182 VisitExpr(E);
11183 if (O)
11184 notePostUse(O, E);
11185 }
11186
11187 void VisitBinComma(BinaryOperator *BO) {
11188 // C++11 [expr.comma]p1:
11189 // Every value computation and side effect associated with the left
11190 // expression is sequenced before every value computation and side
11191 // effect associated with the right expression.
11192 SequenceTree::Seq LHS = Tree.allocate(Region);
11193 SequenceTree::Seq RHS = Tree.allocate(Region);
11194 SequenceTree::Seq OldRegion = Region;
11195
11196 {
11197 SequencedSubexpression SeqLHS(*this);
11198 Region = LHS;
11199 Visit(BO->getLHS());
11200 }
11201
11202 Region = RHS;
11203 Visit(BO->getRHS());
11204
11205 Region = OldRegion;
11206
11207 // Forget that LHS and RHS are sequenced. They are both unsequenced
11208 // with respect to other stuff.
11209 Tree.merge(LHS);
11210 Tree.merge(RHS);
11211 }
11212
11213 void VisitBinAssign(BinaryOperator *BO) {
11214 // The modification is sequenced after the value computation of the LHS
11215 // and RHS, so check it before inspecting the operands and update the
11216 // map afterwards.
11217 Object O = getObject(BO->getLHS(), true);
11218 if (!O)
11219 return VisitExpr(BO);
11220
11221 notePreMod(O, BO);
11222
11223 // C++11 [expr.ass]p7:
11224 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11225 // only once.
11226 //
11227 // Therefore, for a compound assignment operator, O is considered used
11228 // everywhere except within the evaluation of E1 itself.
11229 if (isa<CompoundAssignOperator>(BO))
11230 notePreUse(O, BO);
11231
11232 Visit(BO->getLHS());
11233
11234 if (isa<CompoundAssignOperator>(BO))
11235 notePostUse(O, BO);
11236
11237 Visit(BO->getRHS());
11238
Richard Smith83e37bee2013-06-26 23:16:51 +000011239 // C++11 [expr.ass]p1:
11240 // the assignment is sequenced [...] before the value computation of the
11241 // assignment expression.
11242 // C11 6.5.16/3 has no such rule.
11243 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11244 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011245 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011246
Richard Smithc406cb72013-01-17 01:17:56 +000011247 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11248 VisitBinAssign(CAO);
11249 }
11250
11251 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11252 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11253 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11254 Object O = getObject(UO->getSubExpr(), true);
11255 if (!O)
11256 return VisitExpr(UO);
11257
11258 notePreMod(O, UO);
11259 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011260 // C++11 [expr.pre.incr]p1:
11261 // the expression ++x is equivalent to x+=1
11262 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11263 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011264 }
11265
11266 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11267 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11268 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11269 Object O = getObject(UO->getSubExpr(), true);
11270 if (!O)
11271 return VisitExpr(UO);
11272
11273 notePreMod(O, UO);
11274 Visit(UO->getSubExpr());
11275 notePostMod(O, UO, UK_ModAsSideEffect);
11276 }
11277
11278 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11279 void VisitBinLOr(BinaryOperator *BO) {
11280 // The side-effects of the LHS of an '&&' are sequenced before the
11281 // value computation of the RHS, and hence before the value computation
11282 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11283 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011284 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011285 {
11286 SequencedSubexpression Sequenced(*this);
11287 Visit(BO->getLHS());
11288 }
11289
11290 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011291 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011292 if (!Result)
11293 Visit(BO->getRHS());
11294 } else {
11295 // Check for unsequenced operations in the RHS, treating it as an
11296 // entirely separate evaluation.
11297 //
11298 // FIXME: If there are operations in the RHS which are unsequenced
11299 // with respect to operations outside the RHS, and those operations
11300 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011301 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011302 }
Richard Smithc406cb72013-01-17 01:17:56 +000011303 }
11304 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011305 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011306 {
11307 SequencedSubexpression Sequenced(*this);
11308 Visit(BO->getLHS());
11309 }
11310
11311 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011312 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011313 if (Result)
11314 Visit(BO->getRHS());
11315 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011316 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011317 }
Richard Smithc406cb72013-01-17 01:17:56 +000011318 }
11319
11320 // Only visit the condition, unless we can be sure which subexpression will
11321 // be chosen.
11322 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011323 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011324 {
11325 SequencedSubexpression Sequenced(*this);
11326 Visit(CO->getCond());
11327 }
Richard Smithc406cb72013-01-17 01:17:56 +000011328
11329 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011330 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011331 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011332 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011333 WorkList.push_back(CO->getTrueExpr());
11334 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011335 }
Richard Smithc406cb72013-01-17 01:17:56 +000011336 }
11337
Richard Smithe3dbfe02013-06-30 10:40:20 +000011338 void VisitCallExpr(CallExpr *CE) {
11339 // C++11 [intro.execution]p15:
11340 // When calling a function [...], every value computation and side effect
11341 // associated with any argument expression, or with the postfix expression
11342 // designating the called function, is sequenced before execution of every
11343 // expression or statement in the body of the function [and thus before
11344 // the value computation of its result].
11345 SequencedSubexpression Sequenced(*this);
11346 Base::VisitCallExpr(CE);
11347
11348 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11349 }
11350
Richard Smithc406cb72013-01-17 01:17:56 +000011351 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011352 // This is a call, so all subexpressions are sequenced before the result.
11353 SequencedSubexpression Sequenced(*this);
11354
Richard Smithc406cb72013-01-17 01:17:56 +000011355 if (!CCE->isListInitialization())
11356 return VisitExpr(CCE);
11357
11358 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011359 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011360 SequenceTree::Seq Parent = Region;
11361 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11362 E = CCE->arg_end();
11363 I != E; ++I) {
11364 Region = Tree.allocate(Parent);
11365 Elts.push_back(Region);
11366 Visit(*I);
11367 }
11368
11369 // Forget that the initializers are sequenced.
11370 Region = Parent;
11371 for (unsigned I = 0; I < Elts.size(); ++I)
11372 Tree.merge(Elts[I]);
11373 }
11374
11375 void VisitInitListExpr(InitListExpr *ILE) {
11376 if (!SemaRef.getLangOpts().CPlusPlus11)
11377 return VisitExpr(ILE);
11378
11379 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011380 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011381 SequenceTree::Seq Parent = Region;
11382 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11383 Expr *E = ILE->getInit(I);
11384 if (!E) continue;
11385 Region = Tree.allocate(Parent);
11386 Elts.push_back(Region);
11387 Visit(E);
11388 }
11389
11390 // Forget that the initializers are sequenced.
11391 Region = Parent;
11392 for (unsigned I = 0; I < Elts.size(); ++I)
11393 Tree.merge(Elts[I]);
11394 }
11395};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011396
11397} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011398
11399void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011400 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011401 WorkList.push_back(E);
11402 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011403 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011404 SequenceChecker(*this, Item, WorkList);
11405 }
Richard Smithc406cb72013-01-17 01:17:56 +000011406}
11407
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011408void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11409 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011410 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011411 if (!E->isInstantiationDependent())
11412 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011413 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011414 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011415 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011416}
11417
John McCall1f425642010-11-11 03:21:53 +000011418void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11419 FieldDecl *BitField,
11420 Expr *Init) {
11421 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11422}
11423
David Majnemer61a5bbf2015-04-07 22:08:51 +000011424static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11425 SourceLocation Loc) {
11426 if (!PType->isVariablyModifiedType())
11427 return;
11428 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11429 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11430 return;
11431 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011432 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11433 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11434 return;
11435 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011436 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11437 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11438 return;
11439 }
11440
11441 const ArrayType *AT = S.Context.getAsArrayType(PType);
11442 if (!AT)
11443 return;
11444
11445 if (AT->getSizeModifier() != ArrayType::Star) {
11446 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11447 return;
11448 }
11449
11450 S.Diag(Loc, diag::err_array_star_in_function_definition);
11451}
11452
Mike Stump0c2ec772010-01-21 03:59:47 +000011453/// CheckParmsForFunctionDef - Check that the parameters of the given
11454/// function are appropriate for the definition of a function. This
11455/// takes care of any checks that cannot be performed on the
11456/// declaration itself, e.g., that the types of each of the function
11457/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011458bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011459 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011460 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011461 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011462 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11463 // function declarator that is part of a function definition of
11464 // that function shall not have incomplete type.
11465 //
11466 // This is also C++ [dcl.fct]p6.
11467 if (!Param->isInvalidDecl() &&
11468 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011469 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011470 Param->setInvalidDecl();
11471 HasInvalidParm = true;
11472 }
11473
11474 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11475 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011476 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011477 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011478 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011479 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011480 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011481
11482 // C99 6.7.5.3p12:
11483 // If the function declarator is not part of a definition of that
11484 // function, parameters may have incomplete type and may use the [*]
11485 // notation in their sequences of declarator specifiers to specify
11486 // variable length array types.
11487 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011488 // FIXME: This diagnostic should point the '[*]' if source-location
11489 // information is added for it.
11490 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011491
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011492 // If the parameter is a c++ class type and it has to be destructed in the
11493 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011494 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011495 if (!Param->isInvalidDecl()) {
11496 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11497 if (!ClassDecl->isInvalidDecl() &&
11498 !ClassDecl->hasIrrelevantDestructor() &&
11499 !ClassDecl->isDependentContext() &&
Akira Hatanaka85282972018-05-15 21:00:30 +000011500 ClassDecl->isParamDestroyedInCallee()) {
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011501 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11502 MarkFunctionReferenced(Param->getLocation(), Destructor);
11503 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011504 }
11505 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011506 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011507
11508 // Parameters with the pass_object_size attribute only need to be marked
11509 // constant at function definitions. Because we lack information about
11510 // whether we're on a declaration or definition when we're instantiating the
11511 // attribute, we need to check for constness here.
11512 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11513 if (!Param->getType().isConstQualified())
11514 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11515 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011516 }
11517
11518 return HasInvalidParm;
11519}
John McCall2b5c1b22010-08-12 21:44:57 +000011520
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011521/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11522/// or MemberExpr.
11523static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11524 ASTContext &Context) {
11525 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11526 return Context.getDeclAlign(DRE->getDecl());
11527
11528 if (const auto *ME = dyn_cast<MemberExpr>(E))
11529 return Context.getDeclAlign(ME->getMemberDecl());
11530
11531 return TypeAlign;
11532}
11533
John McCall2b5c1b22010-08-12 21:44:57 +000011534/// CheckCastAlign - Implements -Wcast-align, which warns when a
11535/// pointer cast increases the alignment requirements.
11536void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11537 // This is actually a lot of work to potentially be doing on every
11538 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011539 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011540 return;
11541
11542 // Ignore dependent types.
11543 if (T->isDependentType() || Op->getType()->isDependentType())
11544 return;
11545
11546 // Require that the destination be a pointer type.
11547 const PointerType *DestPtr = T->getAs<PointerType>();
11548 if (!DestPtr) return;
11549
11550 // If the destination has alignment 1, we're done.
11551 QualType DestPointee = DestPtr->getPointeeType();
11552 if (DestPointee->isIncompleteType()) return;
11553 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11554 if (DestAlign.isOne()) return;
11555
11556 // Require that the source be a pointer type.
11557 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11558 if (!SrcPtr) return;
11559 QualType SrcPointee = SrcPtr->getPointeeType();
11560
11561 // Whitelist casts from cv void*. We already implicitly
11562 // whitelisted casts to cv void*, since they have alignment 1.
11563 // Also whitelist casts involving incomplete types, which implicitly
11564 // includes 'void'.
11565 if (SrcPointee->isIncompleteType()) return;
11566
11567 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011568
11569 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11570 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11571 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11572 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11573 if (UO->getOpcode() == UO_AddrOf)
11574 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11575 }
11576
John McCall2b5c1b22010-08-12 21:44:57 +000011577 if (SrcAlign >= DestAlign) return;
11578
11579 Diag(TRange.getBegin(), diag::warn_cast_align)
11580 << Op->getType() << T
11581 << static_cast<unsigned>(SrcAlign.getQuantity())
11582 << static_cast<unsigned>(DestAlign.getQuantity())
11583 << TRange << Op->getSourceRange();
11584}
11585
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011586/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011587/// array member of a struct.
11588///
11589/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11590/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011591static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011592 const NamedDecl *ND) {
11593 if (Size != 1 || !ND) return false;
11594
11595 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11596 if (!FD) return false;
11597
11598 // Don't consider sizes resulting from macro expansions or template argument
11599 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011600
11601 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011602 while (TInfo) {
11603 TypeLoc TL = TInfo->getTypeLoc();
11604 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011605 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11606 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011607 TInfo = TDL->getTypeSourceInfo();
11608 continue;
11609 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011610 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11611 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011612 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11613 return false;
11614 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011615 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011616 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011617
11618 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011619 if (!RD) return false;
11620 if (RD->isUnion()) return false;
11621 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11622 if (!CRD->isStandardLayout()) return false;
11623 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011624
Benjamin Kramer8c543672011-08-06 03:04:42 +000011625 // See if this is the last field decl in the record.
11626 const Decl *D = FD;
11627 while ((D = D->getNextDeclInContext()))
11628 if (isa<FieldDecl>(D))
11629 return false;
11630 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011631}
11632
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011633void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011634 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011635 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011636 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011637 if (IndexExpr->isValueDependent())
11638 return;
11639
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011640 const Type *EffectiveType =
11641 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011642 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011643 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011644 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011645 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011646 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011647
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011648 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011649 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011650 return;
Richard Smith13f67182011-12-16 19:31:14 +000011651 if (IndexNegated)
11652 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011653
Craig Topperc3ec1492014-05-26 06:22:03 +000011654 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011655 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011656 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011657 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011658 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011659
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011660 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011661 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011662 if (!size.isStrictlyPositive())
11663 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011664
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011665 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011666 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011667 // Make sure we're comparing apples to apples when comparing index to size
11668 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11669 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011670 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011671 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011672 if (ptrarith_typesize != array_typesize) {
11673 // There's a cast to a different size type involved
11674 uint64_t ratio = array_typesize / ptrarith_typesize;
11675 // TODO: Be smarter about handling cases where array_typesize is not a
11676 // multiple of ptrarith_typesize
11677 if (ptrarith_typesize * ratio == array_typesize)
11678 size *= llvm::APInt(size.getBitWidth(), ratio);
11679 }
11680 }
11681
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011682 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011683 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011684 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011685 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011686
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011687 // For array subscripting the index must be less than size, but for pointer
11688 // arithmetic also allow the index (offset) to be equal to size since
11689 // computing the next address after the end of the array is legal and
11690 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011691 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011692 return;
11693
11694 // Also don't warn for arrays of size 1 which are members of some
11695 // structure. These are often used to approximate flexible arrays in C89
11696 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011697 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011698 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011699
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011700 // Suppress the warning if the subscript expression (as identified by the
11701 // ']' location) and the index expression are both from macro expansions
11702 // within a system header.
11703 if (ASE) {
11704 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11705 ASE->getRBracketLoc());
11706 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11707 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11708 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011709 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011710 return;
11711 }
11712 }
11713
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011714 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011715 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011716 DiagID = diag::warn_array_index_exceeds_bounds;
11717
11718 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11719 PDiag(DiagID) << index.toString(10, true)
11720 << size.toString(10, true)
11721 << (unsigned)size.getLimitedValue(~0U)
11722 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011723 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011724 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011725 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011726 DiagID = diag::warn_ptr_arith_precedes_bounds;
11727 if (index.isNegative()) index = -index;
11728 }
11729
11730 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11731 PDiag(DiagID) << index.toString(10, true)
11732 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011733 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011734
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011735 if (!ND) {
11736 // Try harder to find a NamedDecl to point at in the note.
11737 while (const ArraySubscriptExpr *ASE =
11738 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11739 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11740 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011741 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011742 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011743 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011744 }
11745
Chandler Carruth1af88f12011-02-17 21:10:52 +000011746 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011747 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11748 PDiag(diag::note_array_index_out_of_bounds)
11749 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011750}
11751
Ted Kremenekdf26df72011-03-01 18:41:00 +000011752void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011753 int AllowOnePastEnd = 0;
11754 while (expr) {
11755 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011756 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011757 case Stmt::ArraySubscriptExprClass: {
11758 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011759 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011760 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011761 expr = ASE->getBase();
11762 break;
11763 }
11764 case Stmt::MemberExprClass: {
11765 expr = cast<MemberExpr>(expr)->getBase();
11766 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011767 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011768 case Stmt::OMPArraySectionExprClass: {
11769 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11770 if (ASE->getLowerBound())
11771 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11772 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11773 return;
11774 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011775 case Stmt::UnaryOperatorClass: {
11776 // Only unwrap the * and & unary operators
11777 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11778 expr = UO->getSubExpr();
11779 switch (UO->getOpcode()) {
11780 case UO_AddrOf:
11781 AllowOnePastEnd++;
11782 break;
11783 case UO_Deref:
11784 AllowOnePastEnd--;
11785 break;
11786 default:
11787 return;
11788 }
11789 break;
11790 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011791 case Stmt::ConditionalOperatorClass: {
11792 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11793 if (const Expr *lhs = cond->getLHS())
11794 CheckArrayAccess(lhs);
11795 if (const Expr *rhs = cond->getRHS())
11796 CheckArrayAccess(rhs);
11797 return;
11798 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011799 case Stmt::CXXOperatorCallExprClass: {
11800 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11801 for (const auto *Arg : OCE->arguments())
11802 CheckArrayAccess(Arg);
11803 return;
11804 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011805 default:
11806 return;
11807 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011808 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011809}
John McCall31168b02011-06-15 23:02:42 +000011810
11811//===--- CHECK: Objective-C retain cycles ----------------------------------//
11812
11813namespace {
John McCall31168b02011-06-15 23:02:42 +000011814
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011815struct RetainCycleOwner {
11816 VarDecl *Variable = nullptr;
11817 SourceRange Range;
11818 SourceLocation Loc;
11819 bool Indirect = false;
11820
11821 RetainCycleOwner() = default;
11822
11823 void setLocsFrom(Expr *e) {
11824 Loc = e->getExprLoc();
11825 Range = e->getSourceRange();
11826 }
11827};
11828
11829} // namespace
John McCall31168b02011-06-15 23:02:42 +000011830
11831/// Consider whether capturing the given variable can possibly lead to
11832/// a retain cycle.
11833static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011834 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011835 // lifetime. In MRR, it's captured strongly if the variable is
11836 // __block and has an appropriate type.
11837 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11838 return false;
11839
11840 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011841 if (ref)
11842 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011843 return true;
11844}
11845
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011846static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011847 while (true) {
11848 e = e->IgnoreParens();
11849 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11850 switch (cast->getCastKind()) {
11851 case CK_BitCast:
11852 case CK_LValueBitCast:
11853 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011854 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011855 e = cast->getSubExpr();
11856 continue;
11857
John McCall31168b02011-06-15 23:02:42 +000011858 default:
11859 return false;
11860 }
11861 }
11862
11863 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11864 ObjCIvarDecl *ivar = ref->getDecl();
11865 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11866 return false;
11867
11868 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011869 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011870 return false;
11871
11872 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11873 owner.Indirect = true;
11874 return true;
11875 }
11876
11877 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11878 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11879 if (!var) return false;
11880 return considerVariable(var, ref, owner);
11881 }
11882
John McCall31168b02011-06-15 23:02:42 +000011883 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11884 if (member->isArrow()) return false;
11885
11886 // Don't count this as an indirect ownership.
11887 e = member->getBase();
11888 continue;
11889 }
11890
John McCallfe96e0b2011-11-06 09:01:30 +000011891 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11892 // Only pay attention to pseudo-objects on property references.
11893 ObjCPropertyRefExpr *pre
11894 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11895 ->IgnoreParens());
11896 if (!pre) return false;
11897 if (pre->isImplicitProperty()) return false;
11898 ObjCPropertyDecl *property = pre->getExplicitProperty();
11899 if (!property->isRetaining() &&
11900 !(property->getPropertyIvarDecl() &&
11901 property->getPropertyIvarDecl()->getType()
11902 .getObjCLifetime() == Qualifiers::OCL_Strong))
11903 return false;
11904
11905 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011906 if (pre->isSuperReceiver()) {
11907 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11908 if (!owner.Variable)
11909 return false;
11910 owner.Loc = pre->getLocation();
11911 owner.Range = pre->getSourceRange();
11912 return true;
11913 }
John McCallfe96e0b2011-11-06 09:01:30 +000011914 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11915 ->getSourceExpr());
11916 continue;
11917 }
11918
John McCall31168b02011-06-15 23:02:42 +000011919 // Array ivars?
11920
11921 return false;
11922 }
11923}
11924
11925namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011926
John McCall31168b02011-06-15 23:02:42 +000011927 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011928 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011929 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011930 Expr *Capturer = nullptr;
11931 bool VarWillBeReased = false;
11932
11933 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11934 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11935 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011936
11937 void VisitDeclRefExpr(DeclRefExpr *ref) {
11938 if (ref->getDecl() == Variable && !Capturer)
11939 Capturer = ref;
11940 }
11941
John McCall31168b02011-06-15 23:02:42 +000011942 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11943 if (Capturer) return;
11944 Visit(ref->getBase());
11945 if (Capturer && ref->isFreeIvar())
11946 Capturer = ref;
11947 }
11948
11949 void VisitBlockExpr(BlockExpr *block) {
11950 // Look inside nested blocks
11951 if (block->getBlockDecl()->capturesVariable(Variable))
11952 Visit(block->getBlockDecl()->getBody());
11953 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011954
11955 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11956 if (Capturer) return;
11957 if (OVE->getSourceExpr())
11958 Visit(OVE->getSourceExpr());
11959 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011960
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011961 void VisitBinaryOperator(BinaryOperator *BinOp) {
11962 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11963 return;
11964 Expr *LHS = BinOp->getLHS();
11965 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11966 if (DRE->getDecl() != Variable)
11967 return;
11968 if (Expr *RHS = BinOp->getRHS()) {
11969 RHS = RHS->IgnoreParenCasts();
11970 llvm::APSInt Value;
11971 VarWillBeReased =
11972 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11973 }
11974 }
11975 }
John McCall31168b02011-06-15 23:02:42 +000011976 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011977
11978} // namespace
John McCall31168b02011-06-15 23:02:42 +000011979
11980/// Check whether the given argument is a block which captures a
11981/// variable.
11982static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11983 assert(owner.Variable && owner.Loc.isValid());
11984
11985 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011986
11987 // Look through [^{...} copy] and Block_copy(^{...}).
11988 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11989 Selector Cmd = ME->getSelector();
11990 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11991 e = ME->getInstanceReceiver();
11992 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011993 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011994 e = e->IgnoreParenCasts();
11995 }
11996 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11997 if (CE->getNumArgs() == 1) {
11998 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011999 if (Fn) {
12000 const IdentifierInfo *FnI = Fn->getIdentifier();
12001 if (FnI && FnI->isStr("_Block_copy")) {
12002 e = CE->getArg(0)->IgnoreParenCasts();
12003 }
12004 }
Jordan Rose67e887c2012-09-17 17:54:30 +000012005 }
12006 }
12007
John McCall31168b02011-06-15 23:02:42 +000012008 BlockExpr *block = dyn_cast<BlockExpr>(e);
12009 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000012010 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000012011
12012 FindCaptureVisitor visitor(S.Context, owner.Variable);
12013 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000012014 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000012015}
12016
12017static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12018 RetainCycleOwner &owner) {
12019 assert(capturer);
12020 assert(owner.Variable && owner.Loc.isValid());
12021
12022 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12023 << owner.Variable << capturer->getSourceRange();
12024 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12025 << owner.Indirect << owner.Range;
12026}
12027
12028/// Check for a keyword selector that starts with the word 'add' or
12029/// 'set'.
12030static bool isSetterLikeSelector(Selector sel) {
12031 if (sel.isUnarySelector()) return false;
12032
Chris Lattner0e62c1c2011-07-23 10:55:15 +000012033 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000012034 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012035 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000012036 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000012037 else if (str.startswith("add")) {
12038 // Specially whitelist 'addOperationWithBlock:'.
12039 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12040 return false;
12041 str = str.substr(3);
12042 }
John McCall31168b02011-06-15 23:02:42 +000012043 else
12044 return false;
12045
12046 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000012047 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000012048}
12049
Benjamin Kramer3a743452015-03-09 15:03:32 +000012050static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12051 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012052 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12053 Message->getReceiverInterface(),
12054 NSAPI::ClassId_NSMutableArray);
12055 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012056 return None;
12057 }
12058
12059 Selector Sel = Message->getSelector();
12060
12061 Optional<NSAPI::NSArrayMethodKind> MKOpt =
12062 S.NSAPIObj->getNSArrayMethodKind(Sel);
12063 if (!MKOpt) {
12064 return None;
12065 }
12066
12067 NSAPI::NSArrayMethodKind MK = *MKOpt;
12068
12069 switch (MK) {
12070 case NSAPI::NSMutableArr_addObject:
12071 case NSAPI::NSMutableArr_insertObjectAtIndex:
12072 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12073 return 0;
12074 case NSAPI::NSMutableArr_replaceObjectAtIndex:
12075 return 1;
12076
12077 default:
12078 return None;
12079 }
12080
12081 return None;
12082}
12083
12084static
12085Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12086 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012087 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12088 Message->getReceiverInterface(),
12089 NSAPI::ClassId_NSMutableDictionary);
12090 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012091 return None;
12092 }
12093
12094 Selector Sel = Message->getSelector();
12095
12096 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12097 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12098 if (!MKOpt) {
12099 return None;
12100 }
12101
12102 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12103
12104 switch (MK) {
12105 case NSAPI::NSMutableDict_setObjectForKey:
12106 case NSAPI::NSMutableDict_setValueForKey:
12107 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12108 return 0;
12109
12110 default:
12111 return None;
12112 }
12113
12114 return None;
12115}
12116
12117static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012118 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12119 Message->getReceiverInterface(),
12120 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000012121
Alex Denisov5dfac812015-08-06 04:51:14 +000012122 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12123 Message->getReceiverInterface(),
12124 NSAPI::ClassId_NSMutableOrderedSet);
12125 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012126 return None;
12127 }
12128
12129 Selector Sel = Message->getSelector();
12130
12131 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12132 if (!MKOpt) {
12133 return None;
12134 }
12135
12136 NSAPI::NSSetMethodKind MK = *MKOpt;
12137
12138 switch (MK) {
12139 case NSAPI::NSMutableSet_addObject:
12140 case NSAPI::NSOrderedSet_setObjectAtIndex:
12141 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12142 case NSAPI::NSOrderedSet_insertObjectAtIndex:
12143 return 0;
12144 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12145 return 1;
12146 }
12147
12148 return None;
12149}
12150
12151void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12152 if (!Message->isInstanceMessage()) {
12153 return;
12154 }
12155
12156 Optional<int> ArgOpt;
12157
12158 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12159 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12160 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12161 return;
12162 }
12163
12164 int ArgIndex = *ArgOpt;
12165
Alex Denisove1d882c2015-03-04 17:55:52 +000012166 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12167 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12168 Arg = OE->getSourceExpr()->IgnoreImpCasts();
12169 }
12170
Alex Denisov5dfac812015-08-06 04:51:14 +000012171 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012172 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000012173 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000012174 Diag(Message->getSourceRange().getBegin(),
12175 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012176 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000012177 }
12178 }
Alex Denisov5dfac812015-08-06 04:51:14 +000012179 } else {
12180 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12181
12182 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12183 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12184 }
12185
12186 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12187 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12188 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12189 ValueDecl *Decl = ReceiverRE->getDecl();
12190 Diag(Message->getSourceRange().getBegin(),
12191 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012192 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012193 if (!ArgRE->isObjCSelfExpr()) {
12194 Diag(Decl->getLocation(),
12195 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012196 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012197 }
12198 }
12199 }
12200 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12201 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12202 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12203 ObjCIvarDecl *Decl = IvarRE->getDecl();
12204 Diag(Message->getSourceRange().getBegin(),
12205 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000012206 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012207 Diag(Decl->getLocation(),
12208 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000012209 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012210 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012211 }
12212 }
12213 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012214}
12215
John McCall31168b02011-06-15 23:02:42 +000012216/// Check a message send to see if it's likely to cause a retain cycle.
12217void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12218 // Only check instance methods whose selector looks like a setter.
12219 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12220 return;
12221
12222 // Try to find a variable that the receiver is strongly owned by.
12223 RetainCycleOwner owner;
12224 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012225 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012226 return;
12227 } else {
12228 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12229 owner.Variable = getCurMethodDecl()->getSelfDecl();
12230 owner.Loc = msg->getSuperLoc();
12231 owner.Range = msg->getSuperLoc();
12232 }
12233
12234 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012235 const ObjCMethodDecl *MD = msg->getMethodDecl();
12236 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12237 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12238 // noescape blocks should not be retained by the method.
12239 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12240 continue;
John McCall31168b02011-06-15 23:02:42 +000012241 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012242 }
12243 }
John McCall31168b02011-06-15 23:02:42 +000012244}
12245
12246/// Check a property assign to see if it's likely to cause a retain cycle.
12247void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12248 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012249 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012250 return;
12251
12252 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12253 diagnoseRetainCycle(*this, capturer, owner);
12254}
12255
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012256void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12257 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012258 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012259 return;
12260
12261 // Because we don't have an expression for the variable, we have to set the
12262 // location explicitly here.
12263 Owner.Loc = Var->getLocation();
12264 Owner.Range = Var->getSourceRange();
12265
12266 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12267 diagnoseRetainCycle(*this, Capturer, Owner);
12268}
12269
Ted Kremenek9304da92012-12-21 08:04:28 +000012270static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12271 Expr *RHS, bool isProperty) {
12272 // Check if RHS is an Objective-C object literal, which also can get
12273 // immediately zapped in a weak reference. Note that we explicitly
12274 // allow ObjCStringLiterals, since those are designed to never really die.
12275 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012276
Ted Kremenek64873352012-12-21 22:46:35 +000012277 // This enum needs to match with the 'select' in
12278 // warn_objc_arc_literal_assign (off-by-1).
12279 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12280 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12281 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012282
12283 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012284 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012285 << (isProperty ? 0 : 1)
12286 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012287
12288 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012289}
12290
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012291static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12292 Qualifiers::ObjCLifetime LT,
12293 Expr *RHS, bool isProperty) {
12294 // Strip off any implicit cast added to get to the one ARC-specific.
12295 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12296 if (cast->getCastKind() == CK_ARCConsumeObject) {
12297 S.Diag(Loc, diag::warn_arc_retained_assign)
12298 << (LT == Qualifiers::OCL_ExplicitNone)
12299 << (isProperty ? 0 : 1)
12300 << RHS->getSourceRange();
12301 return true;
12302 }
12303 RHS = cast->getSubExpr();
12304 }
12305
12306 if (LT == Qualifiers::OCL_Weak &&
12307 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12308 return true;
12309
12310 return false;
12311}
12312
Ted Kremenekb36234d2012-12-21 08:04:20 +000012313bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12314 QualType LHS, Expr *RHS) {
12315 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12316
12317 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12318 return false;
12319
12320 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12321 return true;
12322
12323 return false;
12324}
12325
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012326void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12327 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012328 QualType LHSType;
12329 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012330 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012331 ObjCPropertyRefExpr *PRE
12332 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12333 if (PRE && !PRE->isImplicitProperty()) {
12334 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12335 if (PD)
12336 LHSType = PD->getType();
12337 }
12338
12339 if (LHSType.isNull())
12340 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012341
12342 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12343
12344 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012345 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012346 getCurFunction()->markSafeWeakUse(LHS);
12347 }
12348
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012349 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12350 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012351
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012352 // FIXME. Check for other life times.
12353 if (LT != Qualifiers::OCL_None)
12354 return;
12355
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012356 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012357 if (PRE->isImplicitProperty())
12358 return;
12359 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12360 if (!PD)
12361 return;
12362
Bill Wendling44426052012-12-20 19:22:21 +000012363 unsigned Attributes = PD->getPropertyAttributes();
12364 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012365 // when 'assign' attribute was not explicitly specified
12366 // by user, ignore it and rely on property type itself
12367 // for lifetime info.
12368 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12369 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12370 LHSType->isObjCRetainableType())
12371 return;
12372
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012373 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012374 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012375 Diag(Loc, diag::warn_arc_retained_property_assign)
12376 << RHS->getSourceRange();
12377 return;
12378 }
12379 RHS = cast->getSubExpr();
12380 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012381 }
Bill Wendling44426052012-12-20 19:22:21 +000012382 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012383 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12384 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012385 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012386 }
12387}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012388
12389//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12390
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012391static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12392 SourceLocation StmtLoc,
12393 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012394 // Do not warn if the body is a macro that expands to nothing, e.g:
12395 //
12396 // #define CALL(x)
12397 // if (condition)
12398 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012399 if (Body->hasLeadingEmptyMacro())
12400 return false;
12401
12402 // Get line numbers of statement and body.
12403 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012404 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012405 &StmtLineInvalid);
12406 if (StmtLineInvalid)
12407 return false;
12408
12409 bool BodyLineInvalid;
12410 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12411 &BodyLineInvalid);
12412 if (BodyLineInvalid)
12413 return false;
12414
12415 // Warn if null statement and body are on the same line.
12416 if (StmtLine != BodyLine)
12417 return false;
12418
12419 return true;
12420}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012421
12422void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12423 const Stmt *Body,
12424 unsigned DiagID) {
12425 // Since this is a syntactic check, don't emit diagnostic for template
12426 // instantiations, this just adds noise.
12427 if (CurrentInstantiationScope)
12428 return;
12429
12430 // The body should be a null statement.
12431 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12432 if (!NBody)
12433 return;
12434
12435 // Do the usual checks.
12436 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12437 return;
12438
12439 Diag(NBody->getSemiLoc(), DiagID);
12440 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12441}
12442
12443void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12444 const Stmt *PossibleBody) {
12445 assert(!CurrentInstantiationScope); // Ensured by caller
12446
12447 SourceLocation StmtLoc;
12448 const Stmt *Body;
12449 unsigned DiagID;
12450 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12451 StmtLoc = FS->getRParenLoc();
12452 Body = FS->getBody();
12453 DiagID = diag::warn_empty_for_body;
12454 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12455 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12456 Body = WS->getBody();
12457 DiagID = diag::warn_empty_while_body;
12458 } else
12459 return; // Neither `for' nor `while'.
12460
12461 // The body should be a null statement.
12462 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12463 if (!NBody)
12464 return;
12465
12466 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012467 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012468 return;
12469
12470 // Do the usual checks.
12471 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12472 return;
12473
12474 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12475 // noise level low, emit diagnostics only if for/while is followed by a
12476 // CompoundStmt, e.g.:
12477 // for (int i = 0; i < n; i++);
12478 // {
12479 // a(i);
12480 // }
12481 // or if for/while is followed by a statement with more indentation
12482 // than for/while itself:
12483 // for (int i = 0; i < n; i++);
12484 // a(i);
12485 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12486 if (!ProbableTypo) {
12487 bool BodyColInvalid;
12488 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12489 PossibleBody->getLocStart(),
12490 &BodyColInvalid);
12491 if (BodyColInvalid)
12492 return;
12493
12494 bool StmtColInvalid;
12495 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12496 S->getLocStart(),
12497 &StmtColInvalid);
12498 if (StmtColInvalid)
12499 return;
12500
12501 if (BodyCol > StmtCol)
12502 ProbableTypo = true;
12503 }
12504
12505 if (ProbableTypo) {
12506 Diag(NBody->getSemiLoc(), DiagID);
12507 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12508 }
12509}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012510
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012511//===--- CHECK: Warn on self move with std::move. -------------------------===//
12512
12513/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12514void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12515 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012516 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12517 return;
12518
Richard Smith51ec0cf2017-02-21 01:17:38 +000012519 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012520 return;
12521
12522 // Strip parens and casts away.
12523 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12524 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12525
12526 // Check for a call expression
12527 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12528 if (!CE || CE->getNumArgs() != 1)
12529 return;
12530
12531 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012532 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012533 return;
12534
12535 // Get argument from std::move
12536 RHSExpr = CE->getArg(0);
12537
12538 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12539 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12540
12541 // Two DeclRefExpr's, check that the decls are the same.
12542 if (LHSDeclRef && RHSDeclRef) {
12543 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12544 return;
12545 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12546 RHSDeclRef->getDecl()->getCanonicalDecl())
12547 return;
12548
12549 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12550 << LHSExpr->getSourceRange()
12551 << RHSExpr->getSourceRange();
12552 return;
12553 }
12554
12555 // Member variables require a different approach to check for self moves.
12556 // MemberExpr's are the same if every nested MemberExpr refers to the same
12557 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12558 // the base Expr's are CXXThisExpr's.
12559 const Expr *LHSBase = LHSExpr;
12560 const Expr *RHSBase = RHSExpr;
12561 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12562 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12563 if (!LHSME || !RHSME)
12564 return;
12565
12566 while (LHSME && RHSME) {
12567 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12568 RHSME->getMemberDecl()->getCanonicalDecl())
12569 return;
12570
12571 LHSBase = LHSME->getBase();
12572 RHSBase = RHSME->getBase();
12573 LHSME = dyn_cast<MemberExpr>(LHSBase);
12574 RHSME = dyn_cast<MemberExpr>(RHSBase);
12575 }
12576
12577 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12578 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12579 if (LHSDeclRef && RHSDeclRef) {
12580 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12581 return;
12582 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12583 RHSDeclRef->getDecl()->getCanonicalDecl())
12584 return;
12585
12586 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12587 << LHSExpr->getSourceRange()
12588 << RHSExpr->getSourceRange();
12589 return;
12590 }
12591
12592 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12593 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12594 << LHSExpr->getSourceRange()
12595 << RHSExpr->getSourceRange();
12596}
12597
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012598//===--- Layout compatibility ----------------------------------------------//
12599
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012600static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012601
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012602/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012603static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012604 // C++11 [dcl.enum] p8:
12605 // Two enumeration types are layout-compatible if they have the same
12606 // underlying type.
12607 return ED1->isComplete() && ED2->isComplete() &&
12608 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12609}
12610
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012611/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012612static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12613 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012614 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12615 return false;
12616
12617 if (Field1->isBitField() != Field2->isBitField())
12618 return false;
12619
12620 if (Field1->isBitField()) {
12621 // Make sure that the bit-fields are the same length.
12622 unsigned Bits1 = Field1->getBitWidthValue(C);
12623 unsigned Bits2 = Field2->getBitWidthValue(C);
12624
12625 if (Bits1 != Bits2)
12626 return false;
12627 }
12628
12629 return true;
12630}
12631
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012632/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012633/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012634static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12635 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012636 // If both records are C++ classes, check that base classes match.
12637 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12638 // If one of records is a CXXRecordDecl we are in C++ mode,
12639 // thus the other one is a CXXRecordDecl, too.
12640 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12641 // Check number of base classes.
12642 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12643 return false;
12644
12645 // Check the base classes.
12646 for (CXXRecordDecl::base_class_const_iterator
12647 Base1 = D1CXX->bases_begin(),
12648 BaseEnd1 = D1CXX->bases_end(),
12649 Base2 = D2CXX->bases_begin();
12650 Base1 != BaseEnd1;
12651 ++Base1, ++Base2) {
12652 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12653 return false;
12654 }
12655 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12656 // If only RD2 is a C++ class, it should have zero base classes.
12657 if (D2CXX->getNumBases() > 0)
12658 return false;
12659 }
12660
12661 // Check the fields.
12662 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12663 Field2End = RD2->field_end(),
12664 Field1 = RD1->field_begin(),
12665 Field1End = RD1->field_end();
12666 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12667 if (!isLayoutCompatible(C, *Field1, *Field2))
12668 return false;
12669 }
12670 if (Field1 != Field1End || Field2 != Field2End)
12671 return false;
12672
12673 return true;
12674}
12675
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012676/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012677/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012678static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12679 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012680 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012681 for (auto *Field2 : RD2->fields())
12682 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012683
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012684 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012685 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12686 I = UnmatchedFields.begin(),
12687 E = UnmatchedFields.end();
12688
12689 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012690 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012691 bool Result = UnmatchedFields.erase(*I);
12692 (void) Result;
12693 assert(Result);
12694 break;
12695 }
12696 }
12697 if (I == E)
12698 return false;
12699 }
12700
12701 return UnmatchedFields.empty();
12702}
12703
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012704static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12705 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012706 if (RD1->isUnion() != RD2->isUnion())
12707 return false;
12708
12709 if (RD1->isUnion())
12710 return isLayoutCompatibleUnion(C, RD1, RD2);
12711 else
12712 return isLayoutCompatibleStruct(C, RD1, RD2);
12713}
12714
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012715/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012716static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012717 if (T1.isNull() || T2.isNull())
12718 return false;
12719
12720 // C++11 [basic.types] p11:
12721 // If two types T1 and T2 are the same type, then T1 and T2 are
12722 // layout-compatible types.
12723 if (C.hasSameType(T1, T2))
12724 return true;
12725
12726 T1 = T1.getCanonicalType().getUnqualifiedType();
12727 T2 = T2.getCanonicalType().getUnqualifiedType();
12728
12729 const Type::TypeClass TC1 = T1->getTypeClass();
12730 const Type::TypeClass TC2 = T2->getTypeClass();
12731
12732 if (TC1 != TC2)
12733 return false;
12734
12735 if (TC1 == Type::Enum) {
12736 return isLayoutCompatible(C,
12737 cast<EnumType>(T1)->getDecl(),
12738 cast<EnumType>(T2)->getDecl());
12739 } else if (TC1 == Type::Record) {
12740 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12741 return false;
12742
12743 return isLayoutCompatible(C,
12744 cast<RecordType>(T1)->getDecl(),
12745 cast<RecordType>(T2)->getDecl());
12746 }
12747
12748 return false;
12749}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012750
12751//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012753/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012754///
12755/// \param TypeExpr Type tag expression, as it appears in user's code.
12756///
12757/// \param VD Declaration of an identifier that appears in a type tag.
12758///
12759/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012760static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12761 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012762 while(true) {
12763 if (!TypeExpr)
12764 return false;
12765
12766 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12767
12768 switch (TypeExpr->getStmtClass()) {
12769 case Stmt::UnaryOperatorClass: {
12770 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12771 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12772 TypeExpr = UO->getSubExpr();
12773 continue;
12774 }
12775 return false;
12776 }
12777
12778 case Stmt::DeclRefExprClass: {
12779 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12780 *VD = DRE->getDecl();
12781 return true;
12782 }
12783
12784 case Stmt::IntegerLiteralClass: {
12785 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12786 llvm::APInt MagicValueAPInt = IL->getValue();
12787 if (MagicValueAPInt.getActiveBits() <= 64) {
12788 *MagicValue = MagicValueAPInt.getZExtValue();
12789 return true;
12790 } else
12791 return false;
12792 }
12793
12794 case Stmt::BinaryConditionalOperatorClass:
12795 case Stmt::ConditionalOperatorClass: {
12796 const AbstractConditionalOperator *ACO =
12797 cast<AbstractConditionalOperator>(TypeExpr);
12798 bool Result;
12799 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12800 if (Result)
12801 TypeExpr = ACO->getTrueExpr();
12802 else
12803 TypeExpr = ACO->getFalseExpr();
12804 continue;
12805 }
12806 return false;
12807 }
12808
12809 case Stmt::BinaryOperatorClass: {
12810 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12811 if (BO->getOpcode() == BO_Comma) {
12812 TypeExpr = BO->getRHS();
12813 continue;
12814 }
12815 return false;
12816 }
12817
12818 default:
12819 return false;
12820 }
12821 }
12822}
12823
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012824/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012825///
12826/// \param TypeExpr Expression that specifies a type tag.
12827///
12828/// \param MagicValues Registered magic values.
12829///
12830/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12831/// kind.
12832///
12833/// \param TypeInfo Information about the corresponding C type.
12834///
12835/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012836static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012837 const IdentifierInfo *ArgumentKind,
12838 const Expr *TypeExpr, const ASTContext &Ctx,
12839 const llvm::DenseMap<Sema::TypeTagMagicValue,
12840 Sema::TypeTagData> *MagicValues,
12841 bool &FoundWrongKind,
12842 Sema::TypeTagData &TypeInfo) {
12843 FoundWrongKind = false;
12844
12845 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012846 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012847
12848 uint64_t MagicValue;
12849
12850 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12851 return false;
12852
12853 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012854 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012855 if (I->getArgumentKind() != ArgumentKind) {
12856 FoundWrongKind = true;
12857 return false;
12858 }
12859 TypeInfo.Type = I->getMatchingCType();
12860 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12861 TypeInfo.MustBeNull = I->getMustBeNull();
12862 return true;
12863 }
12864 return false;
12865 }
12866
12867 if (!MagicValues)
12868 return false;
12869
12870 llvm::DenseMap<Sema::TypeTagMagicValue,
12871 Sema::TypeTagData>::const_iterator I =
12872 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12873 if (I == MagicValues->end())
12874 return false;
12875
12876 TypeInfo = I->second;
12877 return true;
12878}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012879
12880void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12881 uint64_t MagicValue, QualType Type,
12882 bool LayoutCompatible,
12883 bool MustBeNull) {
12884 if (!TypeTagForDatatypeMagicValues)
12885 TypeTagForDatatypeMagicValues.reset(
12886 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12887
12888 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12889 (*TypeTagForDatatypeMagicValues)[Magic] =
12890 TypeTagData(Type, LayoutCompatible, MustBeNull);
12891}
12892
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012893static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012894 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12895 if (!BT1)
12896 return false;
12897
12898 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12899 if (!BT2)
12900 return false;
12901
12902 BuiltinType::Kind T1Kind = BT1->getKind();
12903 BuiltinType::Kind T2Kind = BT2->getKind();
12904
12905 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12906 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12907 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12908 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12909}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012910
12911void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012912 const ArrayRef<const Expr *> ExprArgs,
12913 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012914 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12915 bool IsPointerAttr = Attr->getIsPointer();
12916
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012917 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012918 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12919 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012920 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012921 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012922 return;
12923 }
Joel E. Denny81508102018-03-13 14:51:22 +000012924 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012925 bool FoundWrongKind;
12926 TypeTagData TypeInfo;
12927 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12928 TypeTagForDatatypeMagicValues.get(),
12929 FoundWrongKind, TypeInfo)) {
12930 if (FoundWrongKind)
12931 Diag(TypeTagExpr->getExprLoc(),
12932 diag::warn_type_tag_for_datatype_wrong_kind)
12933 << TypeTagExpr->getSourceRange();
12934 return;
12935 }
12936
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012937 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012938 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12939 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012940 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012941 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012942 return;
12943 }
Joel E. Denny81508102018-03-13 14:51:22 +000012944 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012945 if (IsPointerAttr) {
12946 // Skip implicit cast of pointer to `void *' (as a function argument).
12947 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012948 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012949 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012950 ArgumentExpr = ICE->getSubExpr();
12951 }
12952 QualType ArgumentType = ArgumentExpr->getType();
12953
12954 // Passing a `void*' pointer shouldn't trigger a warning.
12955 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12956 return;
12957
12958 if (TypeInfo.MustBeNull) {
12959 // Type tag with matching void type requires a null pointer.
12960 if (!ArgumentExpr->isNullPointerConstant(Context,
12961 Expr::NPC_ValueDependentIsNotNull)) {
12962 Diag(ArgumentExpr->getExprLoc(),
12963 diag::warn_type_safety_null_pointer_required)
12964 << ArgumentKind->getName()
12965 << ArgumentExpr->getSourceRange()
12966 << TypeTagExpr->getSourceRange();
12967 }
12968 return;
12969 }
12970
12971 QualType RequiredType = TypeInfo.Type;
12972 if (IsPointerAttr)
12973 RequiredType = Context.getPointerType(RequiredType);
12974
12975 bool mismatch = false;
12976 if (!TypeInfo.LayoutCompatible) {
12977 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12978
12979 // C++11 [basic.fundamental] p1:
12980 // Plain char, signed char, and unsigned char are three distinct types.
12981 //
12982 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12983 // char' depending on the current char signedness mode.
12984 if (mismatch)
12985 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12986 RequiredType->getPointeeType())) ||
12987 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12988 mismatch = false;
12989 } else
12990 if (IsPointerAttr)
12991 mismatch = !isLayoutCompatible(Context,
12992 ArgumentType->getPointeeType(),
12993 RequiredType->getPointeeType());
12994 else
12995 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12996
12997 if (mismatch)
12998 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012999 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000013000 << TypeInfo.LayoutCompatible << RequiredType
13001 << ArgumentExpr->getSourceRange()
13002 << TypeTagExpr->getSourceRange();
13003}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013004
13005void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13006 CharUnits Alignment) {
13007 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13008}
13009
13010void Sema::DiagnoseMisalignedMembers() {
13011 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000013012 const NamedDecl *ND = m.RD;
13013 if (ND->getName().empty()) {
13014 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13015 ND = TD;
13016 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013017 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000013018 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013019 }
13020 MisalignedMembers.clear();
13021}
13022
13023void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013024 E = E->IgnoreParens();
13025 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013026 return;
13027 if (isa<UnaryOperator>(E) &&
13028 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13029 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13030 if (isa<MemberExpr>(Op)) {
13031 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13032 MisalignedMember(Op));
13033 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013034 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000013035 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13036 Context.getTypeAlignInChars(
13037 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013038 MisalignedMembers.erase(MA);
13039 }
13040 }
13041}
13042
13043void Sema::RefersToMemberWithReducedAlignment(
13044 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000013045 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13046 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013047 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013048 if (!ME)
13049 return;
13050
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000013051 // No need to check expressions with an __unaligned-qualified type.
13052 if (E->getType().getQualifiers().hasUnaligned())
13053 return;
13054
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013055 // For a chain of MemberExpr like "a.b.c.d" this list
13056 // will keep FieldDecl's like [d, c, b].
13057 SmallVector<FieldDecl *, 4> ReverseMemberChain;
13058 const MemberExpr *TopME = nullptr;
13059 bool AnyIsPacked = false;
13060 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013061 QualType BaseType = ME->getBase()->getType();
13062 if (ME->isArrow())
13063 BaseType = BaseType->getPointeeType();
13064 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000013065 if (RD->isInvalidDecl())
13066 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013067
13068 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013069 auto *FD = dyn_cast<FieldDecl>(MD);
13070 // We do not care about non-data members.
13071 if (!FD || FD->isInvalidDecl())
13072 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013073
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013074 AnyIsPacked =
13075 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13076 ReverseMemberChain.push_back(FD);
13077
13078 TopME = ME;
13079 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13080 } while (ME);
13081 assert(TopME && "We did not compute a topmost MemberExpr!");
13082
13083 // Not the scope of this diagnostic.
13084 if (!AnyIsPacked)
13085 return;
13086
13087 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13088 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13089 // TODO: The innermost base of the member expression may be too complicated.
13090 // For now, just disregard these cases. This is left for future
13091 // improvement.
13092 if (!DRE && !isa<CXXThisExpr>(TopBase))
13093 return;
13094
13095 // Alignment expected by the whole expression.
13096 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13097
13098 // No need to do anything else with this case.
13099 if (ExpectedAlignment.isOne())
13100 return;
13101
13102 // Synthesize offset of the whole access.
13103 CharUnits Offset;
13104 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13105 I++) {
13106 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13107 }
13108
13109 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13110 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13111 ReverseMemberChain.back()->getParent()->getTypeForDecl());
13112
13113 // The base expression of the innermost MemberExpr may give
13114 // stronger guarantees than the class containing the member.
13115 if (DRE && !TopME->isArrow()) {
13116 const ValueDecl *VD = DRE->getDecl();
13117 if (!VD->getType()->isReferenceType())
13118 CompleteObjectAlignment =
13119 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13120 }
13121
13122 // Check if the synthesized offset fulfills the alignment.
13123 if (Offset % ExpectedAlignment != 0 ||
13124 // It may fulfill the offset it but the effective alignment may still be
13125 // lower than the expected expression alignment.
13126 CompleteObjectAlignment < ExpectedAlignment) {
13127 // If this happens, we want to determine a sensible culprit of this.
13128 // Intuitively, watching the chain of member expressions from right to
13129 // left, we start with the required alignment (as required by the field
13130 // type) but some packed attribute in that chain has reduced the alignment.
13131 // It may happen that another packed structure increases it again. But if
13132 // we are here such increase has not been enough. So pointing the first
13133 // FieldDecl that either is packed or else its RecordDecl is,
13134 // seems reasonable.
13135 FieldDecl *FD = nullptr;
13136 CharUnits Alignment;
13137 for (FieldDecl *FDI : ReverseMemberChain) {
13138 if (FDI->hasAttr<PackedAttr>() ||
13139 FDI->getParent()->hasAttr<PackedAttr>()) {
13140 FD = FDI;
13141 Alignment = std::min(
13142 Context.getTypeAlignInChars(FD->getType()),
13143 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13144 break;
13145 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013146 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000013147 assert(FD && "We did not find a packed FieldDecl!");
13148 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013149 }
13150}
13151
13152void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13153 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000013154
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000013155 RefersToMemberWithReducedAlignment(
13156 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13157 _2, _3, _4));
13158}