blob: 74ecf5fef79558639c30d4dc1d2fe7783e4b8e41 [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) {
200 Expr *Arg = TheCall->getArg(I);
201 QualType Ty = Arg->getType();
202 if (!Ty->isIntegerType()) {
203 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
204 << Ty << Arg->getSourceRange();
205 return true;
206 }
207 }
208
209 // Third argument should be a pointer to a non-const integer.
210 // IRGen correctly handles volatile, restrict, and address spaces, and
211 // the other qualifiers aren't possible.
212 {
213 Expr *Arg = TheCall->getArg(2);
214 QualType Ty = Arg->getType();
215 const auto *PtrTy = Ty->getAs<PointerType>();
216 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
217 !PtrTy->getPointeeType().isConstQualified())) {
218 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
219 << Ty << Arg->getSourceRange();
220 return true;
221 }
222 }
223
224 return false;
225}
226
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000227static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
Nico Weberade321e2018-04-10 18:53:28 +0000228 CallExpr *TheCall, unsigned SizeIdx,
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000229 unsigned DstSizeIdx) {
230 if (TheCall->getNumArgs() <= SizeIdx ||
231 TheCall->getNumArgs() <= DstSizeIdx)
232 return;
233
234 const Expr *SizeArg = TheCall->getArg(SizeIdx);
235 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
236
237 llvm::APSInt Size, DstSize;
238
239 // find out if both sizes are known at compile time
240 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
241 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
242 return;
243
244 if (Size.ule(DstSize))
245 return;
246
247 // confirmed overflow so generate the diagnostic.
248 IdentifierInfo *FnName = FDecl->getIdentifier();
249 SourceLocation SL = TheCall->getLocStart();
250 SourceRange SR = TheCall->getSourceRange();
251
252 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
253}
254
Peter Collingbournef7706832014-12-12 23:41:25 +0000255static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
256 if (checkArgCount(S, BuiltinCall, 2))
257 return true;
258
259 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
260 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
261 Expr *Call = BuiltinCall->getArg(0);
262 Expr *Chain = BuiltinCall->getArg(1);
263
264 if (Call->getStmtClass() != Stmt::CallExprClass) {
265 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
266 << Call->getSourceRange();
267 return true;
268 }
269
270 auto CE = cast<CallExpr>(Call);
271 if (CE->getCallee()->getType()->isBlockPointerType()) {
272 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
273 << Call->getSourceRange();
274 return true;
275 }
276
277 const Decl *TargetDecl = CE->getCalleeDecl();
278 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
279 if (FD->getBuiltinID()) {
280 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
281 << Call->getSourceRange();
282 return true;
283 }
284
285 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
286 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
287 << Call->getSourceRange();
288 return true;
289 }
290
291 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
292 if (ChainResult.isInvalid())
293 return true;
294 if (!ChainResult.get()->getType()->isPointerType()) {
295 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
296 << Chain->getSourceRange();
297 return true;
298 }
299
David Majnemerced8bdf2015-02-25 17:36:15 +0000300 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000301 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
302 QualType BuiltinTy = S.Context.getFunctionType(
303 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
304 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
305
306 Builtin =
307 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
308
309 BuiltinCall->setType(CE->getType());
310 BuiltinCall->setValueKind(CE->getValueKind());
311 BuiltinCall->setObjectKind(CE->getObjectKind());
312 BuiltinCall->setCallee(Builtin);
313 BuiltinCall->setArg(1, ChainResult.get());
314
315 return false;
316}
317
Reid Kleckner1d59f992015-01-22 01:36:17 +0000318static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
319 Scope::ScopeFlags NeededScopeFlags,
320 unsigned DiagID) {
321 // Scopes aren't available during instantiation. Fortunately, builtin
322 // functions cannot be template args so they cannot be formed through template
323 // instantiation. Therefore checking once during the parse is sufficient.
Richard Smith51ec0cf2017-02-21 01:17:38 +0000324 if (SemaRef.inTemplateInstantiation())
Reid Kleckner1d59f992015-01-22 01:36:17 +0000325 return false;
326
327 Scope *S = SemaRef.getCurScope();
328 while (S && !S->isSEHExceptScope())
329 S = S->getParent();
330 if (!S || !(S->getFlags() & NeededScopeFlags)) {
331 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
332 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
333 << DRE->getDecl()->getIdentifier();
334 return true;
335 }
336
337 return false;
338}
339
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000340static inline bool isBlockPointer(Expr *Arg) {
341 return Arg->getType()->isBlockPointerType();
342}
343
344/// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
345/// void*, which is a requirement of device side enqueue.
346static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
347 const BlockPointerType *BPT =
348 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
349 ArrayRef<QualType> Params =
350 BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
351 unsigned ArgCounter = 0;
352 bool IllegalParams = false;
353 // Iterate through the block parameters until either one is found that is not
354 // a local void*, or the block is valid.
355 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
356 I != E; ++I, ++ArgCounter) {
357 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
358 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
359 LangAS::opencl_local) {
360 // Get the location of the error. If a block literal has been passed
361 // (BlockExpr) then we can point straight to the offending argument,
362 // else we just point to the variable reference.
363 SourceLocation ErrorLoc;
364 if (isa<BlockExpr>(BlockArg)) {
365 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
366 ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
367 } else if (isa<DeclRefExpr>(BlockArg)) {
368 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
369 }
370 S.Diag(ErrorLoc,
371 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
372 IllegalParams = true;
373 }
374 }
375
376 return IllegalParams;
377}
378
Joey Gouly84ae3362017-07-31 15:15:59 +0000379static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
380 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
381 S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
382 << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
383 return true;
384 }
385 return false;
386}
387
Joey Goulyfa76b492017-08-01 13:27:09 +0000388static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
389 if (checkArgCount(S, TheCall, 2))
390 return true;
391
392 if (checkOpenCLSubgroupExt(S, TheCall))
393 return true;
394
395 // First argument is an ndrange_t type.
396 Expr *NDRangeArg = TheCall->getArg(0);
Yaxun Liub7318e02017-10-13 03:37:48 +0000397 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Joey Goulyfa76b492017-08-01 13:27:09 +0000398 S.Diag(NDRangeArg->getLocStart(),
399 diag::err_opencl_builtin_expected_type)
400 << TheCall->getDirectCallee() << "'ndrange_t'";
401 return true;
402 }
403
404 Expr *BlockArg = TheCall->getArg(1);
405 if (!isBlockPointer(BlockArg)) {
406 S.Diag(BlockArg->getLocStart(),
407 diag::err_opencl_builtin_expected_type)
408 << TheCall->getDirectCallee() << "block";
409 return true;
410 }
411 return checkOpenCLBlockArgs(S, BlockArg);
412}
413
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000414/// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
415/// get_kernel_work_group_size
416/// and get_kernel_preferred_work_group_size_multiple builtin functions.
417static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
418 if (checkArgCount(S, TheCall, 1))
419 return true;
420
421 Expr *BlockArg = TheCall->getArg(0);
422 if (!isBlockPointer(BlockArg)) {
423 S.Diag(BlockArg->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000424 diag::err_opencl_builtin_expected_type)
425 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000426 return true;
427 }
428 return checkOpenCLBlockArgs(S, BlockArg);
429}
430
Simon Pilgrim2c518802017-03-30 14:13:19 +0000431/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000432static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
433 const QualType &IntType);
434
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000435static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
Anastasia Stulova0df4ac32016-11-14 17:39:58 +0000436 unsigned Start, unsigned End) {
437 bool IllegalParams = false;
438 for (unsigned I = Start; I <= End; ++I)
439 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
440 S.Context.getSizeType());
441 return IllegalParams;
442}
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000443
444/// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
445/// 'local void*' parameter of passed block.
446static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
447 Expr *BlockArg,
448 unsigned NumNonVarArgs) {
449 const BlockPointerType *BPT =
450 cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
451 unsigned NumBlockParams =
452 BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
453 unsigned TotalNumArgs = TheCall->getNumArgs();
454
455 // For each argument passed to the block, a corresponding uint needs to
456 // be passed to describe the size of the local memory.
457 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
458 S.Diag(TheCall->getLocStart(),
459 diag::err_opencl_enqueue_kernel_local_size_args);
460 return true;
461 }
462
463 // Check that the sizes of the local memory are specified by integers.
464 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
465 TotalNumArgs - 1);
466}
467
468/// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
469/// overload formats specified in Table 6.13.17.1.
470/// int enqueue_kernel(queue_t queue,
471/// kernel_enqueue_flags_t flags,
472/// const ndrange_t ndrange,
473/// void (^block)(void))
474/// int enqueue_kernel(queue_t queue,
475/// kernel_enqueue_flags_t flags,
476/// const ndrange_t ndrange,
477/// uint num_events_in_wait_list,
478/// clk_event_t *event_wait_list,
479/// clk_event_t *event_ret,
480/// void (^block)(void))
481/// int enqueue_kernel(queue_t queue,
482/// kernel_enqueue_flags_t flags,
483/// const ndrange_t ndrange,
484/// void (^block)(local void*, ...),
485/// uint size0, ...)
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)(local void*, ...),
493/// uint size0, ...)
494static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
495 unsigned NumArgs = TheCall->getNumArgs();
496
497 if (NumArgs < 4) {
498 S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
499 return true;
500 }
501
502 Expr *Arg0 = TheCall->getArg(0);
503 Expr *Arg1 = TheCall->getArg(1);
504 Expr *Arg2 = TheCall->getArg(2);
505 Expr *Arg3 = TheCall->getArg(3);
506
507 // First argument always needs to be a queue_t type.
508 if (!Arg0->getType()->isQueueT()) {
509 S.Diag(TheCall->getArg(0)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000510 diag::err_opencl_builtin_expected_type)
511 << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000512 return true;
513 }
514
515 // Second argument always needs to be a kernel_enqueue_flags_t enum value.
516 if (!Arg1->getType()->isIntegerType()) {
517 S.Diag(TheCall->getArg(1)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000518 diag::err_opencl_builtin_expected_type)
519 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000520 return true;
521 }
522
523 // Third argument is always an ndrange_t type.
Anastasia Stulovab42f3c02017-04-21 15:13:24 +0000524 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000525 S.Diag(TheCall->getArg(2)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000526 diag::err_opencl_builtin_expected_type)
527 << TheCall->getDirectCallee() << "'ndrange_t'";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000528 return true;
529 }
530
531 // With four arguments, there is only one form that the function could be
532 // called in: no events and no variable arguments.
533 if (NumArgs == 4) {
534 // check that the last argument is the right block type.
535 if (!isBlockPointer(Arg3)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000536 S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
537 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000538 return true;
539 }
540 // we have a block type, check the prototype
541 const BlockPointerType *BPT =
542 cast<BlockPointerType>(Arg3->getType().getCanonicalType());
543 if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
544 S.Diag(Arg3->getLocStart(),
545 diag::err_opencl_enqueue_kernel_blocks_no_args);
546 return true;
547 }
548 return false;
549 }
550 // we can have block + varargs.
551 if (isBlockPointer(Arg3))
552 return (checkOpenCLBlockArgs(S, Arg3) ||
553 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
554 // last two cases with either exactly 7 args or 7 args and varargs.
555 if (NumArgs >= 7) {
556 // check common block argument.
557 Expr *Arg6 = TheCall->getArg(6);
558 if (!isBlockPointer(Arg6)) {
Joey Gouly6b03d952017-07-04 11:50:23 +0000559 S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
560 << TheCall->getDirectCallee() << "block";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000561 return true;
562 }
563 if (checkOpenCLBlockArgs(S, Arg6))
564 return true;
565
566 // Forth argument has to be any integer type.
567 if (!Arg3->getType()->isIntegerType()) {
568 S.Diag(TheCall->getArg(3)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000569 diag::err_opencl_builtin_expected_type)
570 << TheCall->getDirectCallee() << "integer";
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000571 return true;
572 }
573 // check remaining common arguments.
574 Expr *Arg4 = TheCall->getArg(4);
575 Expr *Arg5 = TheCall->getArg(5);
576
Anastasia Stulova2b461202016-11-14 15:34:01 +0000577 // Fifth argument is always passed as a pointer to clk_event_t.
578 if (!Arg4->isNullPointerConstant(S.Context,
579 Expr::NPC_ValueDependentIsNotNull) &&
580 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000581 S.Diag(TheCall->getArg(4)->getLocStart(),
Joey Gouly6b03d952017-07-04 11:50:23 +0000582 diag::err_opencl_builtin_expected_type)
583 << TheCall->getDirectCallee()
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000584 << S.Context.getPointerType(S.Context.OCLClkEventTy);
585 return true;
586 }
587
Anastasia Stulova2b461202016-11-14 15:34:01 +0000588 // Sixth argument is always passed as a pointer to clk_event_t.
589 if (!Arg5->isNullPointerConstant(S.Context,
590 Expr::NPC_ValueDependentIsNotNull) &&
591 !(Arg5->getType()->isPointerType() &&
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +0000592 Arg5->getType()->getPointeeType()->isClkEventT())) {
593 S.Diag(TheCall->getArg(5)->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
600 if (NumArgs == 7)
601 return false;
602
603 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
604 }
605
606 // None of the specific case has been detected, give generic error
607 S.Diag(TheCall->getLocStart(),
608 diag::err_opencl_enqueue_kernel_incorrect_args);
609 return true;
610}
611
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000612/// Returns OpenCL access qual.
Xiuli Pan11e13f62016-02-26 03:13:03 +0000613static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
Xiuli Pan11e13f62016-02-26 03:13:03 +0000614 return D->getAttr<OpenCLAccessAttr>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000615}
616
617/// Returns true if pipe element type is different from the pointer.
618static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
619 const Expr *Arg0 = Call->getArg(0);
620 // First argument type should always be pipe.
621 if (!Arg0->getType()->isPipeType()) {
622 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000623 << Call->getDirectCallee() << Arg0->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000624 return true;
625 }
Xiuli Pan11e13f62016-02-26 03:13:03 +0000626 OpenCLAccessAttr *AccessQual =
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000627 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
628 // Validates the access qualifier is compatible with the call.
629 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
630 // read_only and write_only, and assumed to be read_only if no qualifier is
631 // specified.
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000632 switch (Call->getDirectCallee()->getBuiltinID()) {
633 case Builtin::BIread_pipe:
634 case Builtin::BIreserve_read_pipe:
635 case Builtin::BIcommit_read_pipe:
636 case Builtin::BIwork_group_reserve_read_pipe:
637 case Builtin::BIsub_group_reserve_read_pipe:
638 case Builtin::BIwork_group_commit_read_pipe:
639 case Builtin::BIsub_group_commit_read_pipe:
640 if (!(!AccessQual || AccessQual->isReadOnly())) {
641 S.Diag(Arg0->getLocStart(),
642 diag::err_opencl_builtin_pipe_invalid_access_modifier)
643 << "read_only" << Arg0->getSourceRange();
644 return true;
645 }
646 break;
647 case Builtin::BIwrite_pipe:
648 case Builtin::BIreserve_write_pipe:
649 case Builtin::BIcommit_write_pipe:
650 case Builtin::BIwork_group_reserve_write_pipe:
651 case Builtin::BIsub_group_reserve_write_pipe:
652 case Builtin::BIwork_group_commit_write_pipe:
653 case Builtin::BIsub_group_commit_write_pipe:
654 if (!(AccessQual && AccessQual->isWriteOnly())) {
655 S.Diag(Arg0->getLocStart(),
656 diag::err_opencl_builtin_pipe_invalid_access_modifier)
657 << "write_only" << Arg0->getSourceRange();
658 return true;
659 }
660 break;
661 default:
662 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000663 }
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000664 return false;
665}
666
667/// Returns true if pipe element type is different from the pointer.
668static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
669 const Expr *Arg0 = Call->getArg(0);
670 const Expr *ArgIdx = Call->getArg(Idx);
671 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000672 const QualType EltTy = PipeTy->getElementType();
673 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000674 // The Idx argument should be a pointer and the type of the pointer and
675 // the type of pipe element should also be the same.
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000676 if (!ArgTy ||
677 !S.Context.hasSameType(
678 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000679 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000680 << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000681 << ArgIdx->getType() << ArgIdx->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000682 return true;
683 }
684 return false;
685}
686
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000687// Performs semantic analysis for the read/write_pipe call.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000688// \param S Reference to the semantic analyzer.
689// \param Call A pointer to the builtin call.
690// \return True if a semantic error has been found, false otherwise.
691static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000692 // OpenCL v2.0 s6.13.16.2 - The built-in read/write
693 // functions have two forms.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000694 switch (Call->getNumArgs()) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000695 case 2:
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000696 if (checkOpenCLPipeArg(S, Call))
697 return true;
698 // The call with 2 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000699 // read/write_pipe(pipe T, T*).
700 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000701 if (checkOpenCLPipePacketType(S, Call, 1))
702 return true;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000703 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000704
705 case 4: {
706 if (checkOpenCLPipeArg(S, Call))
707 return true;
708 // The call with 4 arguments should be
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000709 // read/write_pipe(pipe T, reserve_id_t, uint, T*).
710 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000711 if (!Call->getArg(1)->getType()->isReserveIDT()) {
712 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000713 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000714 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000715 return true;
716 }
717
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000718 // Check the index.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000719 const Expr *Arg2 = Call->getArg(2);
720 if (!Arg2->getType()->isIntegerType() &&
721 !Arg2->getType()->isUnsignedIntegerType()) {
722 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000723 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000724 << Arg2->getType() << Arg2->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000725 return true;
726 }
727
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000728 // Check packet type T.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000729 if (checkOpenCLPipePacketType(S, Call, 3))
730 return true;
731 } break;
732 default:
733 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000734 << Call->getDirectCallee() << Call->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000735 return true;
736 }
737
738 return false;
739}
740
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000741// Performs a semantic analysis on the {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000742// /_}reserve_{read/write}_pipe
743// \param S Reference to the semantic analyzer.
744// \param Call The call to the builtin function to be analyzed.
745// \return True if a semantic error was found, false otherwise.
746static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
747 if (checkArgCount(S, Call, 2))
748 return true;
749
750 if (checkOpenCLPipeArg(S, Call))
751 return true;
752
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000753 // Check the reserve size.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000754 if (!Call->getArg(1)->getType()->isIntegerType() &&
755 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
756 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000757 << Call->getDirectCallee() << S.Context.UnsignedIntTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000758 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000759 return true;
760 }
761
Joey Gouly922ca232017-08-09 14:52:47 +0000762 // Since return type of reserve_read/write_pipe built-in function is
763 // reserve_id_t, which is not defined in the builtin def file , we used int
764 // as return type and need to override the return type of these functions.
765 Call->setType(S.Context.OCLReserveIDTy);
766
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000767 return false;
768}
769
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000770// Performs a semantic analysis on {work_group_/sub_group_
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000771// /_}commit_{read/write}_pipe
772// \param S Reference to the semantic analyzer.
773// \param Call The call to the builtin function to be analyzed.
774// \return True if a semantic error was found, false otherwise.
775static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
776 if (checkArgCount(S, Call, 2))
777 return true;
778
779 if (checkOpenCLPipeArg(S, Call))
780 return true;
781
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000782 // Check reserve_id_t.
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000783 if (!Call->getArg(1)->getType()->isReserveIDT()) {
784 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000785 << Call->getDirectCallee() << S.Context.OCLReserveIDTy
Xiuli Pan0a1c6c22016-03-30 04:46:32 +0000786 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000787 return true;
788 }
789
790 return false;
791}
792
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000793// Performs a semantic analysis on the call to built-in Pipe
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000794// Query Functions.
795// \param S Reference to the semantic analyzer.
796// \param Call The call to the builtin function to be analyzed.
797// \return True if a semantic error was found, false otherwise.
798static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
799 if (checkArgCount(S, Call, 1))
800 return true;
801
802 if (!Call->getArg(0)->getType()->isPipeType()) {
803 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
Xiuli Pan4415bdb2016-03-04 07:11:16 +0000804 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000805 return true;
806 }
807
808 return false;
809}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +0000810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811// OpenCL v2.0 s6.13.9 - Address space qualifier functions.
812// Performs semantic analysis for the to_global/local/private call.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000813// \param S Reference to the semantic analyzer.
814// \param BuiltinID ID of the builtin function.
815// \param Call A pointer to the builtin call.
816// \return True if a semantic error has been found, false otherwise.
817static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
818 CallExpr *Call) {
Yaxun Liuf7449a12016-05-20 19:54:38 +0000819 if (Call->getNumArgs() != 1) {
820 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
821 << Call->getDirectCallee() << Call->getSourceRange();
822 return true;
823 }
824
825 auto RT = Call->getArg(0)->getType();
826 if (!RT->isPointerType() || RT->getPointeeType()
827 .getAddressSpace() == LangAS::opencl_constant) {
828 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
829 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
830 return true;
831 }
832
833 RT = RT->getPointeeType();
834 auto Qual = RT.getQualifiers();
835 switch (BuiltinID) {
836 case Builtin::BIto_global:
837 Qual.setAddressSpace(LangAS::opencl_global);
838 break;
839 case Builtin::BIto_local:
840 Qual.setAddressSpace(LangAS::opencl_local);
841 break;
Yaxun Liub7318e02017-10-13 03:37:48 +0000842 case Builtin::BIto_private:
843 Qual.setAddressSpace(LangAS::opencl_private);
844 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +0000845 default:
Yaxun Liub7318e02017-10-13 03:37:48 +0000846 llvm_unreachable("Invalid builtin function");
Yaxun Liuf7449a12016-05-20 19:54:38 +0000847 }
848 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
849 RT.getUnqualifiedType(), Qual)));
850
851 return false;
852}
853
John McCalldadc5752010-08-24 06:29:42 +0000854ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000855Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
856 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000857 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000858
Chris Lattner3be167f2010-10-01 23:23:24 +0000859 // Find out if any arguments are required to be integer constant expressions.
860 unsigned ICEArguments = 0;
861 ASTContext::GetBuiltinTypeError Error;
862 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
863 if (Error != ASTContext::GE_None)
864 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
865
866 // If any arguments are required to be ICE's, check and diagnose.
867 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
868 // Skip arguments not required to be ICE's.
869 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
870
871 llvm::APSInt Result;
872 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
873 return true;
874 ICEArguments &= ~(1 << ArgNo);
875 }
876
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000877 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000878 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000879 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000880 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000881 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000882 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000883 break;
Martin Storsjo022e7822017-07-17 20:49:45 +0000884 case Builtin::BI__builtin_ms_va_start:
Ted Kremeneka174c522008-07-09 17:58:53 +0000885 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000886 case Builtin::BI__builtin_va_start:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000887 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000888 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000889 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000890 case Builtin::BI__va_start: {
891 switch (Context.getTargetInfo().getTriple().getArch()) {
892 case llvm::Triple::arm:
893 case llvm::Triple::thumb:
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +0000894 if (SemaBuiltinVAStartARMMicrosoft(TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000895 return ExprError();
896 break;
897 default:
Reid Kleckner2b0fa122017-05-02 20:10:03 +0000898 if (SemaBuiltinVAStart(BuiltinID, TheCall))
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000899 return ExprError();
900 break;
901 }
902 break;
903 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000904 case Builtin::BI__builtin_isgreater:
905 case Builtin::BI__builtin_isgreaterequal:
906 case Builtin::BI__builtin_isless:
907 case Builtin::BI__builtin_islessequal:
908 case Builtin::BI__builtin_islessgreater:
909 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000910 if (SemaBuiltinUnorderedCompare(TheCall))
911 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000912 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000913 case Builtin::BI__builtin_fpclassify:
914 if (SemaBuiltinFPClassification(TheCall, 6))
915 return ExprError();
916 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000917 case Builtin::BI__builtin_isfinite:
918 case Builtin::BI__builtin_isinf:
919 case Builtin::BI__builtin_isinf_sign:
920 case Builtin::BI__builtin_isnan:
921 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000922 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000923 return ExprError();
924 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000925 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000926 return SemaBuiltinShuffleVector(TheCall);
927 // TheCall will be freed by the smart pointer here, but that's fine, since
928 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000929 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000930 if (SemaBuiltinPrefetch(TheCall))
931 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000932 break;
David Majnemer51169932016-10-31 05:37:48 +0000933 case Builtin::BI__builtin_alloca_with_align:
934 if (SemaBuiltinAllocaWithAlign(TheCall))
935 return ExprError();
936 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000937 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000938 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000939 if (SemaBuiltinAssume(TheCall))
940 return ExprError();
941 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000942 case Builtin::BI__builtin_assume_aligned:
943 if (SemaBuiltinAssumeAligned(TheCall))
944 return ExprError();
945 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000946 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000947 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000948 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000949 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000950 case Builtin::BI__builtin_longjmp:
951 if (SemaBuiltinLongjmp(TheCall))
952 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000953 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000954 case Builtin::BI__builtin_setjmp:
955 if (SemaBuiltinSetjmp(TheCall))
956 return ExprError();
957 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000958 case Builtin::BI_setjmp:
959 case Builtin::BI_setjmpex:
960 if (checkArgCount(*this, TheCall, 1))
961 return true;
962 break;
John McCallbebede42011-02-26 05:39:39 +0000963 case Builtin::BI__builtin_classify_type:
964 if (checkArgCount(*this, TheCall, 1)) return true;
965 TheCall->setType(Context.IntTy);
966 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000967 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000968 if (checkArgCount(*this, TheCall, 1)) return true;
969 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000970 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000971 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000972 case Builtin::BI__sync_fetch_and_add_1:
973 case Builtin::BI__sync_fetch_and_add_2:
974 case Builtin::BI__sync_fetch_and_add_4:
975 case Builtin::BI__sync_fetch_and_add_8:
976 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000977 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000978 case Builtin::BI__sync_fetch_and_sub_1:
979 case Builtin::BI__sync_fetch_and_sub_2:
980 case Builtin::BI__sync_fetch_and_sub_4:
981 case Builtin::BI__sync_fetch_and_sub_8:
982 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000983 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000984 case Builtin::BI__sync_fetch_and_or_1:
985 case Builtin::BI__sync_fetch_and_or_2:
986 case Builtin::BI__sync_fetch_and_or_4:
987 case Builtin::BI__sync_fetch_and_or_8:
988 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000989 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000990 case Builtin::BI__sync_fetch_and_and_1:
991 case Builtin::BI__sync_fetch_and_and_2:
992 case Builtin::BI__sync_fetch_and_and_4:
993 case Builtin::BI__sync_fetch_and_and_8:
994 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000995 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000996 case Builtin::BI__sync_fetch_and_xor_1:
997 case Builtin::BI__sync_fetch_and_xor_2:
998 case Builtin::BI__sync_fetch_and_xor_4:
999 case Builtin::BI__sync_fetch_and_xor_8:
1000 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001001 case Builtin::BI__sync_fetch_and_nand:
1002 case Builtin::BI__sync_fetch_and_nand_1:
1003 case Builtin::BI__sync_fetch_and_nand_2:
1004 case Builtin::BI__sync_fetch_and_nand_4:
1005 case Builtin::BI__sync_fetch_and_nand_8:
1006 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001007 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001008 case Builtin::BI__sync_add_and_fetch_1:
1009 case Builtin::BI__sync_add_and_fetch_2:
1010 case Builtin::BI__sync_add_and_fetch_4:
1011 case Builtin::BI__sync_add_and_fetch_8:
1012 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001013 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001014 case Builtin::BI__sync_sub_and_fetch_1:
1015 case Builtin::BI__sync_sub_and_fetch_2:
1016 case Builtin::BI__sync_sub_and_fetch_4:
1017 case Builtin::BI__sync_sub_and_fetch_8:
1018 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001019 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001020 case Builtin::BI__sync_and_and_fetch_1:
1021 case Builtin::BI__sync_and_and_fetch_2:
1022 case Builtin::BI__sync_and_and_fetch_4:
1023 case Builtin::BI__sync_and_and_fetch_8:
1024 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001025 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001026 case Builtin::BI__sync_or_and_fetch_1:
1027 case Builtin::BI__sync_or_and_fetch_2:
1028 case Builtin::BI__sync_or_and_fetch_4:
1029 case Builtin::BI__sync_or_and_fetch_8:
1030 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001031 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +00001032 case Builtin::BI__sync_xor_and_fetch_1:
1033 case Builtin::BI__sync_xor_and_fetch_2:
1034 case Builtin::BI__sync_xor_and_fetch_4:
1035 case Builtin::BI__sync_xor_and_fetch_8:
1036 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001037 case Builtin::BI__sync_nand_and_fetch:
1038 case Builtin::BI__sync_nand_and_fetch_1:
1039 case Builtin::BI__sync_nand_and_fetch_2:
1040 case Builtin::BI__sync_nand_and_fetch_4:
1041 case Builtin::BI__sync_nand_and_fetch_8:
1042 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001043 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001044 case Builtin::BI__sync_val_compare_and_swap_1:
1045 case Builtin::BI__sync_val_compare_and_swap_2:
1046 case Builtin::BI__sync_val_compare_and_swap_4:
1047 case Builtin::BI__sync_val_compare_and_swap_8:
1048 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001049 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001050 case Builtin::BI__sync_bool_compare_and_swap_1:
1051 case Builtin::BI__sync_bool_compare_and_swap_2:
1052 case Builtin::BI__sync_bool_compare_and_swap_4:
1053 case Builtin::BI__sync_bool_compare_and_swap_8:
1054 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001055 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +00001056 case Builtin::BI__sync_lock_test_and_set_1:
1057 case Builtin::BI__sync_lock_test_and_set_2:
1058 case Builtin::BI__sync_lock_test_and_set_4:
1059 case Builtin::BI__sync_lock_test_and_set_8:
1060 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +00001061 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001062 case Builtin::BI__sync_lock_release_1:
1063 case Builtin::BI__sync_lock_release_2:
1064 case Builtin::BI__sync_lock_release_4:
1065 case Builtin::BI__sync_lock_release_8:
1066 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001067 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001068 case Builtin::BI__sync_swap_1:
1069 case Builtin::BI__sync_swap_2:
1070 case Builtin::BI__sync_swap_4:
1071 case Builtin::BI__sync_swap_8:
1072 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001073 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001074 case Builtin::BI__builtin_nontemporal_load:
1075 case Builtin::BI__builtin_nontemporal_store:
1076 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +00001077#define BUILTIN(ID, TYPE, ATTRS)
1078#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1079 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001080 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +00001081#include "clang/Basic/Builtins.def"
Reid Kleckner30701ed2017-09-05 20:27:35 +00001082 case Builtin::BI__annotation:
1083 if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1084 return ExprError();
1085 break;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001086 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +00001087 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001088 return ExprError();
1089 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +00001090 case Builtin::BI__builtin_addressof:
1091 if (SemaBuiltinAddressof(*this, TheCall))
1092 return ExprError();
1093 break;
John McCall03107a42015-10-29 20:48:01 +00001094 case Builtin::BI__builtin_add_overflow:
1095 case Builtin::BI__builtin_sub_overflow:
1096 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +00001097 if (SemaBuiltinOverflow(*this, TheCall))
1098 return ExprError();
1099 break;
Richard Smith760520b2014-06-03 23:27:44 +00001100 case Builtin::BI__builtin_operator_new:
Eric Fiselierfa752f22018-03-21 19:19:48 +00001101 case Builtin::BI__builtin_operator_delete: {
1102 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1103 ExprResult Res =
1104 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1105 if (Res.isInvalid())
1106 CorrectDelayedTyposInExpr(TheCallResult.get());
1107 return Res;
1108 }
Aaron Ballman06525342018-04-10 21:58:13 +00001109 case Builtin::BI__builtin_dump_struct: {
1110 // We first want to ensure we are called with 2 arguments
1111 if (checkArgCount(*this, TheCall, 2))
1112 return ExprError();
1113 // Ensure that the first argument is of type 'struct XX *'
1114 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1115 const QualType PtrArgType = PtrArg->getType();
1116 if (!PtrArgType->isPointerType() ||
1117 !PtrArgType->getPointeeType()->isRecordType()) {
1118 Diag(PtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1119 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1120 << "structure pointer";
1121 return ExprError();
1122 }
1123
1124 // Ensure that the second argument is of type 'FunctionType'
1125 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1126 const QualType FnPtrArgType = FnPtrArg->getType();
1127 if (!FnPtrArgType->isPointerType()) {
1128 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1129 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1130 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1131 return ExprError();
1132 }
1133
1134 const auto *FuncType =
1135 FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1136
1137 if (!FuncType) {
1138 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1139 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1140 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1141 return ExprError();
1142 }
1143
1144 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1145 if (!FT->getNumParams()) {
1146 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1147 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1148 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1149 return ExprError();
1150 }
1151 QualType PT = FT->getParamType(0);
1152 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1153 !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1154 !PT->getPointeeType().isConstQualified()) {
1155 Diag(FnPtrArg->getLocStart(), diag::err_typecheck_convert_incompatible)
1156 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1157 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1158 return ExprError();
1159 }
1160 }
1161
1162 TheCall->setType(Context.IntTy);
1163 break;
1164 }
1165
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001166 // check secure string manipulation functions where overflows
1167 // are detectable at compile time
1168 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001169 case Builtin::BI__builtin___memmove_chk:
1170 case Builtin::BI__builtin___memset_chk:
1171 case Builtin::BI__builtin___strlcat_chk:
1172 case Builtin::BI__builtin___strlcpy_chk:
1173 case Builtin::BI__builtin___strncat_chk:
1174 case Builtin::BI__builtin___strncpy_chk:
1175 case Builtin::BI__builtin___stpncpy_chk:
1176 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1177 break;
Steven Wu566c14e2014-09-24 04:37:33 +00001178 case Builtin::BI__builtin___memccpy_chk:
1179 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1180 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +00001181 case Builtin::BI__builtin___snprintf_chk:
1182 case Builtin::BI__builtin___vsnprintf_chk:
1183 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1184 break;
Peter Collingbournef7706832014-12-12 23:41:25 +00001185 case Builtin::BI__builtin_call_with_static_chain:
1186 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1187 return ExprError();
1188 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001189 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001190 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001191 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1192 diag::err_seh___except_block))
1193 return ExprError();
1194 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +00001195 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +00001196 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +00001197 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1198 diag::err_seh___except_filter))
1199 return ExprError();
1200 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +00001201 case Builtin::BI__GetExceptionInfo:
1202 if (checkArgCount(*this, TheCall, 1))
1203 return ExprError();
1204
1205 if (CheckCXXThrowOperand(
1206 TheCall->getLocStart(),
1207 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1208 TheCall))
1209 return ExprError();
1210
1211 TheCall->setType(Context.VoidPtrTy);
1212 break;
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +00001213 // OpenCL v2.0, s6.13.16 - Pipe functions
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001214 case Builtin::BIread_pipe:
1215 case Builtin::BIwrite_pipe:
1216 // Since those two functions are declared with var args, we need a semantic
1217 // check for the argument.
1218 if (SemaBuiltinRWPipe(*this, TheCall))
1219 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001220 TheCall->setType(Context.IntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001221 break;
1222 case Builtin::BIreserve_read_pipe:
1223 case Builtin::BIreserve_write_pipe:
1224 case Builtin::BIwork_group_reserve_read_pipe:
1225 case Builtin::BIwork_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001226 if (SemaBuiltinReserveRWPipe(*this, TheCall))
1227 return ExprError();
Joey Gouly84ae3362017-07-31 15:15:59 +00001228 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001229 case Builtin::BIsub_group_reserve_read_pipe:
1230 case Builtin::BIsub_group_reserve_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001231 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1232 SemaBuiltinReserveRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001233 return ExprError();
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001234 break;
1235 case Builtin::BIcommit_read_pipe:
1236 case Builtin::BIcommit_write_pipe:
1237 case Builtin::BIwork_group_commit_read_pipe:
1238 case Builtin::BIwork_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001239 if (SemaBuiltinCommitRWPipe(*this, TheCall))
1240 return ExprError();
1241 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001242 case Builtin::BIsub_group_commit_read_pipe:
1243 case Builtin::BIsub_group_commit_write_pipe:
Joey Gouly84ae3362017-07-31 15:15:59 +00001244 if (checkOpenCLSubgroupExt(*this, TheCall) ||
1245 SemaBuiltinCommitRWPipe(*this, TheCall))
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001246 return ExprError();
1247 break;
1248 case Builtin::BIget_pipe_num_packets:
1249 case Builtin::BIget_pipe_max_packets:
1250 if (SemaBuiltinPipePackets(*this, TheCall))
1251 return ExprError();
Alexey Baderaf17c792016-09-07 10:32:03 +00001252 TheCall->setType(Context.UnsignedIntTy);
Xiuli Panbb4d8d32016-01-26 04:03:48 +00001253 break;
Yaxun Liuf7449a12016-05-20 19:54:38 +00001254 case Builtin::BIto_global:
1255 case Builtin::BIto_local:
1256 case Builtin::BIto_private:
1257 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1258 return ExprError();
1259 break;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +00001260 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1261 case Builtin::BIenqueue_kernel:
1262 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1263 return ExprError();
1264 break;
1265 case Builtin::BIget_kernel_work_group_size:
1266 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1267 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1268 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001269 break;
Joey Goulyfa76b492017-08-01 13:27:09 +00001270 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1271 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1272 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1273 return ExprError();
1274 break;
Mehdi Amini06d367c2016-10-24 20:39:34 +00001275 case Builtin::BI__builtin_os_log_format:
1276 case Builtin::BI__builtin_os_log_format_buffer_size:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00001277 if (SemaBuiltinOSLogFormat(TheCall))
Mehdi Amini06d367c2016-10-24 20:39:34 +00001278 return ExprError();
Mehdi Amini06d367c2016-10-24 20:39:34 +00001279 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001280 }
Richard Smith760520b2014-06-03 23:27:44 +00001281
Nate Begeman4904e322010-06-08 02:47:44 +00001282 // Since the target specific builtins for each arch overlap, only check those
1283 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +00001284 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001285 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +00001286 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001287 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001288 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00001289 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +00001290 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1291 return ExprError();
1292 break;
Tim Northover25e8a672014-05-24 12:51:25 +00001293 case llvm::Triple::aarch64:
1294 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +00001295 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +00001296 return ExprError();
1297 break;
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001298 case llvm::Triple::hexagon:
1299 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1300 return ExprError();
1301 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001302 case llvm::Triple::mips:
1303 case llvm::Triple::mipsel:
1304 case llvm::Triple::mips64:
1305 case llvm::Triple::mips64el:
1306 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1307 return ExprError();
1308 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001309 case llvm::Triple::systemz:
1310 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1311 return ExprError();
1312 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001313 case llvm::Triple::x86:
1314 case llvm::Triple::x86_64:
1315 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1316 return ExprError();
1317 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001318 case llvm::Triple::ppc:
1319 case llvm::Triple::ppc64:
1320 case llvm::Triple::ppc64le:
1321 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1322 return ExprError();
1323 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001324 default:
1325 break;
1326 }
1327 }
1328
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001329 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001330}
1331
Nate Begeman91e1fea2010-06-14 05:21:25 +00001332// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001333static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001334 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001335 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001336 switch (Type.getEltType()) {
1337 case NeonTypeFlags::Int8:
1338 case NeonTypeFlags::Poly8:
1339 return shift ? 7 : (8 << IsQuad) - 1;
1340 case NeonTypeFlags::Int16:
1341 case NeonTypeFlags::Poly16:
1342 return shift ? 15 : (4 << IsQuad) - 1;
1343 case NeonTypeFlags::Int32:
1344 return shift ? 31 : (2 << IsQuad) - 1;
1345 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001346 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001347 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001348 case NeonTypeFlags::Poly128:
1349 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001350 case NeonTypeFlags::Float16:
1351 assert(!shift && "cannot shift float types!");
1352 return (4 << IsQuad) - 1;
1353 case NeonTypeFlags::Float32:
1354 assert(!shift && "cannot shift float types!");
1355 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001356 case NeonTypeFlags::Float64:
1357 assert(!shift && "cannot shift float types!");
1358 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001359 }
David Blaikie8a40f702012-01-17 06:56:22 +00001360 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001361}
1362
Bob Wilsone4d77232011-11-08 05:04:11 +00001363/// getNeonEltType - Return the QualType corresponding to the elements of
1364/// the vector type specified by the NeonTypeFlags. This is used to check
1365/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001366static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001367 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001368 switch (Flags.getEltType()) {
1369 case NeonTypeFlags::Int8:
1370 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1371 case NeonTypeFlags::Int16:
1372 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1373 case NeonTypeFlags::Int32:
1374 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1375 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001376 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001377 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1378 else
1379 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1380 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001381 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001382 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001383 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001384 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001385 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001386 if (IsInt64Long)
1387 return Context.UnsignedLongTy;
1388 else
1389 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001390 case NeonTypeFlags::Poly128:
1391 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001392 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001393 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001394 case NeonTypeFlags::Float32:
1395 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001396 case NeonTypeFlags::Float64:
1397 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001398 }
David Blaikie8a40f702012-01-17 06:56:22 +00001399 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001400}
1401
Tim Northover12670412014-02-19 10:37:05 +00001402bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001403 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001404 uint64_t mask = 0;
1405 unsigned TV = 0;
1406 int PtrArgNum = -1;
1407 bool HasConstPtr = false;
1408 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001409#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001410#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001411#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001412#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001413 }
1414
1415 // For NEON intrinsics which are overloaded on vector element type, validate
1416 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001417 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001418 if (mask) {
1419 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1420 return true;
1421
1422 TV = Result.getLimitedValue(64);
1423 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1424 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001425 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001426 }
1427
1428 if (PtrArgNum >= 0) {
1429 // Check that pointer arguments have the specified type.
1430 Expr *Arg = TheCall->getArg(PtrArgNum);
1431 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1432 Arg = ICE->getSubExpr();
1433 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1434 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001435
Tim Northovera2ee4332014-03-29 15:09:45 +00001436 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001437 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1438 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001439 bool IsInt64Long =
1440 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1441 QualType EltTy =
1442 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001443 if (HasConstPtr)
1444 EltTy = EltTy.withConst();
1445 QualType LHSTy = Context.getPointerType(EltTy);
1446 AssignConvertType ConvTy;
1447 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1448 if (RHS.isInvalid())
1449 return true;
1450 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1451 RHS.get(), AA_Assigning))
1452 return true;
1453 }
1454
1455 // For NEON intrinsics which take an immediate value as part of the
1456 // instruction, range check them here.
1457 unsigned i = 0, l = 0, u = 0;
1458 switch (BuiltinID) {
1459 default:
1460 return false;
Tim Northover12670412014-02-19 10:37:05 +00001461#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001462#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001463#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001464#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001465 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001466
Richard Sandiford28940af2014-04-16 08:47:51 +00001467 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001468}
1469
Tim Northovera2ee4332014-03-29 15:09:45 +00001470bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1471 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001472 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001473 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001474 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001475 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001476 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001477 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1478 BuiltinID == AArch64::BI__builtin_arm_strex ||
1479 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001480 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001481 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001482 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1483 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1484 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001485
1486 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1487
1488 // Ensure that we have the proper number of arguments.
1489 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1490 return true;
1491
1492 // Inspect the pointer argument of the atomic builtin. This should always be
1493 // a pointer type, whose element is an integral scalar or pointer type.
1494 // Because it is a pointer type, we don't have to worry about any implicit
1495 // casts here.
1496 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1497 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1498 if (PointerArgRes.isInvalid())
1499 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001500 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001501
1502 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1503 if (!pointerType) {
1504 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1505 << PointerArg->getType() << PointerArg->getSourceRange();
1506 return true;
1507 }
1508
1509 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1510 // task is to insert the appropriate casts into the AST. First work out just
1511 // what the appropriate type is.
1512 QualType ValType = pointerType->getPointeeType();
1513 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1514 if (IsLdrex)
1515 AddrType.addConst();
1516
1517 // Issue a warning if the cast is dodgy.
1518 CastKind CastNeeded = CK_NoOp;
1519 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1520 CastNeeded = CK_BitCast;
1521 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1522 << PointerArg->getType()
1523 << Context.getPointerType(AddrType)
1524 << AA_Passing << PointerArg->getSourceRange();
1525 }
1526
1527 // Finally, do the cast and replace the argument with the corrected version.
1528 AddrType = Context.getPointerType(AddrType);
1529 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1530 if (PointerArgRes.isInvalid())
1531 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001532 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001533
1534 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1535
1536 // In general, we allow ints, floats and pointers to be loaded and stored.
1537 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1538 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1539 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1540 << PointerArg->getType() << PointerArg->getSourceRange();
1541 return true;
1542 }
1543
1544 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001545 if (Context.getTypeSize(ValType) > MaxWidth) {
1546 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001547 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1548 << PointerArg->getType() << PointerArg->getSourceRange();
1549 return true;
1550 }
1551
1552 switch (ValType.getObjCLifetime()) {
1553 case Qualifiers::OCL_None:
1554 case Qualifiers::OCL_ExplicitNone:
1555 // okay
1556 break;
1557
1558 case Qualifiers::OCL_Weak:
1559 case Qualifiers::OCL_Strong:
1560 case Qualifiers::OCL_Autoreleasing:
1561 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1562 << ValType << PointerArg->getSourceRange();
1563 return true;
1564 }
1565
Tim Northover6aacd492013-07-16 09:47:53 +00001566 if (IsLdrex) {
1567 TheCall->setType(ValType);
1568 return false;
1569 }
1570
1571 // Initialize the argument to be stored.
1572 ExprResult ValArg = TheCall->getArg(0);
1573 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1574 Context, ValType, /*consume*/ false);
1575 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1576 if (ValArg.isInvalid())
1577 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001578 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001579
1580 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1581 // but the custom checker bypasses all default analysis.
1582 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001583 return false;
1584}
1585
Nate Begeman4904e322010-06-08 02:47:44 +00001586bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001587 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001588 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1589 BuiltinID == ARM::BI__builtin_arm_strex ||
1590 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001591 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001592 }
1593
Yi Kong26d104a2014-08-13 19:18:14 +00001594 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1595 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1596 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1597 }
1598
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001599 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1600 BuiltinID == ARM::BI__builtin_arm_wsr64)
1601 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1602
1603 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1604 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1605 BuiltinID == ARM::BI__builtin_arm_wsr ||
1606 BuiltinID == ARM::BI__builtin_arm_wsrp)
1607 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1608
Tim Northover12670412014-02-19 10:37:05 +00001609 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1610 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001611
Yi Kong4efadfb2014-07-03 16:01:25 +00001612 // For intrinsics which take an immediate value as part of the instruction,
1613 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001614 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001615 switch (BuiltinID) {
1616 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001617 case ARM::BI__builtin_arm_ssat:
1618 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1619 case ARM::BI__builtin_arm_usat:
1620 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1621 case ARM::BI__builtin_arm_ssat16:
1622 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1623 case ARM::BI__builtin_arm_usat16:
1624 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001625 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001626 case ARM::BI__builtin_arm_vcvtr_d:
1627 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001628 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001629 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001630 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001631 case ARM::BI__builtin_arm_dbg:
1632 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001633 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001634}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001635
Tim Northover573cbee2014-05-24 12:52:07 +00001636bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001637 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001638 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001639 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1640 BuiltinID == AArch64::BI__builtin_arm_strex ||
1641 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001642 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1643 }
1644
Yi Konga5548432014-08-13 19:18:20 +00001645 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1646 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1647 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1648 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1649 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1650 }
1651
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001652 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1653 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001654 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001655
1656 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1657 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1658 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1659 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1660 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1661
Tim Northovera2ee4332014-03-29 15:09:45 +00001662 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1663 return true;
1664
Yi Kong19a29ac2014-07-17 10:52:06 +00001665 // For intrinsics which take an immediate value as part of the instruction,
1666 // range check them here.
1667 unsigned i = 0, l = 0, u = 0;
1668 switch (BuiltinID) {
1669 default: return false;
1670 case AArch64::BI__builtin_arm_dmb:
1671 case AArch64::BI__builtin_arm_dsb:
1672 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1673 }
1674
Yi Kong19a29ac2014-07-17 10:52:06 +00001675 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001676}
1677
Krzysztof Parzyszek45850682018-05-11 16:41:51 +00001678bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
1679 CallExpr *TheCall) {
1680 struct ArgInfo {
1681 ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
1682 : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
1683 unsigned OpNum = 0;
1684 bool IsSigned = false;
1685 unsigned BitWidth = 0;
1686 unsigned Align = 0;
1687 };
1688
1689 static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
1690 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} },
1691 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} },
1692 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} },
1693 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 0 }} },
1694 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} },
1695 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} },
1696 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} },
1697 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} },
1698 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} },
1699 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} },
1700 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} },
1701
1702 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} },
1703 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} },
1704 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} },
1705 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} },
1706 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} },
1707 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} },
1708 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} },
1709 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} },
1710 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} },
1711 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} },
1712 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} },
1713
1714 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} },
1715 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} },
1716 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} },
1717 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} },
1718 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} },
1719 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} },
1720 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} },
1721 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} },
1722 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} },
1723 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} },
1724 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} },
1725 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} },
1726 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} },
1727 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} },
1728 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} },
1729 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} },
1730 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} },
1731 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} },
1732 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} },
1733 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} },
1734 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} },
1735 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} },
1736 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} },
1737 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} },
1738 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} },
1739 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} },
1740 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} },
1741 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} },
1742 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} },
1743 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} },
1744 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} },
1745 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} },
1746 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} },
1747 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} },
1748 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} },
1749 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} },
1750 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} },
1751 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} },
1752 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} },
1753 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} },
1754 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} },
1755 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} },
1756 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} },
1757 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} },
1758 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} },
1759 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} },
1760 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} },
1761 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} },
1762 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} },
1763 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} },
1764 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} },
1765 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
1766 {{ 1, false, 6, 0 }} },
1767 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} },
1768 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} },
1769 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} },
1770 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} },
1771 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} },
1772 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} },
1773 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
1774 {{ 1, false, 5, 0 }} },
1775 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} },
1776 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} },
1777 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} },
1778 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} },
1779 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} },
1780 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 },
1781 { 2, false, 5, 0 }} },
1782 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 },
1783 { 2, false, 6, 0 }} },
1784 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 },
1785 { 3, false, 5, 0 }} },
1786 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 },
1787 { 3, false, 6, 0 }} },
1788 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} },
1789 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} },
1790 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} },
1791 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} },
1792 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} },
1793 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} },
1794 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} },
1795 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} },
1796 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} },
1797 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} },
1798 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} },
1799 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} },
1800 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} },
1801 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} },
1802 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} },
1803 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
1804 {{ 2, false, 4, 0 },
1805 { 3, false, 5, 0 }} },
1806 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
1807 {{ 2, false, 4, 0 },
1808 { 3, false, 5, 0 }} },
1809 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
1810 {{ 2, false, 4, 0 },
1811 { 3, false, 5, 0 }} },
1812 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
1813 {{ 2, false, 4, 0 },
1814 { 3, false, 5, 0 }} },
1815 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} },
1816 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} },
1817 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} },
1818 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} },
1819 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} },
1820 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} },
1821 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} },
1822 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} },
1823 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} },
1824 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} },
1825 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 },
1826 { 2, false, 5, 0 }} },
1827 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 },
1828 { 2, false, 6, 0 }} },
1829 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} },
1830 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} },
1831 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} },
1832 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} },
1833 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} },
1834 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} },
1835 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} },
1836 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} },
1837 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
1838 {{ 1, false, 4, 0 }} },
1839 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} },
1840 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
1841 {{ 1, false, 4, 0 }} },
1842 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} },
1843 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} },
1844 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} },
1845 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} },
1846 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} },
1847 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} },
1848 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} },
1849 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} },
1850 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} },
1851 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} },
1852 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} },
1853 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} },
1854 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} },
1855 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} },
1856 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} },
1857 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} },
1858 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} },
1859 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} },
1860 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} },
1861 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
1862 {{ 3, false, 1, 0 }} },
1863 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} },
1864 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} },
1865 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} },
1866 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
1867 {{ 3, false, 1, 0 }} },
1868 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} },
1869 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} },
1870 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} },
1871 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
1872 {{ 3, false, 1, 0 }} },
1873 };
1874
1875 auto F = Infos.find(BuiltinID);
1876 if (F == Infos.end())
1877 return false;
1878
1879 bool Error = false;
1880
1881 for (const ArgInfo &A : F->second) {
1882 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
1883 int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
1884 if (!A.Align) {
1885 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
1886 } else {
1887 unsigned M = 1 << A.Align;
1888 Min *= M;
1889 Max *= M;
1890 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
1891 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
1892 }
1893 }
1894 return Error;
1895}
1896
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001897// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1898// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1899// ordering for DSP is unspecified. MSA is ordered by the data format used
1900// by the underlying instruction i.e., df/m, df/n and then by size.
1901//
1902// FIXME: The size tests here should instead be tablegen'd along with the
1903// definitions from include/clang/Basic/BuiltinsMips.def.
1904// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1905// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001906bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001907 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001908 switch (BuiltinID) {
1909 default: return false;
1910 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1911 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001912 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1913 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1914 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1915 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1916 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001917 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1918 // df/m field.
1919 // These intrinsics take an unsigned 3 bit immediate.
1920 case Mips::BI__builtin_msa_bclri_b:
1921 case Mips::BI__builtin_msa_bnegi_b:
1922 case Mips::BI__builtin_msa_bseti_b:
1923 case Mips::BI__builtin_msa_sat_s_b:
1924 case Mips::BI__builtin_msa_sat_u_b:
1925 case Mips::BI__builtin_msa_slli_b:
1926 case Mips::BI__builtin_msa_srai_b:
1927 case Mips::BI__builtin_msa_srari_b:
1928 case Mips::BI__builtin_msa_srli_b:
1929 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1930 case Mips::BI__builtin_msa_binsli_b:
1931 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1932 // These intrinsics take an unsigned 4 bit immediate.
1933 case Mips::BI__builtin_msa_bclri_h:
1934 case Mips::BI__builtin_msa_bnegi_h:
1935 case Mips::BI__builtin_msa_bseti_h:
1936 case Mips::BI__builtin_msa_sat_s_h:
1937 case Mips::BI__builtin_msa_sat_u_h:
1938 case Mips::BI__builtin_msa_slli_h:
1939 case Mips::BI__builtin_msa_srai_h:
1940 case Mips::BI__builtin_msa_srari_h:
1941 case Mips::BI__builtin_msa_srli_h:
1942 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1943 case Mips::BI__builtin_msa_binsli_h:
1944 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001945 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001946 // The first block of intrinsics actually have an unsigned 5 bit field,
1947 // not a df/n field.
1948 case Mips::BI__builtin_msa_clei_u_b:
1949 case Mips::BI__builtin_msa_clei_u_h:
1950 case Mips::BI__builtin_msa_clei_u_w:
1951 case Mips::BI__builtin_msa_clei_u_d:
1952 case Mips::BI__builtin_msa_clti_u_b:
1953 case Mips::BI__builtin_msa_clti_u_h:
1954 case Mips::BI__builtin_msa_clti_u_w:
1955 case Mips::BI__builtin_msa_clti_u_d:
1956 case Mips::BI__builtin_msa_maxi_u_b:
1957 case Mips::BI__builtin_msa_maxi_u_h:
1958 case Mips::BI__builtin_msa_maxi_u_w:
1959 case Mips::BI__builtin_msa_maxi_u_d:
1960 case Mips::BI__builtin_msa_mini_u_b:
1961 case Mips::BI__builtin_msa_mini_u_h:
1962 case Mips::BI__builtin_msa_mini_u_w:
1963 case Mips::BI__builtin_msa_mini_u_d:
1964 case Mips::BI__builtin_msa_addvi_b:
1965 case Mips::BI__builtin_msa_addvi_h:
1966 case Mips::BI__builtin_msa_addvi_w:
1967 case Mips::BI__builtin_msa_addvi_d:
1968 case Mips::BI__builtin_msa_bclri_w:
1969 case Mips::BI__builtin_msa_bnegi_w:
1970 case Mips::BI__builtin_msa_bseti_w:
1971 case Mips::BI__builtin_msa_sat_s_w:
1972 case Mips::BI__builtin_msa_sat_u_w:
1973 case Mips::BI__builtin_msa_slli_w:
1974 case Mips::BI__builtin_msa_srai_w:
1975 case Mips::BI__builtin_msa_srari_w:
1976 case Mips::BI__builtin_msa_srli_w:
1977 case Mips::BI__builtin_msa_srlri_w:
1978 case Mips::BI__builtin_msa_subvi_b:
1979 case Mips::BI__builtin_msa_subvi_h:
1980 case Mips::BI__builtin_msa_subvi_w:
1981 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1982 case Mips::BI__builtin_msa_binsli_w:
1983 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1984 // These intrinsics take an unsigned 6 bit immediate.
1985 case Mips::BI__builtin_msa_bclri_d:
1986 case Mips::BI__builtin_msa_bnegi_d:
1987 case Mips::BI__builtin_msa_bseti_d:
1988 case Mips::BI__builtin_msa_sat_s_d:
1989 case Mips::BI__builtin_msa_sat_u_d:
1990 case Mips::BI__builtin_msa_slli_d:
1991 case Mips::BI__builtin_msa_srai_d:
1992 case Mips::BI__builtin_msa_srari_d:
1993 case Mips::BI__builtin_msa_srli_d:
1994 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1995 case Mips::BI__builtin_msa_binsli_d:
1996 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1997 // These intrinsics take a signed 5 bit immediate.
1998 case Mips::BI__builtin_msa_ceqi_b:
1999 case Mips::BI__builtin_msa_ceqi_h:
2000 case Mips::BI__builtin_msa_ceqi_w:
2001 case Mips::BI__builtin_msa_ceqi_d:
2002 case Mips::BI__builtin_msa_clti_s_b:
2003 case Mips::BI__builtin_msa_clti_s_h:
2004 case Mips::BI__builtin_msa_clti_s_w:
2005 case Mips::BI__builtin_msa_clti_s_d:
2006 case Mips::BI__builtin_msa_clei_s_b:
2007 case Mips::BI__builtin_msa_clei_s_h:
2008 case Mips::BI__builtin_msa_clei_s_w:
2009 case Mips::BI__builtin_msa_clei_s_d:
2010 case Mips::BI__builtin_msa_maxi_s_b:
2011 case Mips::BI__builtin_msa_maxi_s_h:
2012 case Mips::BI__builtin_msa_maxi_s_w:
2013 case Mips::BI__builtin_msa_maxi_s_d:
2014 case Mips::BI__builtin_msa_mini_s_b:
2015 case Mips::BI__builtin_msa_mini_s_h:
2016 case Mips::BI__builtin_msa_mini_s_w:
2017 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2018 // These intrinsics take an unsigned 8 bit immediate.
2019 case Mips::BI__builtin_msa_andi_b:
2020 case Mips::BI__builtin_msa_nori_b:
2021 case Mips::BI__builtin_msa_ori_b:
2022 case Mips::BI__builtin_msa_shf_b:
2023 case Mips::BI__builtin_msa_shf_h:
2024 case Mips::BI__builtin_msa_shf_w:
2025 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2026 case Mips::BI__builtin_msa_bseli_b:
2027 case Mips::BI__builtin_msa_bmnzi_b:
2028 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2029 // df/n format
2030 // These intrinsics take an unsigned 4 bit immediate.
2031 case Mips::BI__builtin_msa_copy_s_b:
2032 case Mips::BI__builtin_msa_copy_u_b:
2033 case Mips::BI__builtin_msa_insve_b:
2034 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002035 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2036 // These intrinsics take an unsigned 3 bit immediate.
2037 case Mips::BI__builtin_msa_copy_s_h:
2038 case Mips::BI__builtin_msa_copy_u_h:
2039 case Mips::BI__builtin_msa_insve_h:
2040 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002041 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2042 // These intrinsics take an unsigned 2 bit immediate.
2043 case Mips::BI__builtin_msa_copy_s_w:
2044 case Mips::BI__builtin_msa_copy_u_w:
2045 case Mips::BI__builtin_msa_insve_w:
2046 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002047 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2048 // These intrinsics take an unsigned 1 bit immediate.
2049 case Mips::BI__builtin_msa_copy_s_d:
2050 case Mips::BI__builtin_msa_copy_u_d:
2051 case Mips::BI__builtin_msa_insve_d:
2052 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002053 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2054 // Memory offsets and immediate loads.
2055 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00002056 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002057 case Mips::BI__builtin_msa_ldi_h:
2058 case Mips::BI__builtin_msa_ldi_w:
2059 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2060 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2061 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2062 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2063 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2064 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2065 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2066 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2067 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00002068 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002069
Simon Dardis1f90f2d2016-10-19 17:50:52 +00002070 if (!m)
2071 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2072
2073 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2074 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00002075}
2076
Kit Bartone50adcb2015-03-30 19:40:59 +00002077bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2078 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00002079 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2080 BuiltinID == PPC::BI__builtin_divdeu ||
2081 BuiltinID == PPC::BI__builtin_bpermd;
2082 bool IsTarget64Bit = Context.getTargetInfo()
2083 .getTypeWidth(Context
2084 .getTargetInfo()
2085 .getIntPtrType()) == 64;
2086 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2087 BuiltinID == PPC::BI__builtin_divweu ||
2088 BuiltinID == PPC::BI__builtin_divde ||
2089 BuiltinID == PPC::BI__builtin_divdeu;
2090
2091 if (Is64BitBltin && !IsTarget64Bit)
2092 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
2093 << TheCall->getSourceRange();
2094
2095 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2096 (BuiltinID == PPC::BI__builtin_bpermd &&
2097 !Context.getTargetInfo().hasFeature("bpermd")))
2098 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
2099 << TheCall->getSourceRange();
2100
Kit Bartone50adcb2015-03-30 19:40:59 +00002101 switch (BuiltinID) {
2102 default: return false;
2103 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2104 case PPC::BI__builtin_altivec_crypto_vshasigmad:
2105 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2106 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2107 case PPC::BI__builtin_tbegin:
2108 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2109 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2110 case PPC::BI__builtin_tabortwc:
2111 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2112 case PPC::BI__builtin_tabortwci:
2113 case PPC::BI__builtin_tabortdci:
2114 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
2115 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00002116 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00002117 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00002118 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00002119 }
2120 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2121}
2122
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002123bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
2124 CallExpr *TheCall) {
2125 if (BuiltinID == SystemZ::BI__builtin_tabort) {
2126 Expr *Arg = TheCall->getArg(0);
2127 llvm::APSInt AbortCode(32);
2128 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
2129 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
2130 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
2131 << Arg->getSourceRange();
2132 }
2133
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002134 // For intrinsics which take an immediate value as part of the instruction,
2135 // range check them here.
2136 unsigned i = 0, l = 0, u = 0;
2137 switch (BuiltinID) {
2138 default: return false;
2139 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
2140 case SystemZ::BI__builtin_s390_verimb:
2141 case SystemZ::BI__builtin_s390_verimh:
2142 case SystemZ::BI__builtin_s390_verimf:
2143 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
2144 case SystemZ::BI__builtin_s390_vfaeb:
2145 case SystemZ::BI__builtin_s390_vfaeh:
2146 case SystemZ::BI__builtin_s390_vfaef:
2147 case SystemZ::BI__builtin_s390_vfaebs:
2148 case SystemZ::BI__builtin_s390_vfaehs:
2149 case SystemZ::BI__builtin_s390_vfaefs:
2150 case SystemZ::BI__builtin_s390_vfaezb:
2151 case SystemZ::BI__builtin_s390_vfaezh:
2152 case SystemZ::BI__builtin_s390_vfaezf:
2153 case SystemZ::BI__builtin_s390_vfaezbs:
2154 case SystemZ::BI__builtin_s390_vfaezhs:
2155 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002156 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002157 case SystemZ::BI__builtin_s390_vfidb:
2158 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
2159 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002160 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002161 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
2162 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
2163 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
2164 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
2165 case SystemZ::BI__builtin_s390_vstrcb:
2166 case SystemZ::BI__builtin_s390_vstrch:
2167 case SystemZ::BI__builtin_s390_vstrcf:
2168 case SystemZ::BI__builtin_s390_vstrczb:
2169 case SystemZ::BI__builtin_s390_vstrczh:
2170 case SystemZ::BI__builtin_s390_vstrczf:
2171 case SystemZ::BI__builtin_s390_vstrcbs:
2172 case SystemZ::BI__builtin_s390_vstrchs:
2173 case SystemZ::BI__builtin_s390_vstrcfs:
2174 case SystemZ::BI__builtin_s390_vstrczbs:
2175 case SystemZ::BI__builtin_s390_vstrczhs:
2176 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00002177 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
2178 case SystemZ::BI__builtin_s390_vfminsb:
2179 case SystemZ::BI__builtin_s390_vfmaxsb:
2180 case SystemZ::BI__builtin_s390_vfmindb:
2181 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00002182 }
2183 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00002184}
2185
Craig Topper5ba2c502015-11-07 08:08:31 +00002186/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2187/// This checks that the target supports __builtin_cpu_supports and
2188/// that the string argument is constant and valid.
2189static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
2190 Expr *Arg = TheCall->getArg(0);
2191
2192 // Check if the argument is a string literal.
2193 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2194 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2195 << Arg->getSourceRange();
2196
2197 // Check the contents of the string.
2198 StringRef Feature =
2199 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2200 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
2201 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2202 << Arg->getSourceRange();
2203 return false;
2204}
2205
Craig Topper699ae0c2017-08-10 20:28:30 +00002206/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
2207/// This checks that the target supports __builtin_cpu_is and
2208/// that the string argument is constant and valid.
2209static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
2210 Expr *Arg = TheCall->getArg(0);
2211
2212 // Check if the argument is a string literal.
2213 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2214 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2215 << Arg->getSourceRange();
2216
2217 // Check the contents of the string.
2218 StringRef Feature =
2219 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2220 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
2221 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
2222 << Arg->getSourceRange();
2223 return false;
2224}
2225
Craig Toppera7e253e2016-09-23 04:48:31 +00002226// Check if the rounding mode is legal.
2227bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2228 // Indicates if this instruction has rounding control or just SAE.
2229 bool HasRC = false;
2230
2231 unsigned ArgNum = 0;
2232 switch (BuiltinID) {
2233 default:
2234 return false;
2235 case X86::BI__builtin_ia32_vcvttsd2si32:
2236 case X86::BI__builtin_ia32_vcvttsd2si64:
2237 case X86::BI__builtin_ia32_vcvttsd2usi32:
2238 case X86::BI__builtin_ia32_vcvttsd2usi64:
2239 case X86::BI__builtin_ia32_vcvttss2si32:
2240 case X86::BI__builtin_ia32_vcvttss2si64:
2241 case X86::BI__builtin_ia32_vcvttss2usi32:
2242 case X86::BI__builtin_ia32_vcvttss2usi64:
2243 ArgNum = 1;
2244 break;
2245 case X86::BI__builtin_ia32_cvtps2pd512_mask:
2246 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2247 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2248 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2249 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2250 case X86::BI__builtin_ia32_cvttps2dq512_mask:
2251 case X86::BI__builtin_ia32_cvttps2qq512_mask:
2252 case X86::BI__builtin_ia32_cvttps2udq512_mask:
2253 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2254 case X86::BI__builtin_ia32_exp2pd_mask:
2255 case X86::BI__builtin_ia32_exp2ps_mask:
2256 case X86::BI__builtin_ia32_getexppd512_mask:
2257 case X86::BI__builtin_ia32_getexpps512_mask:
2258 case X86::BI__builtin_ia32_rcp28pd_mask:
2259 case X86::BI__builtin_ia32_rcp28ps_mask:
2260 case X86::BI__builtin_ia32_rsqrt28pd_mask:
2261 case X86::BI__builtin_ia32_rsqrt28ps_mask:
2262 case X86::BI__builtin_ia32_vcomisd:
2263 case X86::BI__builtin_ia32_vcomiss:
2264 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2265 ArgNum = 3;
2266 break;
2267 case X86::BI__builtin_ia32_cmppd512_mask:
2268 case X86::BI__builtin_ia32_cmpps512_mask:
2269 case X86::BI__builtin_ia32_cmpsd_mask:
2270 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002271 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002272 case X86::BI__builtin_ia32_getexpsd128_round_mask:
2273 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002274 case X86::BI__builtin_ia32_maxpd512_mask:
2275 case X86::BI__builtin_ia32_maxps512_mask:
2276 case X86::BI__builtin_ia32_maxsd_round_mask:
2277 case X86::BI__builtin_ia32_maxss_round_mask:
2278 case X86::BI__builtin_ia32_minpd512_mask:
2279 case X86::BI__builtin_ia32_minps512_mask:
2280 case X86::BI__builtin_ia32_minsd_round_mask:
2281 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002282 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2283 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2284 case X86::BI__builtin_ia32_reducepd512_mask:
2285 case X86::BI__builtin_ia32_reduceps512_mask:
2286 case X86::BI__builtin_ia32_rndscalepd_mask:
2287 case X86::BI__builtin_ia32_rndscaleps_mask:
2288 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2289 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2290 ArgNum = 4;
2291 break;
2292 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002293 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002294 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002295 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002296 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002297 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002298 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002299 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002300 case X86::BI__builtin_ia32_rangepd512_mask:
2301 case X86::BI__builtin_ia32_rangeps512_mask:
2302 case X86::BI__builtin_ia32_rangesd128_round_mask:
2303 case X86::BI__builtin_ia32_rangess128_round_mask:
2304 case X86::BI__builtin_ia32_reducesd_mask:
2305 case X86::BI__builtin_ia32_reducess_mask:
2306 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2307 case X86::BI__builtin_ia32_rndscaless_round_mask:
2308 ArgNum = 5;
2309 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002310 case X86::BI__builtin_ia32_vcvtsd2si64:
2311 case X86::BI__builtin_ia32_vcvtsd2si32:
2312 case X86::BI__builtin_ia32_vcvtsd2usi32:
2313 case X86::BI__builtin_ia32_vcvtsd2usi64:
2314 case X86::BI__builtin_ia32_vcvtss2si32:
2315 case X86::BI__builtin_ia32_vcvtss2si64:
2316 case X86::BI__builtin_ia32_vcvtss2usi32:
2317 case X86::BI__builtin_ia32_vcvtss2usi64:
2318 ArgNum = 1;
2319 HasRC = true;
2320 break;
Craig Topper8e066312016-11-07 07:01:09 +00002321 case X86::BI__builtin_ia32_cvtsi2sd64:
2322 case X86::BI__builtin_ia32_cvtsi2ss32:
2323 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002324 case X86::BI__builtin_ia32_cvtusi2sd64:
2325 case X86::BI__builtin_ia32_cvtusi2ss32:
2326 case X86::BI__builtin_ia32_cvtusi2ss64:
2327 ArgNum = 2;
2328 HasRC = true;
2329 break;
2330 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2331 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2332 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2333 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2334 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2335 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2336 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2337 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2338 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2339 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2340 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002341 case X86::BI__builtin_ia32_sqrtpd512_mask:
2342 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002343 ArgNum = 3;
2344 HasRC = true;
2345 break;
2346 case X86::BI__builtin_ia32_addpd512_mask:
2347 case X86::BI__builtin_ia32_addps512_mask:
2348 case X86::BI__builtin_ia32_divpd512_mask:
2349 case X86::BI__builtin_ia32_divps512_mask:
2350 case X86::BI__builtin_ia32_mulpd512_mask:
2351 case X86::BI__builtin_ia32_mulps512_mask:
2352 case X86::BI__builtin_ia32_subpd512_mask:
2353 case X86::BI__builtin_ia32_subps512_mask:
2354 case X86::BI__builtin_ia32_addss_round_mask:
2355 case X86::BI__builtin_ia32_addsd_round_mask:
2356 case X86::BI__builtin_ia32_divss_round_mask:
2357 case X86::BI__builtin_ia32_divsd_round_mask:
2358 case X86::BI__builtin_ia32_mulss_round_mask:
2359 case X86::BI__builtin_ia32_mulsd_round_mask:
2360 case X86::BI__builtin_ia32_subss_round_mask:
2361 case X86::BI__builtin_ia32_subsd_round_mask:
2362 case X86::BI__builtin_ia32_scalefpd512_mask:
2363 case X86::BI__builtin_ia32_scalefps512_mask:
2364 case X86::BI__builtin_ia32_scalefsd_round_mask:
2365 case X86::BI__builtin_ia32_scalefss_round_mask:
2366 case X86::BI__builtin_ia32_getmantpd512_mask:
2367 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002368 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2369 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2370 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002371 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2372 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2373 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2374 case X86::BI__builtin_ia32_vfmaddps512_mask:
2375 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2376 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2377 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2378 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2379 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2380 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2381 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2382 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2383 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2384 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2385 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2386 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2387 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2388 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2389 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2390 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2391 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2392 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2393 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2394 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2395 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2396 case X86::BI__builtin_ia32_vfmaddss3_mask:
2397 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2398 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2399 ArgNum = 4;
2400 HasRC = true;
2401 break;
2402 case X86::BI__builtin_ia32_getmantsd_round_mask:
2403 case X86::BI__builtin_ia32_getmantss_round_mask:
2404 ArgNum = 5;
2405 HasRC = true;
2406 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002407 }
2408
2409 llvm::APSInt Result;
2410
2411 // We can't check the value of a dependent argument.
2412 Expr *Arg = TheCall->getArg(ArgNum);
2413 if (Arg->isTypeDependent() || Arg->isValueDependent())
2414 return false;
2415
2416 // Check constant-ness first.
2417 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2418 return true;
2419
2420 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2421 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2422 // combined with ROUND_NO_EXC.
2423 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2424 Result == 8/*ROUND_NO_EXC*/ ||
2425 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2426 return false;
2427
2428 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2429 << Arg->getSourceRange();
2430}
2431
Craig Topperdf5beb22017-03-13 17:16:50 +00002432// Check if the gather/scatter scale is legal.
2433bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2434 CallExpr *TheCall) {
2435 unsigned ArgNum = 0;
2436 switch (BuiltinID) {
2437 default:
2438 return false;
2439 case X86::BI__builtin_ia32_gatherpfdpd:
2440 case X86::BI__builtin_ia32_gatherpfdps:
2441 case X86::BI__builtin_ia32_gatherpfqpd:
2442 case X86::BI__builtin_ia32_gatherpfqps:
2443 case X86::BI__builtin_ia32_scatterpfdpd:
2444 case X86::BI__builtin_ia32_scatterpfdps:
2445 case X86::BI__builtin_ia32_scatterpfqpd:
2446 case X86::BI__builtin_ia32_scatterpfqps:
2447 ArgNum = 3;
2448 break;
2449 case X86::BI__builtin_ia32_gatherd_pd:
2450 case X86::BI__builtin_ia32_gatherd_pd256:
2451 case X86::BI__builtin_ia32_gatherq_pd:
2452 case X86::BI__builtin_ia32_gatherq_pd256:
2453 case X86::BI__builtin_ia32_gatherd_ps:
2454 case X86::BI__builtin_ia32_gatherd_ps256:
2455 case X86::BI__builtin_ia32_gatherq_ps:
2456 case X86::BI__builtin_ia32_gatherq_ps256:
2457 case X86::BI__builtin_ia32_gatherd_q:
2458 case X86::BI__builtin_ia32_gatherd_q256:
2459 case X86::BI__builtin_ia32_gatherq_q:
2460 case X86::BI__builtin_ia32_gatherq_q256:
2461 case X86::BI__builtin_ia32_gatherd_d:
2462 case X86::BI__builtin_ia32_gatherd_d256:
2463 case X86::BI__builtin_ia32_gatherq_d:
2464 case X86::BI__builtin_ia32_gatherq_d256:
2465 case X86::BI__builtin_ia32_gather3div2df:
2466 case X86::BI__builtin_ia32_gather3div2di:
2467 case X86::BI__builtin_ia32_gather3div4df:
2468 case X86::BI__builtin_ia32_gather3div4di:
2469 case X86::BI__builtin_ia32_gather3div4sf:
2470 case X86::BI__builtin_ia32_gather3div4si:
2471 case X86::BI__builtin_ia32_gather3div8sf:
2472 case X86::BI__builtin_ia32_gather3div8si:
2473 case X86::BI__builtin_ia32_gather3siv2df:
2474 case X86::BI__builtin_ia32_gather3siv2di:
2475 case X86::BI__builtin_ia32_gather3siv4df:
2476 case X86::BI__builtin_ia32_gather3siv4di:
2477 case X86::BI__builtin_ia32_gather3siv4sf:
2478 case X86::BI__builtin_ia32_gather3siv4si:
2479 case X86::BI__builtin_ia32_gather3siv8sf:
2480 case X86::BI__builtin_ia32_gather3siv8si:
2481 case X86::BI__builtin_ia32_gathersiv8df:
2482 case X86::BI__builtin_ia32_gathersiv16sf:
2483 case X86::BI__builtin_ia32_gatherdiv8df:
2484 case X86::BI__builtin_ia32_gatherdiv16sf:
2485 case X86::BI__builtin_ia32_gathersiv8di:
2486 case X86::BI__builtin_ia32_gathersiv16si:
2487 case X86::BI__builtin_ia32_gatherdiv8di:
2488 case X86::BI__builtin_ia32_gatherdiv16si:
2489 case X86::BI__builtin_ia32_scatterdiv2df:
2490 case X86::BI__builtin_ia32_scatterdiv2di:
2491 case X86::BI__builtin_ia32_scatterdiv4df:
2492 case X86::BI__builtin_ia32_scatterdiv4di:
2493 case X86::BI__builtin_ia32_scatterdiv4sf:
2494 case X86::BI__builtin_ia32_scatterdiv4si:
2495 case X86::BI__builtin_ia32_scatterdiv8sf:
2496 case X86::BI__builtin_ia32_scatterdiv8si:
2497 case X86::BI__builtin_ia32_scattersiv2df:
2498 case X86::BI__builtin_ia32_scattersiv2di:
2499 case X86::BI__builtin_ia32_scattersiv4df:
2500 case X86::BI__builtin_ia32_scattersiv4di:
2501 case X86::BI__builtin_ia32_scattersiv4sf:
2502 case X86::BI__builtin_ia32_scattersiv4si:
2503 case X86::BI__builtin_ia32_scattersiv8sf:
2504 case X86::BI__builtin_ia32_scattersiv8si:
2505 case X86::BI__builtin_ia32_scattersiv8df:
2506 case X86::BI__builtin_ia32_scattersiv16sf:
2507 case X86::BI__builtin_ia32_scatterdiv8df:
2508 case X86::BI__builtin_ia32_scatterdiv16sf:
2509 case X86::BI__builtin_ia32_scattersiv8di:
2510 case X86::BI__builtin_ia32_scattersiv16si:
2511 case X86::BI__builtin_ia32_scatterdiv8di:
2512 case X86::BI__builtin_ia32_scatterdiv16si:
2513 ArgNum = 4;
2514 break;
2515 }
2516
2517 llvm::APSInt Result;
2518
2519 // We can't check the value of a dependent argument.
2520 Expr *Arg = TheCall->getArg(ArgNum);
2521 if (Arg->isTypeDependent() || Arg->isValueDependent())
2522 return false;
2523
2524 // Check constant-ness first.
2525 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2526 return true;
2527
2528 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2529 return false;
2530
2531 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2532 << Arg->getSourceRange();
2533}
2534
Craig Topper51738f82018-04-26 20:14:46 +00002535static bool isX86_32Builtin(unsigned BuiltinID) {
2536 // These builtins only work on x86-32 targets.
2537 switch (BuiltinID) {
2538 case X86::BI__builtin_ia32_readeflags_u32:
2539 case X86::BI__builtin_ia32_writeeflags_u32:
2540 return true;
2541 }
2542
2543 return false;
2544}
2545
Craig Topperf0ddc892016-09-23 04:48:27 +00002546bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2547 if (BuiltinID == X86::BI__builtin_cpu_supports)
2548 return SemaBuiltinCpuSupports(*this, TheCall);
2549
Craig Topper699ae0c2017-08-10 20:28:30 +00002550 if (BuiltinID == X86::BI__builtin_cpu_is)
2551 return SemaBuiltinCpuIs(*this, TheCall);
2552
Craig Topper51738f82018-04-26 20:14:46 +00002553 // Check for 32-bit only builtins on a 64-bit target.
2554 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2555 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2556 return Diag(TheCall->getCallee()->getLocStart(),
2557 diag::err_32_bit_builtin_64_bit_tgt);
2558
Craig Toppera7e253e2016-09-23 04:48:31 +00002559 // If the intrinsic has rounding or SAE make sure its valid.
2560 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2561 return true;
2562
Craig Topperdf5beb22017-03-13 17:16:50 +00002563 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2564 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2565 return true;
2566
Craig Topperf0ddc892016-09-23 04:48:27 +00002567 // For intrinsics which take an immediate value as part of the instruction,
2568 // range check them here.
2569 int i = 0, l = 0, u = 0;
2570 switch (BuiltinID) {
2571 default:
2572 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002573 case X86::BI_mm_prefetch:
Craig Topper170de4b2017-12-21 23:50:22 +00002574 i = 1; l = 0; u = 7;
Craig Topper39c87102016-05-18 03:18:12 +00002575 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002576 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002577 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2578 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2579 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2580 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002581 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002582 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002583 case X86::BI__builtin_ia32_vpermil2pd:
2584 case X86::BI__builtin_ia32_vpermil2pd256:
2585 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002586 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002587 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002588 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002589 case X86::BI__builtin_ia32_cmpb128_mask:
2590 case X86::BI__builtin_ia32_cmpw128_mask:
2591 case X86::BI__builtin_ia32_cmpd128_mask:
2592 case X86::BI__builtin_ia32_cmpq128_mask:
2593 case X86::BI__builtin_ia32_cmpb256_mask:
2594 case X86::BI__builtin_ia32_cmpw256_mask:
2595 case X86::BI__builtin_ia32_cmpd256_mask:
2596 case X86::BI__builtin_ia32_cmpq256_mask:
2597 case X86::BI__builtin_ia32_cmpb512_mask:
2598 case X86::BI__builtin_ia32_cmpw512_mask:
2599 case X86::BI__builtin_ia32_cmpd512_mask:
2600 case X86::BI__builtin_ia32_cmpq512_mask:
2601 case X86::BI__builtin_ia32_ucmpb128_mask:
2602 case X86::BI__builtin_ia32_ucmpw128_mask:
2603 case X86::BI__builtin_ia32_ucmpd128_mask:
2604 case X86::BI__builtin_ia32_ucmpq128_mask:
2605 case X86::BI__builtin_ia32_ucmpb256_mask:
2606 case X86::BI__builtin_ia32_ucmpw256_mask:
2607 case X86::BI__builtin_ia32_ucmpd256_mask:
2608 case X86::BI__builtin_ia32_ucmpq256_mask:
2609 case X86::BI__builtin_ia32_ucmpb512_mask:
2610 case X86::BI__builtin_ia32_ucmpw512_mask:
2611 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002612 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002613 case X86::BI__builtin_ia32_vpcomub:
2614 case X86::BI__builtin_ia32_vpcomuw:
2615 case X86::BI__builtin_ia32_vpcomud:
2616 case X86::BI__builtin_ia32_vpcomuq:
2617 case X86::BI__builtin_ia32_vpcomb:
2618 case X86::BI__builtin_ia32_vpcomw:
2619 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002620 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002621 i = 2; l = 0; u = 7;
2622 break;
2623 case X86::BI__builtin_ia32_roundps:
2624 case X86::BI__builtin_ia32_roundpd:
2625 case X86::BI__builtin_ia32_roundps256:
2626 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002627 i = 1; l = 0; u = 15;
2628 break;
2629 case X86::BI__builtin_ia32_roundss:
2630 case X86::BI__builtin_ia32_roundsd:
2631 case X86::BI__builtin_ia32_rangepd128_mask:
2632 case X86::BI__builtin_ia32_rangepd256_mask:
2633 case X86::BI__builtin_ia32_rangepd512_mask:
2634 case X86::BI__builtin_ia32_rangeps128_mask:
2635 case X86::BI__builtin_ia32_rangeps256_mask:
2636 case X86::BI__builtin_ia32_rangeps512_mask:
2637 case X86::BI__builtin_ia32_getmantsd_round_mask:
2638 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002639 i = 2; l = 0; u = 15;
2640 break;
2641 case X86::BI__builtin_ia32_cmpps:
2642 case X86::BI__builtin_ia32_cmpss:
2643 case X86::BI__builtin_ia32_cmppd:
2644 case X86::BI__builtin_ia32_cmpsd:
2645 case X86::BI__builtin_ia32_cmpps256:
2646 case X86::BI__builtin_ia32_cmppd256:
2647 case X86::BI__builtin_ia32_cmpps128_mask:
2648 case X86::BI__builtin_ia32_cmppd128_mask:
2649 case X86::BI__builtin_ia32_cmpps256_mask:
2650 case X86::BI__builtin_ia32_cmppd256_mask:
2651 case X86::BI__builtin_ia32_cmpps512_mask:
2652 case X86::BI__builtin_ia32_cmppd512_mask:
2653 case X86::BI__builtin_ia32_cmpsd_mask:
2654 case X86::BI__builtin_ia32_cmpss_mask:
2655 i = 2; l = 0; u = 31;
2656 break;
Craig Topper39c87102016-05-18 03:18:12 +00002657 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002658 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002659 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002660 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2661 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002662 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2663 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2664 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2665 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2666 case X86::BI__builtin_ia32_rndscaleps_mask:
2667 case X86::BI__builtin_ia32_rndscalepd_mask:
2668 case X86::BI__builtin_ia32_reducepd128_mask:
2669 case X86::BI__builtin_ia32_reducepd256_mask:
2670 case X86::BI__builtin_ia32_reducepd512_mask:
2671 case X86::BI__builtin_ia32_reduceps128_mask:
2672 case X86::BI__builtin_ia32_reduceps256_mask:
2673 case X86::BI__builtin_ia32_reduceps512_mask:
2674 case X86::BI__builtin_ia32_prold512_mask:
2675 case X86::BI__builtin_ia32_prolq512_mask:
2676 case X86::BI__builtin_ia32_prold128_mask:
2677 case X86::BI__builtin_ia32_prold256_mask:
2678 case X86::BI__builtin_ia32_prolq128_mask:
2679 case X86::BI__builtin_ia32_prolq256_mask:
2680 case X86::BI__builtin_ia32_prord128_mask:
2681 case X86::BI__builtin_ia32_prord256_mask:
2682 case X86::BI__builtin_ia32_prorq128_mask:
2683 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002684 case X86::BI__builtin_ia32_fpclasspd128_mask:
2685 case X86::BI__builtin_ia32_fpclasspd256_mask:
2686 case X86::BI__builtin_ia32_fpclassps128_mask:
2687 case X86::BI__builtin_ia32_fpclassps256_mask:
2688 case X86::BI__builtin_ia32_fpclassps512_mask:
2689 case X86::BI__builtin_ia32_fpclasspd512_mask:
2690 case X86::BI__builtin_ia32_fpclasssd_mask:
2691 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002692 i = 1; l = 0; u = 255;
2693 break;
Craig Topper39c87102016-05-18 03:18:12 +00002694 case X86::BI__builtin_ia32_palignr128:
2695 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002696 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002697 case X86::BI__builtin_ia32_vcomisd:
2698 case X86::BI__builtin_ia32_vcomiss:
2699 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2700 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2701 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2702 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002703 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2704 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2705 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002706 case X86::BI__builtin_ia32_vpshldd128_mask:
2707 case X86::BI__builtin_ia32_vpshldd256_mask:
2708 case X86::BI__builtin_ia32_vpshldd512_mask:
2709 case X86::BI__builtin_ia32_vpshldq128_mask:
2710 case X86::BI__builtin_ia32_vpshldq256_mask:
2711 case X86::BI__builtin_ia32_vpshldq512_mask:
2712 case X86::BI__builtin_ia32_vpshldw128_mask:
2713 case X86::BI__builtin_ia32_vpshldw256_mask:
2714 case X86::BI__builtin_ia32_vpshldw512_mask:
2715 case X86::BI__builtin_ia32_vpshrdd128_mask:
2716 case X86::BI__builtin_ia32_vpshrdd256_mask:
2717 case X86::BI__builtin_ia32_vpshrdd512_mask:
2718 case X86::BI__builtin_ia32_vpshrdq128_mask:
2719 case X86::BI__builtin_ia32_vpshrdq256_mask:
2720 case X86::BI__builtin_ia32_vpshrdq512_mask:
2721 case X86::BI__builtin_ia32_vpshrdw128_mask:
2722 case X86::BI__builtin_ia32_vpshrdw256_mask:
2723 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002724 i = 2; l = 0; u = 255;
2725 break;
2726 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2727 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2728 case X86::BI__builtin_ia32_fixupimmps512_mask:
2729 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2730 case X86::BI__builtin_ia32_fixupimmsd_mask:
2731 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2732 case X86::BI__builtin_ia32_fixupimmss_mask:
2733 case X86::BI__builtin_ia32_fixupimmss_maskz:
2734 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2735 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2736 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2737 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2738 case X86::BI__builtin_ia32_fixupimmps128_mask:
2739 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2740 case X86::BI__builtin_ia32_fixupimmps256_mask:
2741 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2742 case X86::BI__builtin_ia32_pternlogd512_mask:
2743 case X86::BI__builtin_ia32_pternlogd512_maskz:
2744 case X86::BI__builtin_ia32_pternlogq512_mask:
2745 case X86::BI__builtin_ia32_pternlogq512_maskz:
2746 case X86::BI__builtin_ia32_pternlogd128_mask:
2747 case X86::BI__builtin_ia32_pternlogd128_maskz:
2748 case X86::BI__builtin_ia32_pternlogd256_mask:
2749 case X86::BI__builtin_ia32_pternlogd256_maskz:
2750 case X86::BI__builtin_ia32_pternlogq128_mask:
2751 case X86::BI__builtin_ia32_pternlogq128_maskz:
2752 case X86::BI__builtin_ia32_pternlogq256_mask:
2753 case X86::BI__builtin_ia32_pternlogq256_maskz:
2754 i = 3; l = 0; u = 255;
2755 break;
Craig Topper9625db02017-03-12 22:19:10 +00002756 case X86::BI__builtin_ia32_gatherpfdpd:
2757 case X86::BI__builtin_ia32_gatherpfdps:
2758 case X86::BI__builtin_ia32_gatherpfqpd:
2759 case X86::BI__builtin_ia32_gatherpfqps:
2760 case X86::BI__builtin_ia32_scatterpfdpd:
2761 case X86::BI__builtin_ia32_scatterpfdps:
2762 case X86::BI__builtin_ia32_scatterpfqpd:
2763 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002764 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002765 break;
Craig Topper39c87102016-05-18 03:18:12 +00002766 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2767 case X86::BI__builtin_ia32_rndscaless_round_mask:
2768 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002769 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002770 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002771 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002772}
2773
Richard Smith55ce3522012-06-25 20:30:08 +00002774/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2775/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2776/// Returns true when the format fits the function and the FormatStringInfo has
2777/// been populated.
2778bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2779 FormatStringInfo *FSI) {
2780 FSI->HasVAListArg = Format->getFirstArg() == 0;
2781 FSI->FormatIdx = Format->getFormatIdx() - 1;
2782 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002783
Richard Smith55ce3522012-06-25 20:30:08 +00002784 // The way the format attribute works in GCC, the implicit this argument
2785 // of member functions is counted. However, it doesn't appear in our own
2786 // lists, so decrement format_idx in that case.
2787 if (IsCXXMember) {
2788 if(FSI->FormatIdx == 0)
2789 return false;
2790 --FSI->FormatIdx;
2791 if (FSI->FirstDataArg != 0)
2792 --FSI->FirstDataArg;
2793 }
2794 return true;
2795}
Mike Stump11289f42009-09-09 15:08:12 +00002796
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002797/// Checks if a the given expression evaluates to null.
2798///
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002799/// Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002800static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002801 // If the expression has non-null type, it doesn't evaluate to null.
2802 if (auto nullability
2803 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2804 if (*nullability == NullabilityKind::NonNull)
2805 return false;
2806 }
2807
Ted Kremeneka146db32014-01-17 06:24:47 +00002808 // As a special case, transparent unions initialized with zero are
2809 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002810 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002811 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2812 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002813 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002814 if (const InitListExpr *ILE =
2815 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002816 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002817 }
2818
2819 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002820 return (!Expr->isValueDependent() &&
2821 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2822 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002823}
2824
2825static void CheckNonNullArgument(Sema &S,
2826 const Expr *ArgExpr,
2827 SourceLocation CallSiteLoc) {
2828 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002829 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2830 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002831}
2832
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002833bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2834 FormatStringInfo FSI;
2835 if ((GetFormatStringType(Format) == FST_NSString) &&
2836 getFormatStringInfo(Format, false, &FSI)) {
2837 Idx = FSI.FormatIdx;
2838 return true;
2839 }
2840 return false;
2841}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002842
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002843/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002844/// as formatting string to formatting method.
2845static void
2846DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2847 const NamedDecl *FDecl,
2848 Expr **Args,
2849 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002850 unsigned Idx = 0;
2851 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002852 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2853 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002854 Idx = 2;
2855 Format = true;
2856 }
2857 else
2858 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2859 if (S.GetFormatNSStringIdx(I, Idx)) {
2860 Format = true;
2861 break;
2862 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002863 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002864 if (!Format || NumArgs <= Idx)
2865 return;
2866 const Expr *FormatExpr = Args[Idx];
2867 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2868 FormatExpr = CSCE->getSubExpr();
2869 const StringLiteral *FormatString;
2870 if (const ObjCStringLiteral *OSL =
2871 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2872 FormatString = OSL->getString();
2873 else
2874 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2875 if (!FormatString)
2876 return;
2877 if (S.FormatStringHasSArg(FormatString)) {
2878 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2879 << "%s" << 1 << 1;
2880 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2881 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002882 }
2883}
2884
Douglas Gregorb4866e82015-06-19 18:13:19 +00002885/// Determine whether the given type has a non-null nullability annotation.
2886static bool isNonNullType(ASTContext &ctx, QualType type) {
2887 if (auto nullability = type->getNullability(ctx))
2888 return *nullability == NullabilityKind::NonNull;
2889
2890 return false;
2891}
2892
Ted Kremenek2bc73332014-01-17 06:24:43 +00002893static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002894 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002895 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002896 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002897 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002898 assert((FDecl || Proto) && "Need a function declaration or prototype");
2899
Ted Kremenek9aedc152014-01-17 06:24:56 +00002900 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002901 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002902 if (FDecl) {
2903 // Handle the nonnull attribute on the function/method declaration itself.
2904 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2905 if (!NonNull->args_size()) {
2906 // Easy case: all pointer arguments are nonnull.
2907 for (const auto *Arg : Args)
2908 if (S.isValidPointerAttrType(Arg->getType()))
2909 CheckNonNullArgument(S, Arg, CallSiteLoc);
2910 return;
2911 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002912
Joel E. Denny81508102018-03-13 14:51:22 +00002913 for (const ParamIdx &Idx : NonNull->args()) {
2914 unsigned IdxAST = Idx.getASTIndex();
2915 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00002916 continue;
2917 if (NonNullArgs.empty())
2918 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00002919 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002920 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002921 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002922 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002923
Douglas Gregorb4866e82015-06-19 18:13:19 +00002924 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2925 // Handle the nonnull attribute on the parameters of the
2926 // function/method.
2927 ArrayRef<ParmVarDecl*> parms;
2928 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2929 parms = FD->parameters();
2930 else
2931 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2932
2933 unsigned ParamIndex = 0;
2934 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2935 I != E; ++I, ++ParamIndex) {
2936 const ParmVarDecl *PVD = *I;
2937 if (PVD->hasAttr<NonNullAttr>() ||
2938 isNonNullType(S.Context, PVD->getType())) {
2939 if (NonNullArgs.empty())
2940 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002941
Douglas Gregorb4866e82015-06-19 18:13:19 +00002942 NonNullArgs.set(ParamIndex);
2943 }
2944 }
2945 } else {
2946 // If we have a non-function, non-method declaration but no
2947 // function prototype, try to dig out the function prototype.
2948 if (!Proto) {
2949 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2950 QualType type = VD->getType().getNonReferenceType();
2951 if (auto pointerType = type->getAs<PointerType>())
2952 type = pointerType->getPointeeType();
2953 else if (auto blockType = type->getAs<BlockPointerType>())
2954 type = blockType->getPointeeType();
2955 // FIXME: data member pointers?
2956
2957 // Dig out the function prototype, if there is one.
2958 Proto = type->getAs<FunctionProtoType>();
2959 }
2960 }
2961
2962 // Fill in non-null argument information from the nullability
2963 // information on the parameter types (if we have them).
2964 if (Proto) {
2965 unsigned Index = 0;
2966 for (auto paramType : Proto->getParamTypes()) {
2967 if (isNonNullType(S.Context, paramType)) {
2968 if (NonNullArgs.empty())
2969 NonNullArgs.resize(Args.size());
2970
2971 NonNullArgs.set(Index);
2972 }
2973
2974 ++Index;
2975 }
2976 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002977 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002978
Douglas Gregorb4866e82015-06-19 18:13:19 +00002979 // Check for non-null arguments.
2980 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2981 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002982 if (NonNullArgs[ArgIndex])
2983 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002984 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002985}
2986
Richard Smith55ce3522012-06-25 20:30:08 +00002987/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002988/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2989/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002990void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002991 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2992 bool IsMemberFunction, SourceLocation Loc,
2993 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002994 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002995 if (CurContext->isDependentContext())
2996 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002997
Ted Kremenekb8176da2010-09-09 04:33:05 +00002998 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002999 llvm::SmallBitVector CheckedVarArgs;
3000 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003001 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003002 // Only create vector if there are format attributes.
3003 CheckedVarArgs.resize(Args.size());
3004
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003005 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00003006 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00003007 }
Richard Smithd7293d72013-08-05 18:49:43 +00003008 }
Richard Smith55ce3522012-06-25 20:30:08 +00003009
3010 // Refuse POD arguments that weren't caught by the format string
3011 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00003012 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3013 if (CallType != VariadicDoesNotApply &&
3014 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00003015 unsigned NumParams = Proto ? Proto->getNumParams()
3016 : FDecl && isa<FunctionDecl>(FDecl)
3017 ? cast<FunctionDecl>(FDecl)->getNumParams()
3018 : FDecl && isa<ObjCMethodDecl>(FDecl)
3019 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3020 : 0;
3021
Alp Toker9cacbab2014-01-20 20:26:09 +00003022 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003023 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00003024 if (const Expr *Arg = Args[ArgIdx]) {
3025 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3026 checkVariadicArgument(Arg, CallType);
3027 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00003028 }
Richard Smithd7293d72013-08-05 18:49:43 +00003029 }
Mike Stump11289f42009-09-09 15:08:12 +00003030
Douglas Gregorb4866e82015-06-19 18:13:19 +00003031 if (FDecl || Proto) {
3032 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003033
Richard Trieu41bc0992013-06-22 00:20:41 +00003034 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00003035 if (FDecl) {
3036 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00003037 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00003038 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00003039 }
George Burgess IVce6284b2017-01-28 02:19:40 +00003040
3041 if (FD)
3042 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00003043}
3044
3045/// CheckConstructorCall - Check a constructor call for correctness and safety
3046/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003047void Sema::CheckConstructorCall(FunctionDecl *FDecl,
3048 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003049 const FunctionProtoType *Proto,
3050 SourceLocation Loc) {
3051 VariadicCallType CallType =
3052 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00003053 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
3054 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00003055}
3056
3057/// CheckFunctionCall - Check a direct function call for various correctness
3058/// and safety properties not strictly enforced by the C type system.
3059bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
3060 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003061 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
3062 isa<CXXMethodDecl>(FDecl);
3063 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
3064 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00003065 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
3066 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00003067 Expr** Args = TheCall->getArgs();
3068 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00003069
3070 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00003071 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00003072 // If this is a call to a member operator, hide the first argument
3073 // from checkCall.
3074 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00003075 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00003076 ++Args;
3077 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00003078 } else if (IsMemberFunction)
3079 ImplicitThis =
3080 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
3081
3082 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00003083 IsMemberFunction, TheCall->getRParenLoc(),
3084 TheCall->getCallee()->getSourceRange(), CallType);
3085
3086 IdentifierInfo *FnInfo = FDecl->getIdentifier();
3087 // None of the checks below are needed for functions that don't have
3088 // simple names (e.g., C++ conversion functions).
3089 if (!FnInfo)
3090 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003091
Richard Trieua7f30b12016-12-06 01:42:28 +00003092 CheckAbsoluteValueFunction(TheCall, FDecl);
3093 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00003094
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00003095 if (getLangOpts().ObjC1)
3096 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003097
Anna Zaks22122702012-01-17 00:37:07 +00003098 unsigned CMId = FDecl->getMemoryFunctionKind();
3099 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00003100 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00003101
Anna Zaks201d4892012-01-13 21:52:01 +00003102 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00003103 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00003104 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00003105 else if (CMId == Builtin::BIstrncat)
3106 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00003107 else
Anna Zaks22122702012-01-17 00:37:07 +00003108 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003109
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003110 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00003111}
3112
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003113bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00003114 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00003115 VariadicCallType CallType =
3116 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003117
George Burgess IVce6284b2017-01-28 02:19:40 +00003118 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
3119 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003120 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003121
3122 return false;
3123}
3124
Richard Trieu664c4c62013-06-20 21:03:13 +00003125bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
3126 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00003127 QualType Ty;
3128 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003129 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003130 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00003131 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00003132 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003133 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003134
Douglas Gregorb4866e82015-06-19 18:13:19 +00003135 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
3136 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003137 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003138
Richard Trieu664c4c62013-06-20 21:03:13 +00003139 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00003140 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00003141 CallType = VariadicDoesNotApply;
3142 } else if (Ty->isBlockPointerType()) {
3143 CallType = VariadicBlock;
3144 } else { // Ty->isFunctionPointerType()
3145 CallType = VariadicFunction;
3146 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003147
George Burgess IVce6284b2017-01-28 02:19:40 +00003148 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00003149 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
3150 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00003151 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00003152
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003153 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00003154}
3155
Richard Trieu41bc0992013-06-22 00:20:41 +00003156/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
3157/// such as function pointers returned from functions.
3158bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003159 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00003160 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00003161 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00003162 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00003163 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00003164 TheCall->getCallee()->getSourceRange(), CallType);
3165
3166 return false;
3167}
3168
Tim Northovere94a34c2014-03-11 10:49:14 +00003169static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00003170 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00003171 return false;
3172
JF Bastiendda2cb12016-04-18 18:01:49 +00003173 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00003174 switch (Op) {
3175 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003176 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00003177 llvm_unreachable("There is no ordering argument for an init");
3178
3179 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003180 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00003181 case AtomicExpr::AO__atomic_load_n:
3182 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00003183 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
3184 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003185
3186 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003187 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00003188 case AtomicExpr::AO__atomic_store:
3189 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00003190 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
3191 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
3192 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00003193
3194 default:
3195 return true;
3196 }
3197}
3198
Richard Smithfeea8832012-04-12 05:08:17 +00003199ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
3200 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003201 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3202 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003203
Yaxun Liu39195062017-08-04 18:16:31 +00003204 // All the non-OpenCL operations take one of the following forms.
3205 // The OpenCL operations take the __c11 forms with one extra argument for
3206 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00003207 enum {
3208 // C __c11_atomic_init(A *, C)
3209 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003210
Richard Smithfeea8832012-04-12 05:08:17 +00003211 // C __c11_atomic_load(A *, int)
3212 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003213
Richard Smithfeea8832012-04-12 05:08:17 +00003214 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00003215 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003216
Eric Fiselier8d662442016-03-30 23:39:56 +00003217 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00003218 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003219
Richard Smithfeea8832012-04-12 05:08:17 +00003220 // C __c11_atomic_add(A *, M, int)
3221 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003222
Richard Smithfeea8832012-04-12 05:08:17 +00003223 // C __atomic_exchange_n(A *, CP, int)
3224 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003225
Richard Smithfeea8832012-04-12 05:08:17 +00003226 // void __atomic_exchange(A *, C *, CP, int)
3227 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003228
Richard Smithfeea8832012-04-12 05:08:17 +00003229 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3230 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003231
Richard Smithfeea8832012-04-12 05:08:17 +00003232 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3233 GNUCmpXchg
3234 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003235
Yaxun Liu39195062017-08-04 18:16:31 +00003236 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003237 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3238 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003239 // where:
3240 // C is an appropriate type,
3241 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3242 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3243 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3244 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003245
Yaxun Liu39195062017-08-04 18:16:31 +00003246 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3247 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3248 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003249 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3250 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3251 AtomicExpr::AO__atomic_load,
3252 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003253 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3254 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3255 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3256 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3257 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003258 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3259 Op == AtomicExpr::AO__atomic_store_n ||
3260 Op == AtomicExpr::AO__atomic_exchange_n ||
3261 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3262 bool IsAddSub = false;
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003263 bool IsMinMax = false;
Richard Smithfeea8832012-04-12 05:08:17 +00003264
3265 switch (Op) {
3266 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003267 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003268 Form = Init;
3269 break;
3270
3271 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003272 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003273 case AtomicExpr::AO__atomic_load_n:
3274 Form = Load;
3275 break;
3276
Richard Smithfeea8832012-04-12 05:08:17 +00003277 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003278 Form = LoadCopy;
3279 break;
3280
3281 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003282 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003283 case AtomicExpr::AO__atomic_store:
3284 case AtomicExpr::AO__atomic_store_n:
3285 Form = Copy;
3286 break;
3287
3288 case AtomicExpr::AO__c11_atomic_fetch_add:
3289 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003290 case AtomicExpr::AO__opencl_atomic_fetch_add:
3291 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3292 case AtomicExpr::AO__opencl_atomic_fetch_min:
3293 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003294 case AtomicExpr::AO__atomic_fetch_add:
3295 case AtomicExpr::AO__atomic_fetch_sub:
3296 case AtomicExpr::AO__atomic_add_fetch:
3297 case AtomicExpr::AO__atomic_sub_fetch:
3298 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003299 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003300 case AtomicExpr::AO__c11_atomic_fetch_and:
3301 case AtomicExpr::AO__c11_atomic_fetch_or:
3302 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003303 case AtomicExpr::AO__opencl_atomic_fetch_and:
3304 case AtomicExpr::AO__opencl_atomic_fetch_or:
3305 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003306 case AtomicExpr::AO__atomic_fetch_and:
3307 case AtomicExpr::AO__atomic_fetch_or:
3308 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003309 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003310 case AtomicExpr::AO__atomic_and_fetch:
3311 case AtomicExpr::AO__atomic_or_fetch:
3312 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003313 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003314 Form = Arithmetic;
3315 break;
3316
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003317 case AtomicExpr::AO__atomic_fetch_min:
3318 case AtomicExpr::AO__atomic_fetch_max:
3319 IsMinMax = true;
3320 Form = Arithmetic;
3321 break;
3322
Richard Smithfeea8832012-04-12 05:08:17 +00003323 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003324 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003325 case AtomicExpr::AO__atomic_exchange_n:
3326 Form = Xchg;
3327 break;
3328
3329 case AtomicExpr::AO__atomic_exchange:
3330 Form = GNUXchg;
3331 break;
3332
3333 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3334 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003335 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3336 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003337 Form = C11CmpXchg;
3338 break;
3339
3340 case AtomicExpr::AO__atomic_compare_exchange:
3341 case AtomicExpr::AO__atomic_compare_exchange_n:
3342 Form = GNUCmpXchg;
3343 break;
3344 }
3345
Yaxun Liu39195062017-08-04 18:16:31 +00003346 unsigned AdjustedNumArgs = NumArgs[Form];
3347 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3348 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003349 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003350 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003351 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003352 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003353 << TheCall->getCallee()->getSourceRange();
3354 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003355 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3356 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003357 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003358 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003359 << TheCall->getCallee()->getSourceRange();
3360 return ExprError();
3361 }
3362
Richard Smithfeea8832012-04-12 05:08:17 +00003363 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003364 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003365 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3366 if (ConvertedPtr.isInvalid())
3367 return ExprError();
3368
3369 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003370 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3371 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003372 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003373 << Ptr->getType() << Ptr->getSourceRange();
3374 return ExprError();
3375 }
3376
Richard Smithfeea8832012-04-12 05:08:17 +00003377 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3378 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3379 QualType ValType = AtomTy; // 'C'
3380 if (IsC11) {
3381 if (!AtomTy->isAtomicType()) {
3382 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3383 << Ptr->getType() << Ptr->getSourceRange();
3384 return ExprError();
3385 }
Yaxun Liu39195062017-08-04 18:16:31 +00003386 if (AtomTy.isConstQualified() ||
3387 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003388 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003389 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3390 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003391 return ExprError();
3392 }
Richard Smithfeea8832012-04-12 05:08:17 +00003393 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003394 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003395 if (ValType.isConstQualified()) {
3396 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3397 << Ptr->getType() << Ptr->getSourceRange();
3398 return ExprError();
3399 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003400 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003401
Richard Smithfeea8832012-04-12 05:08:17 +00003402 // For an arithmetic operation, the implied arithmetic must be well-formed.
3403 if (Form == Arithmetic) {
3404 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003405 if (IsAddSub && !ValType->isIntegerType()
3406 && !ValType->isPointerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003407 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3408 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3409 return ExprError();
3410 }
Elena Demikhovskyd31327d2018-05-13 07:45:58 +00003411 if (IsMinMax) {
3412 const BuiltinType *BT = ValType->getAs<BuiltinType>();
3413 if (!BT || (BT->getKind() != BuiltinType::Int &&
3414 BT->getKind() != BuiltinType::UInt)) {
3415 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_int32_or_ptr);
3416 return ExprError();
3417 }
3418 }
3419 if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003420 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3421 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3422 return ExprError();
3423 }
David Majnemere85cff82015-01-28 05:48:06 +00003424 if (IsC11 && ValType->isPointerType() &&
3425 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3426 diag::err_incomplete_type)) {
3427 return ExprError();
3428 }
Richard Smithfeea8832012-04-12 05:08:17 +00003429 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3430 // For __atomic_*_n operations, the value type must be a scalar integral or
3431 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003432 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003433 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3434 return ExprError();
3435 }
3436
Eli Friedmanaa769812013-09-11 03:49:34 +00003437 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3438 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003439 // For GNU atomics, require a trivially-copyable type. This is not part of
3440 // the GNU atomics specification, but we enforce it for sanity.
3441 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003442 << Ptr->getType() << Ptr->getSourceRange();
3443 return ExprError();
3444 }
3445
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003446 switch (ValType.getObjCLifetime()) {
3447 case Qualifiers::OCL_None:
3448 case Qualifiers::OCL_ExplicitNone:
3449 // okay
3450 break;
3451
3452 case Qualifiers::OCL_Weak:
3453 case Qualifiers::OCL_Strong:
3454 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003455 // FIXME: Can this happen? By this point, ValType should be known
3456 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003457 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3458 << ValType << Ptr->getSourceRange();
3459 return ExprError();
3460 }
3461
David Majnemerc6eb6502015-06-03 00:26:35 +00003462 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3463 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003464 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003465 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003466 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003467 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003468 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3469 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003470 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003471 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003472 ResultType = Context.BoolTy;
3473
Richard Smithfeea8832012-04-12 05:08:17 +00003474 // The type of a parameter passed 'by value'. In the GNU atomics, such
3475 // arguments are actually passed as pointers.
3476 QualType ByValType = ValType; // 'CP'
3477 if (!IsC11 && !IsN)
3478 ByValType = Ptr->getType();
3479
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003480 // The first argument --- the pointer --- has a fixed type; we
3481 // deduce the types of the rest of the arguments accordingly. Walk
3482 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003483 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003484 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003485 if (i < NumVals[Form] + 1) {
3486 switch (i) {
3487 case 1:
3488 // The second argument is the non-atomic operand. For arithmetic, this
3489 // is always passed by value, and for a compare_exchange it is always
3490 // passed by address. For the rest, GNU uses by-address and C11 uses
3491 // by-value.
3492 assert(Form != Load);
3493 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3494 Ty = ValType;
3495 else if (Form == Copy || Form == Xchg)
3496 Ty = ByValType;
3497 else if (Form == Arithmetic)
3498 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003499 else {
3500 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003501 // Treat this argument as _Nonnull as we want to show a warning if
3502 // NULL is passed into it.
3503 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003504 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003505 // Keep address space of non-atomic pointer type.
3506 if (const PointerType *PtrTy =
3507 ValArg->getType()->getAs<PointerType>()) {
3508 AS = PtrTy->getPointeeType().getAddressSpace();
3509 }
3510 Ty = Context.getPointerType(
3511 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3512 }
Richard Smithfeea8832012-04-12 05:08:17 +00003513 break;
3514 case 2:
3515 // The third argument to compare_exchange / GNU exchange is a
3516 // (pointer to a) desired value.
3517 Ty = ByValType;
3518 break;
3519 case 3:
3520 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3521 Ty = Context.BoolTy;
3522 break;
3523 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003524 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003525 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003526 Ty = Context.IntTy;
3527 }
Richard Smithfeea8832012-04-12 05:08:17 +00003528
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003529 InitializedEntity Entity =
3530 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003531 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003532 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3533 if (Arg.isInvalid())
3534 return true;
3535 TheCall->setArg(i, Arg.get());
3536 }
3537
Richard Smithfeea8832012-04-12 05:08:17 +00003538 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003539 SmallVector<Expr*, 5> SubExprs;
3540 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003541 switch (Form) {
3542 case Init:
3543 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003544 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003545 break;
3546 case Load:
3547 SubExprs.push_back(TheCall->getArg(1)); // Order
3548 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003549 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003550 case Copy:
3551 case Arithmetic:
3552 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003553 SubExprs.push_back(TheCall->getArg(2)); // Order
3554 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003555 break;
3556 case GNUXchg:
3557 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3558 SubExprs.push_back(TheCall->getArg(3)); // Order
3559 SubExprs.push_back(TheCall->getArg(1)); // Val1
3560 SubExprs.push_back(TheCall->getArg(2)); // Val2
3561 break;
3562 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003563 SubExprs.push_back(TheCall->getArg(3)); // Order
3564 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003565 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003566 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003567 break;
3568 case GNUCmpXchg:
3569 SubExprs.push_back(TheCall->getArg(4)); // Order
3570 SubExprs.push_back(TheCall->getArg(1)); // Val1
3571 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3572 SubExprs.push_back(TheCall->getArg(2)); // Val2
3573 SubExprs.push_back(TheCall->getArg(3)); // Weak
3574 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003575 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003576
3577 if (SubExprs.size() >= 2 && Form != Init) {
3578 llvm::APSInt Result(32);
3579 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3580 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003581 Diag(SubExprs[1]->getLocStart(),
3582 diag::warn_atomic_op_has_invalid_memory_order)
3583 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003584 }
3585
Yaxun Liu30d652a2017-08-15 16:02:49 +00003586 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3587 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3588 llvm::APSInt Result(32);
3589 if (Scope->isIntegerConstantExpr(Result, Context) &&
3590 !ScopeModel->isValid(Result.getZExtValue())) {
3591 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3592 << Scope->getSourceRange();
3593 }
3594 SubExprs.push_back(Scope);
3595 }
3596
Fariborz Jahanian615de762013-05-28 17:37:39 +00003597 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3598 SubExprs, ResultType, Op,
3599 TheCall->getRParenLoc());
3600
3601 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003602 Op == AtomicExpr::AO__c11_atomic_store ||
3603 Op == AtomicExpr::AO__opencl_atomic_load ||
3604 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003605 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003606 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3607 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3608 Op == AtomicExpr::AO__opencl_atomic_load)
3609 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003610
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003611 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003612}
3613
John McCall29ad95b2011-08-27 01:09:30 +00003614/// checkBuiltinArgument - Given a call to a builtin function, perform
3615/// normal type-checking on the given argument, updating the call in
3616/// place. This is useful when a builtin function requires custom
3617/// type-checking for some of its arguments but not necessarily all of
3618/// them.
3619///
3620/// Returns true on error.
3621static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3622 FunctionDecl *Fn = E->getDirectCallee();
3623 assert(Fn && "builtin call without direct callee!");
3624
3625 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3626 InitializedEntity Entity =
3627 InitializedEntity::InitializeParameter(S.Context, Param);
3628
3629 ExprResult Arg = E->getArg(0);
3630 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3631 if (Arg.isInvalid())
3632 return true;
3633
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003634 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003635 return false;
3636}
3637
Chris Lattnerdc046542009-05-08 06:58:22 +00003638/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3639/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3640/// type of its first argument. The main ActOnCallExpr routines have already
3641/// promoted the types of arguments because all of these calls are prototyped as
3642/// void(...).
3643///
3644/// This function goes through and does final semantic checking for these
3645/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003646ExprResult
3647Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003648 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003649 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3650 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3651
3652 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003653 if (TheCall->getNumArgs() < 1) {
3654 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3655 << 0 << 1 << TheCall->getNumArgs()
3656 << TheCall->getCallee()->getSourceRange();
3657 return ExprError();
3658 }
Mike Stump11289f42009-09-09 15:08:12 +00003659
Chris Lattnerdc046542009-05-08 06:58:22 +00003660 // Inspect the first argument of the atomic builtin. This should always be
3661 // a pointer type, whose element is an integral scalar or pointer type.
3662 // Because it is a pointer type, we don't have to worry about any implicit
3663 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003664 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003665 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003666 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3667 if (FirstArgResult.isInvalid())
3668 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003669 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003670 TheCall->setArg(0, FirstArg);
3671
John McCall31168b02011-06-15 23:02:42 +00003672 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3673 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003674 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3675 << FirstArg->getType() << FirstArg->getSourceRange();
3676 return ExprError();
3677 }
Mike Stump11289f42009-09-09 15:08:12 +00003678
John McCall31168b02011-06-15 23:02:42 +00003679 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003680 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003681 !ValType->isBlockPointerType()) {
3682 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3683 << FirstArg->getType() << FirstArg->getSourceRange();
3684 return ExprError();
3685 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003686
Aaron Ballmana383c942018-05-05 17:38:42 +00003687 if (ValType.isConstQualified()) {
3688 Diag(DRE->getLocStart(), diag::err_atomic_builtin_cannot_be_const)
3689 << FirstArg->getType() << FirstArg->getSourceRange();
3690 return ExprError();
3691 }
3692
John McCall31168b02011-06-15 23:02:42 +00003693 switch (ValType.getObjCLifetime()) {
3694 case Qualifiers::OCL_None:
3695 case Qualifiers::OCL_ExplicitNone:
3696 // okay
3697 break;
3698
3699 case Qualifiers::OCL_Weak:
3700 case Qualifiers::OCL_Strong:
3701 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003702 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003703 << ValType << FirstArg->getSourceRange();
3704 return ExprError();
3705 }
3706
John McCallb50451a2011-10-05 07:41:44 +00003707 // Strip any qualifiers off ValType.
3708 ValType = ValType.getUnqualifiedType();
3709
Chandler Carruth3973af72010-07-18 20:54:12 +00003710 // The majority of builtins return a value, but a few have special return
3711 // types, so allow them to override appropriately below.
3712 QualType ResultType = ValType;
3713
Chris Lattnerdc046542009-05-08 06:58:22 +00003714 // We need to figure out which concrete builtin this maps onto. For example,
3715 // __sync_fetch_and_add with a 2 byte object turns into
3716 // __sync_fetch_and_add_2.
3717#define BUILTIN_ROW(x) \
3718 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3719 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003720
Chris Lattnerdc046542009-05-08 06:58:22 +00003721 static const unsigned BuiltinIndices[][5] = {
3722 BUILTIN_ROW(__sync_fetch_and_add),
3723 BUILTIN_ROW(__sync_fetch_and_sub),
3724 BUILTIN_ROW(__sync_fetch_and_or),
3725 BUILTIN_ROW(__sync_fetch_and_and),
3726 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003727 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003728
Chris Lattnerdc046542009-05-08 06:58:22 +00003729 BUILTIN_ROW(__sync_add_and_fetch),
3730 BUILTIN_ROW(__sync_sub_and_fetch),
3731 BUILTIN_ROW(__sync_and_and_fetch),
3732 BUILTIN_ROW(__sync_or_and_fetch),
3733 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003734 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003735
Chris Lattnerdc046542009-05-08 06:58:22 +00003736 BUILTIN_ROW(__sync_val_compare_and_swap),
3737 BUILTIN_ROW(__sync_bool_compare_and_swap),
3738 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003739 BUILTIN_ROW(__sync_lock_release),
3740 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003741 };
Mike Stump11289f42009-09-09 15:08:12 +00003742#undef BUILTIN_ROW
3743
Chris Lattnerdc046542009-05-08 06:58:22 +00003744 // Determine the index of the size.
3745 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003746 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003747 case 1: SizeIndex = 0; break;
3748 case 2: SizeIndex = 1; break;
3749 case 4: SizeIndex = 2; break;
3750 case 8: SizeIndex = 3; break;
3751 case 16: SizeIndex = 4; break;
3752 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003753 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3754 << FirstArg->getType() << FirstArg->getSourceRange();
3755 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003756 }
Mike Stump11289f42009-09-09 15:08:12 +00003757
Chris Lattnerdc046542009-05-08 06:58:22 +00003758 // Each of these builtins has one pointer argument, followed by some number of
3759 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3760 // that we ignore. Find out which row of BuiltinIndices to read from as well
3761 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003762 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003763 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003764 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003765 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003766 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003767 case Builtin::BI__sync_fetch_and_add:
3768 case Builtin::BI__sync_fetch_and_add_1:
3769 case Builtin::BI__sync_fetch_and_add_2:
3770 case Builtin::BI__sync_fetch_and_add_4:
3771 case Builtin::BI__sync_fetch_and_add_8:
3772 case Builtin::BI__sync_fetch_and_add_16:
3773 BuiltinIndex = 0;
3774 break;
3775
3776 case Builtin::BI__sync_fetch_and_sub:
3777 case Builtin::BI__sync_fetch_and_sub_1:
3778 case Builtin::BI__sync_fetch_and_sub_2:
3779 case Builtin::BI__sync_fetch_and_sub_4:
3780 case Builtin::BI__sync_fetch_and_sub_8:
3781 case Builtin::BI__sync_fetch_and_sub_16:
3782 BuiltinIndex = 1;
3783 break;
3784
3785 case Builtin::BI__sync_fetch_and_or:
3786 case Builtin::BI__sync_fetch_and_or_1:
3787 case Builtin::BI__sync_fetch_and_or_2:
3788 case Builtin::BI__sync_fetch_and_or_4:
3789 case Builtin::BI__sync_fetch_and_or_8:
3790 case Builtin::BI__sync_fetch_and_or_16:
3791 BuiltinIndex = 2;
3792 break;
3793
3794 case Builtin::BI__sync_fetch_and_and:
3795 case Builtin::BI__sync_fetch_and_and_1:
3796 case Builtin::BI__sync_fetch_and_and_2:
3797 case Builtin::BI__sync_fetch_and_and_4:
3798 case Builtin::BI__sync_fetch_and_and_8:
3799 case Builtin::BI__sync_fetch_and_and_16:
3800 BuiltinIndex = 3;
3801 break;
Mike Stump11289f42009-09-09 15:08:12 +00003802
Douglas Gregor73722482011-11-28 16:30:08 +00003803 case Builtin::BI__sync_fetch_and_xor:
3804 case Builtin::BI__sync_fetch_and_xor_1:
3805 case Builtin::BI__sync_fetch_and_xor_2:
3806 case Builtin::BI__sync_fetch_and_xor_4:
3807 case Builtin::BI__sync_fetch_and_xor_8:
3808 case Builtin::BI__sync_fetch_and_xor_16:
3809 BuiltinIndex = 4;
3810 break;
3811
Hal Finkeld2208b52014-10-02 20:53:50 +00003812 case Builtin::BI__sync_fetch_and_nand:
3813 case Builtin::BI__sync_fetch_and_nand_1:
3814 case Builtin::BI__sync_fetch_and_nand_2:
3815 case Builtin::BI__sync_fetch_and_nand_4:
3816 case Builtin::BI__sync_fetch_and_nand_8:
3817 case Builtin::BI__sync_fetch_and_nand_16:
3818 BuiltinIndex = 5;
3819 WarnAboutSemanticsChange = true;
3820 break;
3821
Douglas Gregor73722482011-11-28 16:30:08 +00003822 case Builtin::BI__sync_add_and_fetch:
3823 case Builtin::BI__sync_add_and_fetch_1:
3824 case Builtin::BI__sync_add_and_fetch_2:
3825 case Builtin::BI__sync_add_and_fetch_4:
3826 case Builtin::BI__sync_add_and_fetch_8:
3827 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003828 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003829 break;
3830
3831 case Builtin::BI__sync_sub_and_fetch:
3832 case Builtin::BI__sync_sub_and_fetch_1:
3833 case Builtin::BI__sync_sub_and_fetch_2:
3834 case Builtin::BI__sync_sub_and_fetch_4:
3835 case Builtin::BI__sync_sub_and_fetch_8:
3836 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003837 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003838 break;
3839
3840 case Builtin::BI__sync_and_and_fetch:
3841 case Builtin::BI__sync_and_and_fetch_1:
3842 case Builtin::BI__sync_and_and_fetch_2:
3843 case Builtin::BI__sync_and_and_fetch_4:
3844 case Builtin::BI__sync_and_and_fetch_8:
3845 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003846 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003847 break;
3848
3849 case Builtin::BI__sync_or_and_fetch:
3850 case Builtin::BI__sync_or_and_fetch_1:
3851 case Builtin::BI__sync_or_and_fetch_2:
3852 case Builtin::BI__sync_or_and_fetch_4:
3853 case Builtin::BI__sync_or_and_fetch_8:
3854 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003855 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003856 break;
3857
3858 case Builtin::BI__sync_xor_and_fetch:
3859 case Builtin::BI__sync_xor_and_fetch_1:
3860 case Builtin::BI__sync_xor_and_fetch_2:
3861 case Builtin::BI__sync_xor_and_fetch_4:
3862 case Builtin::BI__sync_xor_and_fetch_8:
3863 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003864 BuiltinIndex = 10;
3865 break;
3866
3867 case Builtin::BI__sync_nand_and_fetch:
3868 case Builtin::BI__sync_nand_and_fetch_1:
3869 case Builtin::BI__sync_nand_and_fetch_2:
3870 case Builtin::BI__sync_nand_and_fetch_4:
3871 case Builtin::BI__sync_nand_and_fetch_8:
3872 case Builtin::BI__sync_nand_and_fetch_16:
3873 BuiltinIndex = 11;
3874 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003875 break;
Mike Stump11289f42009-09-09 15:08:12 +00003876
Chris Lattnerdc046542009-05-08 06:58:22 +00003877 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003878 case Builtin::BI__sync_val_compare_and_swap_1:
3879 case Builtin::BI__sync_val_compare_and_swap_2:
3880 case Builtin::BI__sync_val_compare_and_swap_4:
3881 case Builtin::BI__sync_val_compare_and_swap_8:
3882 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003883 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003884 NumFixed = 2;
3885 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003886
Chris Lattnerdc046542009-05-08 06:58:22 +00003887 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003888 case Builtin::BI__sync_bool_compare_and_swap_1:
3889 case Builtin::BI__sync_bool_compare_and_swap_2:
3890 case Builtin::BI__sync_bool_compare_and_swap_4:
3891 case Builtin::BI__sync_bool_compare_and_swap_8:
3892 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003893 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003894 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003895 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003896 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003897
3898 case Builtin::BI__sync_lock_test_and_set:
3899 case Builtin::BI__sync_lock_test_and_set_1:
3900 case Builtin::BI__sync_lock_test_and_set_2:
3901 case Builtin::BI__sync_lock_test_and_set_4:
3902 case Builtin::BI__sync_lock_test_and_set_8:
3903 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003904 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003905 break;
3906
Chris Lattnerdc046542009-05-08 06:58:22 +00003907 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003908 case Builtin::BI__sync_lock_release_1:
3909 case Builtin::BI__sync_lock_release_2:
3910 case Builtin::BI__sync_lock_release_4:
3911 case Builtin::BI__sync_lock_release_8:
3912 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003913 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003914 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003915 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003916 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003917
3918 case Builtin::BI__sync_swap:
3919 case Builtin::BI__sync_swap_1:
3920 case Builtin::BI__sync_swap_2:
3921 case Builtin::BI__sync_swap_4:
3922 case Builtin::BI__sync_swap_8:
3923 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003924 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003925 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003926 }
Mike Stump11289f42009-09-09 15:08:12 +00003927
Chris Lattnerdc046542009-05-08 06:58:22 +00003928 // Now that we know how many fixed arguments we expect, first check that we
3929 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003930 if (TheCall->getNumArgs() < 1+NumFixed) {
3931 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3932 << 0 << 1+NumFixed << TheCall->getNumArgs()
3933 << TheCall->getCallee()->getSourceRange();
3934 return ExprError();
3935 }
Mike Stump11289f42009-09-09 15:08:12 +00003936
Hal Finkeld2208b52014-10-02 20:53:50 +00003937 if (WarnAboutSemanticsChange) {
3938 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3939 << TheCall->getCallee()->getSourceRange();
3940 }
3941
Chris Lattner5b9241b2009-05-08 15:36:58 +00003942 // Get the decl for the concrete builtin from this, we can tell what the
3943 // concrete integer type we should convert to is.
3944 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003945 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003946 FunctionDecl *NewBuiltinDecl;
3947 if (NewBuiltinID == BuiltinID)
3948 NewBuiltinDecl = FDecl;
3949 else {
3950 // Perform builtin lookup to avoid redeclaring it.
3951 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3952 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3953 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3954 assert(Res.getFoundDecl());
3955 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003956 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003957 return ExprError();
3958 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003959
John McCallcf142162010-08-07 06:22:56 +00003960 // The first argument --- the pointer --- has a fixed type; we
3961 // deduce the types of the rest of the arguments accordingly. Walk
3962 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003963 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003964 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003965
Chris Lattnerdc046542009-05-08 06:58:22 +00003966 // GCC does an implicit conversion to the pointer or integer ValType. This
3967 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003968 // Initialize the argument.
3969 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3970 ValType, /*consume*/ false);
3971 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003972 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003973 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003974
Chris Lattnerdc046542009-05-08 06:58:22 +00003975 // Okay, we have something that *can* be converted to the right type. Check
3976 // to see if there is a potentially weird extension going on here. This can
3977 // happen when you do an atomic operation on something like an char* and
3978 // pass in 42. The 42 gets converted to char. This is even more strange
3979 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003980 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003981 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003982 }
Mike Stump11289f42009-09-09 15:08:12 +00003983
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003984 ASTContext& Context = this->getASTContext();
3985
3986 // Create a new DeclRefExpr to refer to the new decl.
3987 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3988 Context,
3989 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003990 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003991 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003992 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003993 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003994 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003995 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003996
Chris Lattnerdc046542009-05-08 06:58:22 +00003997 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003998 // FIXME: This loses syntactic information.
3999 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
4000 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
4001 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004002 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00004003
Chandler Carruthbc8cab12010-07-18 07:23:17 +00004004 // Change the result type of the call to match the original value type. This
4005 // is arbitrary, but the codegen for these builtins ins design to handle it
4006 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00004007 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00004008
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004009 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00004010}
4011
Michael Zolotukhin84df1232015-09-08 23:52:33 +00004012/// SemaBuiltinNontemporalOverloaded - We have a call to
4013/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
4014/// overloaded function based on the pointer type of its last argument.
4015///
4016/// This function goes through and does final semantic checking for these
4017/// builtins.
4018ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
4019 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
4020 DeclRefExpr *DRE =
4021 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4022 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4023 unsigned BuiltinID = FDecl->getBuiltinID();
4024 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
4025 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
4026 "Unexpected nontemporal load/store builtin!");
4027 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
4028 unsigned numArgs = isStore ? 2 : 1;
4029
4030 // Ensure that we have the proper number of arguments.
4031 if (checkArgCount(*this, TheCall, numArgs))
4032 return ExprError();
4033
4034 // Inspect the last argument of the nontemporal builtin. This should always
4035 // be a pointer type, from which we imply the type of the memory access.
4036 // Because it is a pointer type, we don't have to worry about any implicit
4037 // casts here.
4038 Expr *PointerArg = TheCall->getArg(numArgs - 1);
4039 ExprResult PointerArgResult =
4040 DefaultFunctionArrayLvalueConversion(PointerArg);
4041
4042 if (PointerArgResult.isInvalid())
4043 return ExprError();
4044 PointerArg = PointerArgResult.get();
4045 TheCall->setArg(numArgs - 1, PointerArg);
4046
4047 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
4048 if (!pointerType) {
4049 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
4050 << PointerArg->getType() << PointerArg->getSourceRange();
4051 return ExprError();
4052 }
4053
4054 QualType ValType = pointerType->getPointeeType();
4055
4056 // Strip any qualifiers off ValType.
4057 ValType = ValType.getUnqualifiedType();
4058 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4059 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
4060 !ValType->isVectorType()) {
4061 Diag(DRE->getLocStart(),
4062 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
4063 << PointerArg->getType() << PointerArg->getSourceRange();
4064 return ExprError();
4065 }
4066
4067 if (!isStore) {
4068 TheCall->setType(ValType);
4069 return TheCallResult;
4070 }
4071
4072 ExprResult ValArg = TheCall->getArg(0);
4073 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4074 Context, ValType, /*consume*/ false);
4075 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
4076 if (ValArg.isInvalid())
4077 return ExprError();
4078
4079 TheCall->setArg(0, ValArg.get());
4080 TheCall->setType(Context.VoidTy);
4081 return TheCallResult;
4082}
4083
Chris Lattner6436fb62009-02-18 06:01:06 +00004084/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00004085/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00004086/// Note: It might also make sense to do the UTF-16 conversion here (would
4087/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00004088bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00004089 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00004090 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
4091
Douglas Gregorfb65e592011-07-27 05:40:30 +00004092 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00004093 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
4094 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00004095 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00004096 }
Mike Stump11289f42009-09-09 15:08:12 +00004097
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004098 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004099 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004100 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00004101 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
4102 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4103 llvm::UTF16 *ToPtr = &ToBuf[0];
4104
4105 llvm::ConversionResult Result =
4106 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4107 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004108 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00004109 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00004110 Diag(Arg->getLocStart(),
4111 diag::warn_cfstring_truncated) << Arg->getSourceRange();
4112 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00004113 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00004114}
4115
Mehdi Amini06d367c2016-10-24 20:39:34 +00004116/// CheckObjCString - Checks that the format string argument to the os_log()
4117/// and os_trace() functions is correct, and converts it to const char *.
4118ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
4119 Arg = Arg->IgnoreParenCasts();
4120 auto *Literal = dyn_cast<StringLiteral>(Arg);
4121 if (!Literal) {
4122 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
4123 Literal = ObjcLiteral->getString();
4124 }
4125 }
4126
4127 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
4128 return ExprError(
4129 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
4130 << Arg->getSourceRange());
4131 }
4132
4133 ExprResult Result(Literal);
4134 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
4135 InitializedEntity Entity =
4136 InitializedEntity::InitializeParameter(Context, ResultTy, false);
4137 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
4138 return Result;
4139}
4140
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004141/// Check that the user is calling the appropriate va_start builtin for the
4142/// target and calling convention.
4143static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
4144 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
4145 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00004146 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004147 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00004148 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
4149 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004150 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004151 if (const FunctionDecl *FD = S.getCurFunctionDecl())
4152 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
4153 if (IsMSVAStart) {
4154 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00004155 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004156 return S.Diag(Fn->getLocStart(),
4157 diag::err_ms_va_start_used_in_sysv_function);
4158 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00004159 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004160 // On x64 Windows, don't allow this in System V ABI functions.
4161 // (Yes, that means there's no corresponding way to support variadic
4162 // System V ABI functions on Windows.)
4163 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00004164 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004165 return S.Diag(Fn->getLocStart(),
4166 diag::err_va_start_used_in_wrong_abi_function)
4167 << !IsWindows;
4168 }
4169 return false;
4170 }
4171
4172 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00004173 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004174 return false;
4175}
4176
4177static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
4178 ParmVarDecl **LastParam = nullptr) {
4179 // Determine whether the current function, block, or obj-c method is variadic
4180 // and get its parameter list.
4181 bool IsVariadic = false;
4182 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00004183 DeclContext *Caller = S.CurContext;
4184 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
4185 IsVariadic = Block->isVariadic();
4186 Params = Block->parameters();
4187 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004188 IsVariadic = FD->isVariadic();
4189 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004190 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004191 IsVariadic = MD->isVariadic();
4192 // FIXME: This isn't correct for methods (results in bogus warning).
4193 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00004194 } else if (isa<CapturedDecl>(Caller)) {
4195 // We don't support va_start in a CapturedDecl.
4196 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
4197 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004198 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004199 // This must be some other declcontext that parses exprs.
4200 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
4201 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004202 }
4203
4204 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00004205 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004206 return true;
4207 }
4208
4209 if (LastParam)
4210 *LastParam = Params.empty() ? nullptr : Params.back();
4211
4212 return false;
4213}
4214
Charles Davisc7d5c942015-09-17 20:55:33 +00004215/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
4216/// for validity. Emit an error and return true on failure; return false
4217/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004218bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00004219 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004220
4221 if (checkVAStartABI(*this, BuiltinID, Fn))
4222 return true;
4223
Chris Lattner08464942007-12-28 05:29:59 +00004224 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00004225 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004226 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004227 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4228 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00004229 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004230 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00004231 return true;
4232 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004233
4234 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00004235 return Diag(TheCall->getLocEnd(),
4236 diag::err_typecheck_call_too_few_args_at_least)
4237 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00004238 }
4239
John McCall29ad95b2011-08-27 01:09:30 +00004240 // Type-check the first argument normally.
4241 if (checkBuiltinArgument(*this, TheCall, 0))
4242 return true;
4243
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004244 // Check that the current function is variadic, and get its last parameter.
4245 ParmVarDecl *LastParam;
4246 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00004247 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004248
Chris Lattner43be2e62007-12-19 23:59:04 +00004249 // Verify that the second argument to the builtin is the last argument of the
4250 // current function or method.
4251 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00004252 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004253
Nico Weber9eea7642013-05-24 23:31:57 +00004254 // These are valid if SecondArgIsLastNamedArgument is false after the next
4255 // block.
4256 QualType Type;
4257 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00004258 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00004259
Anders Carlsson6a8350b2008-02-11 04:20:54 +00004260 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4261 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004262 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004263
4264 Type = PV->getType();
4265 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004266 IsCRegister =
4267 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004268 }
4269 }
Mike Stump11289f42009-09-09 15:08:12 +00004270
Chris Lattner43be2e62007-12-19 23:59:04 +00004271 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004272 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004273 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004274 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004275 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4276 // Promotable integers are UB, but enumerations need a bit of
4277 // extra checking to see what their promotable type actually is.
4278 if (!Type->isPromotableIntegerType())
4279 return false;
4280 if (!Type->isEnumeralType())
4281 return true;
4282 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4283 return !(ED &&
4284 Context.typesAreCompatible(ED->getPromotionType(), Type));
4285 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004286 unsigned Reason = 0;
4287 if (Type->isReferenceType()) Reason = 1;
4288 else if (IsCRegister) Reason = 2;
4289 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004290 Diag(ParamLoc, diag::note_parameter_type) << Type;
4291 }
4292
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004293 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004294 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004295}
Chris Lattner43be2e62007-12-19 23:59:04 +00004296
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004297bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004298 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4299 // const char *named_addr);
4300
4301 Expr *Func = Call->getCallee();
4302
4303 if (Call->getNumArgs() < 3)
4304 return Diag(Call->getLocEnd(),
4305 diag::err_typecheck_call_too_few_args_at_least)
4306 << 0 /*function call*/ << 3 << Call->getNumArgs();
4307
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004308 // Type-check the first argument normally.
4309 if (checkBuiltinArgument(*this, Call, 0))
4310 return true;
4311
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004312 // Check that the current function is variadic.
4313 if (checkVAStartIsInVariadicFunction(*this, Func))
4314 return true;
4315
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004316 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004317
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004318 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4319 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4320
4321 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4322 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4323
4324 const QualType &ConstCharPtrTy =
4325 Context.getPointerType(Context.CharTy.withConst());
4326 if (!Arg1Ty->isPointerType() ||
4327 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4328 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4329 << Arg1->getType() << ConstCharPtrTy
4330 << 1 /* different class */
4331 << 0 /* qualifier difference */
4332 << 3 /* parameter mismatch */
4333 << 2 << Arg1->getType() << ConstCharPtrTy;
4334
4335 const QualType SizeTy = Context.getSizeType();
4336 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4337 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4338 << Arg2->getType() << SizeTy
4339 << 1 /* different class */
4340 << 0 /* qualifier difference */
4341 << 3 /* parameter mismatch */
4342 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004343
4344 return false;
4345}
4346
Chris Lattner2da14fb2007-12-20 00:26:33 +00004347/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4348/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004349bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4350 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004351 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004352 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004353 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004354 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004355 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004356 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004357 << SourceRange(TheCall->getArg(2)->getLocStart(),
4358 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004359
John Wiegley01296292011-04-08 18:41:53 +00004360 ExprResult OrigArg0 = TheCall->getArg(0);
4361 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004362
Chris Lattner2da14fb2007-12-20 00:26:33 +00004363 // Do standard promotions between the two arguments, returning their common
4364 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004365 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004366 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4367 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004368
4369 // Make sure any conversions are pushed back into the call; this is
4370 // type safe since unordered compare builtins are declared as "_Bool
4371 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004372 TheCall->setArg(0, OrigArg0.get());
4373 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004374
John Wiegley01296292011-04-08 18:41:53 +00004375 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004376 return false;
4377
Chris Lattner2da14fb2007-12-20 00:26:33 +00004378 // If the common type isn't a real floating type, then the arguments were
4379 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004380 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004381 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004382 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004383 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4384 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004385
Chris Lattner2da14fb2007-12-20 00:26:33 +00004386 return false;
4387}
4388
Benjamin Kramer634fc102010-02-15 22:42:31 +00004389/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4390/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004391/// to check everything. We expect the last argument to be a floating point
4392/// value.
4393bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4394 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004395 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004396 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004397 if (TheCall->getNumArgs() > NumArgs)
4398 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004399 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004400 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004401 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004402 (*(TheCall->arg_end()-1))->getLocEnd());
4403
Benjamin Kramer64aae502010-02-16 10:07:31 +00004404 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004405
Eli Friedman7e4faac2009-08-31 20:06:00 +00004406 if (OrigArg->isTypeDependent())
4407 return false;
4408
Chris Lattner68784ef2010-05-06 05:50:07 +00004409 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004410 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004411 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004412 diag::err_typecheck_call_invalid_unary_fp)
4413 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004414
Neil Hickey88c0fac2016-12-13 16:22:50 +00004415 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004416 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004417 // Only remove standard FloatCasts, leaving other casts inplace
4418 if (Cast->getCastKind() == CK_FloatingCast) {
4419 Expr *CastArg = Cast->getSubExpr();
4420 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4421 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4422 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4423 "promotion from float to either float or double is the only expected cast here");
4424 Cast->setSubExpr(nullptr);
4425 TheCall->setArg(NumArgs-1, CastArg);
4426 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004427 }
4428 }
4429
Eli Friedman7e4faac2009-08-31 20:06:00 +00004430 return false;
4431}
4432
Tony Jiangbbc48e92017-05-24 15:13:32 +00004433// Customized Sema Checking for VSX builtins that have the following signature:
4434// vector [...] builtinName(vector [...], vector [...], const int);
4435// Which takes the same type of vectors (any legal vector type) for the first
4436// two arguments and takes compile time constant for the third argument.
4437// Example builtins are :
4438// vector double vec_xxpermdi(vector double, vector double, int);
4439// vector short vec_xxsldwi(vector short, vector short, int);
4440bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4441 unsigned ExpectedNumArgs = 3;
4442 if (TheCall->getNumArgs() < ExpectedNumArgs)
4443 return Diag(TheCall->getLocEnd(),
4444 diag::err_typecheck_call_too_few_args_at_least)
4445 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4446 << TheCall->getSourceRange();
4447
4448 if (TheCall->getNumArgs() > ExpectedNumArgs)
4449 return Diag(TheCall->getLocEnd(),
4450 diag::err_typecheck_call_too_many_args_at_most)
4451 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4452 << TheCall->getSourceRange();
4453
4454 // Check the third argument is a compile time constant
4455 llvm::APSInt Value;
4456 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4457 return Diag(TheCall->getLocStart(),
4458 diag::err_vsx_builtin_nonconstant_argument)
4459 << 3 /* argument index */ << TheCall->getDirectCallee()
4460 << SourceRange(TheCall->getArg(2)->getLocStart(),
4461 TheCall->getArg(2)->getLocEnd());
4462
4463 QualType Arg1Ty = TheCall->getArg(0)->getType();
4464 QualType Arg2Ty = TheCall->getArg(1)->getType();
4465
4466 // Check the type of argument 1 and argument 2 are vectors.
4467 SourceLocation BuiltinLoc = TheCall->getLocStart();
4468 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4469 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4470 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4471 << TheCall->getDirectCallee()
4472 << SourceRange(TheCall->getArg(0)->getLocStart(),
4473 TheCall->getArg(1)->getLocEnd());
4474 }
4475
4476 // Check the first two arguments are the same type.
4477 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4478 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4479 << TheCall->getDirectCallee()
4480 << SourceRange(TheCall->getArg(0)->getLocStart(),
4481 TheCall->getArg(1)->getLocEnd());
4482 }
4483
4484 // When default clang type checking is turned off and the customized type
4485 // checking is used, the returning type of the function must be explicitly
4486 // set. Otherwise it is _Bool by default.
4487 TheCall->setType(Arg1Ty);
4488
4489 return false;
4490}
4491
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004492/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4493// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004494ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004495 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004496 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004497 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004498 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4499 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004500
Nate Begemana0110022010-06-08 00:16:34 +00004501 // Determine which of the following types of shufflevector we're checking:
4502 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004503 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004504 QualType resType = TheCall->getArg(0)->getType();
4505 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004506
Douglas Gregorc25f7662009-05-19 22:10:17 +00004507 if (!TheCall->getArg(0)->isTypeDependent() &&
4508 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004509 QualType LHSType = TheCall->getArg(0)->getType();
4510 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004511
Craig Topperbaca3892013-07-29 06:47:04 +00004512 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4513 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004514 diag::err_vec_builtin_non_vector)
4515 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004516 << SourceRange(TheCall->getArg(0)->getLocStart(),
4517 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004518
Nate Begemana0110022010-06-08 00:16:34 +00004519 numElements = LHSType->getAs<VectorType>()->getNumElements();
4520 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004521
Nate Begemana0110022010-06-08 00:16:34 +00004522 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4523 // with mask. If so, verify that RHS is an integer vector type with the
4524 // same number of elts as lhs.
4525 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004526 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004527 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004528 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004529 diag::err_vec_builtin_incompatible_vector)
4530 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004531 << SourceRange(TheCall->getArg(1)->getLocStart(),
4532 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004533 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004534 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004535 diag::err_vec_builtin_incompatible_vector)
4536 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004537 << SourceRange(TheCall->getArg(0)->getLocStart(),
4538 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004539 } else if (numElements != numResElements) {
4540 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004541 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004542 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004543 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004544 }
4545
4546 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004547 if (TheCall->getArg(i)->isTypeDependent() ||
4548 TheCall->getArg(i)->isValueDependent())
4549 continue;
4550
Nate Begemana0110022010-06-08 00:16:34 +00004551 llvm::APSInt Result(32);
4552 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4553 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004554 diag::err_shufflevector_nonconstant_argument)
4555 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004556
Craig Topper50ad5b72013-08-03 17:40:38 +00004557 // Allow -1 which will be translated to undef in the IR.
4558 if (Result.isSigned() && Result.isAllOnesValue())
4559 continue;
4560
Chris Lattner7ab824e2008-08-10 02:05:13 +00004561 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004562 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004563 diag::err_shufflevector_argument_too_large)
4564 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004565 }
4566
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004567 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004568
Chris Lattner7ab824e2008-08-10 02:05:13 +00004569 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004570 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004571 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004572 }
4573
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004574 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4575 TheCall->getCallee()->getLocStart(),
4576 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004577}
Chris Lattner43be2e62007-12-19 23:59:04 +00004578
Hal Finkelc4d7c822013-09-18 03:29:45 +00004579/// SemaConvertVectorExpr - Handle __builtin_convertvector
4580ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4581 SourceLocation BuiltinLoc,
4582 SourceLocation RParenLoc) {
4583 ExprValueKind VK = VK_RValue;
4584 ExprObjectKind OK = OK_Ordinary;
4585 QualType DstTy = TInfo->getType();
4586 QualType SrcTy = E->getType();
4587
4588 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4589 return ExprError(Diag(BuiltinLoc,
4590 diag::err_convertvector_non_vector)
4591 << E->getSourceRange());
4592 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4593 return ExprError(Diag(BuiltinLoc,
4594 diag::err_convertvector_non_vector_type));
4595
4596 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4597 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4598 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4599 if (SrcElts != DstElts)
4600 return ExprError(Diag(BuiltinLoc,
4601 diag::err_convertvector_incompatible_vector)
4602 << E->getSourceRange());
4603 }
4604
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004605 return new (Context)
4606 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004607}
4608
Daniel Dunbarb7257262008-07-21 22:59:13 +00004609/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4610// This is declared to take (const void*, ...) and can take two
4611// optional constant int args.
4612bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004613 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004614
Chris Lattner3b054132008-11-19 05:08:23 +00004615 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004616 return Diag(TheCall->getLocEnd(),
4617 diag::err_typecheck_call_too_many_args_at_most)
4618 << 0 /*function call*/ << 3 << NumArgs
4619 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004620
4621 // Argument 0 is checked for us and the remaining arguments must be
4622 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004623 for (unsigned i = 1; i != NumArgs; ++i)
4624 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004625 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004626
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004627 return false;
4628}
4629
Hal Finkelf0417332014-07-17 14:25:55 +00004630/// SemaBuiltinAssume - Handle __assume (MS Extension).
4631// __assume does not evaluate its arguments, and should warn if its argument
4632// has side effects.
4633bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4634 Expr *Arg = TheCall->getArg(0);
4635 if (Arg->isInstantiationDependent()) return false;
4636
4637 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004638 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004639 << Arg->getSourceRange()
4640 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4641
4642 return false;
4643}
4644
David Majnemer86b1bfa2016-10-31 18:07:57 +00004645/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004646/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4647/// than 8.
4648bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4649 // The alignment must be a constant integer.
4650 Expr *Arg = TheCall->getArg(1);
4651
4652 // We can't check the value of a dependent argument.
4653 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004654 if (const auto *UE =
4655 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4656 if (UE->getKind() == UETT_AlignOf)
4657 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4658 << Arg->getSourceRange();
4659
David Majnemer51169932016-10-31 05:37:48 +00004660 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4661
4662 if (!Result.isPowerOf2())
4663 return Diag(TheCall->getLocStart(),
4664 diag::err_alignment_not_power_of_two)
4665 << Arg->getSourceRange();
4666
4667 if (Result < Context.getCharWidth())
4668 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4669 << (unsigned)Context.getCharWidth()
4670 << Arg->getSourceRange();
4671
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004672 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004673 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004674 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004675 << Arg->getSourceRange();
4676 }
4677
4678 return false;
4679}
4680
4681/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004682/// as (const void*, size_t, ...) and can take one optional constant int arg.
4683bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4684 unsigned NumArgs = TheCall->getNumArgs();
4685
4686 if (NumArgs > 3)
4687 return Diag(TheCall->getLocEnd(),
4688 diag::err_typecheck_call_too_many_args_at_most)
4689 << 0 /*function call*/ << 3 << NumArgs
4690 << TheCall->getSourceRange();
4691
4692 // The alignment must be a constant integer.
4693 Expr *Arg = TheCall->getArg(1);
4694
4695 // We can't check the value of a dependent argument.
4696 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4697 llvm::APSInt Result;
4698 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4699 return true;
4700
4701 if (!Result.isPowerOf2())
4702 return Diag(TheCall->getLocStart(),
4703 diag::err_alignment_not_power_of_two)
4704 << Arg->getSourceRange();
4705 }
4706
4707 if (NumArgs > 2) {
4708 ExprResult Arg(TheCall->getArg(2));
4709 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4710 Context.getSizeType(), false);
4711 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4712 if (Arg.isInvalid()) return true;
4713 TheCall->setArg(2, Arg.get());
4714 }
Hal Finkelf0417332014-07-17 14:25:55 +00004715
4716 return false;
4717}
4718
Mehdi Amini06d367c2016-10-24 20:39:34 +00004719bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4720 unsigned BuiltinID =
4721 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4722 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4723
4724 unsigned NumArgs = TheCall->getNumArgs();
4725 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4726 if (NumArgs < NumRequiredArgs) {
4727 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4728 << 0 /* function call */ << NumRequiredArgs << NumArgs
4729 << TheCall->getSourceRange();
4730 }
4731 if (NumArgs >= NumRequiredArgs + 0x100) {
4732 return Diag(TheCall->getLocEnd(),
4733 diag::err_typecheck_call_too_many_args_at_most)
4734 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4735 << TheCall->getSourceRange();
4736 }
4737 unsigned i = 0;
4738
4739 // For formatting call, check buffer arg.
4740 if (!IsSizeCall) {
4741 ExprResult Arg(TheCall->getArg(i));
4742 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4743 Context, Context.VoidPtrTy, false);
4744 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4745 if (Arg.isInvalid())
4746 return true;
4747 TheCall->setArg(i, Arg.get());
4748 i++;
4749 }
4750
4751 // Check string literal arg.
4752 unsigned FormatIdx = i;
4753 {
4754 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4755 if (Arg.isInvalid())
4756 return true;
4757 TheCall->setArg(i, Arg.get());
4758 i++;
4759 }
4760
4761 // Make sure variadic args are scalar.
4762 unsigned FirstDataArg = i;
4763 while (i < NumArgs) {
4764 ExprResult Arg = DefaultVariadicArgumentPromotion(
4765 TheCall->getArg(i), VariadicFunction, nullptr);
4766 if (Arg.isInvalid())
4767 return true;
4768 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4769 if (ArgSize.getQuantity() >= 0x100) {
4770 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4771 << i << (int)ArgSize.getQuantity() << 0xff
4772 << TheCall->getSourceRange();
4773 }
4774 TheCall->setArg(i, Arg.get());
4775 i++;
4776 }
4777
4778 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4779 // call to avoid duplicate diagnostics.
4780 if (!IsSizeCall) {
4781 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4782 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4783 bool Success = CheckFormatArguments(
4784 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4785 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4786 CheckedVarArgs);
4787 if (!Success)
4788 return true;
4789 }
4790
4791 if (IsSizeCall) {
4792 TheCall->setType(Context.getSizeType());
4793 } else {
4794 TheCall->setType(Context.VoidPtrTy);
4795 }
4796 return false;
4797}
4798
Eric Christopher8d0c6212010-04-17 02:26:23 +00004799/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4800/// TheCall is a constant expression.
4801bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4802 llvm::APSInt &Result) {
4803 Expr *Arg = TheCall->getArg(ArgNum);
4804 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4805 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4806
4807 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4808
4809 if (!Arg->isIntegerConstantExpr(Result, Context))
4810 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004811 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004812
Chris Lattnerd545ad12009-09-23 06:06:36 +00004813 return false;
4814}
4815
Richard Sandiford28940af2014-04-16 08:47:51 +00004816/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4817/// TheCall is a constant expression in the range [Low, High].
4818bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4819 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004820 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004821
4822 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004823 Expr *Arg = TheCall->getArg(ArgNum);
4824 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004825 return false;
4826
Eric Christopher8d0c6212010-04-17 02:26:23 +00004827 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004828 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004829 return true;
4830
Richard Sandiford28940af2014-04-16 08:47:51 +00004831 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004832 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004833 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004834
4835 return false;
4836}
4837
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004838/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4839/// TheCall is a constant expression is a multiple of Num..
4840bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4841 unsigned Num) {
4842 llvm::APSInt Result;
4843
4844 // We can't check the value of a dependent argument.
4845 Expr *Arg = TheCall->getArg(ArgNum);
4846 if (Arg->isTypeDependent() || Arg->isValueDependent())
4847 return false;
4848
4849 // Check constant-ness first.
4850 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4851 return true;
4852
4853 if (Result.getSExtValue() % Num != 0)
4854 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4855 << Num << Arg->getSourceRange();
4856
4857 return false;
4858}
4859
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004860/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4861/// TheCall is an ARM/AArch64 special register string literal.
4862bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4863 int ArgNum, unsigned ExpectedFieldNum,
4864 bool AllowName) {
4865 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4866 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4867 BuiltinID == ARM::BI__builtin_arm_rsr ||
4868 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4869 BuiltinID == ARM::BI__builtin_arm_wsr ||
4870 BuiltinID == ARM::BI__builtin_arm_wsrp;
4871 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4872 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4873 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4874 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4875 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4876 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4877 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4878
4879 // We can't check the value of a dependent argument.
4880 Expr *Arg = TheCall->getArg(ArgNum);
4881 if (Arg->isTypeDependent() || Arg->isValueDependent())
4882 return false;
4883
4884 // Check if the argument is a string literal.
4885 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4886 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4887 << Arg->getSourceRange();
4888
4889 // Check the type of special register given.
4890 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4891 SmallVector<StringRef, 6> Fields;
4892 Reg.split(Fields, ":");
4893
4894 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4895 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4896 << Arg->getSourceRange();
4897
4898 // If the string is the name of a register then we cannot check that it is
4899 // valid here but if the string is of one the forms described in ACLE then we
4900 // can check that the supplied fields are integers and within the valid
4901 // ranges.
4902 if (Fields.size() > 1) {
4903 bool FiveFields = Fields.size() == 5;
4904
4905 bool ValidString = true;
4906 if (IsARMBuiltin) {
4907 ValidString &= Fields[0].startswith_lower("cp") ||
4908 Fields[0].startswith_lower("p");
4909 if (ValidString)
4910 Fields[0] =
4911 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4912
4913 ValidString &= Fields[2].startswith_lower("c");
4914 if (ValidString)
4915 Fields[2] = Fields[2].drop_front(1);
4916
4917 if (FiveFields) {
4918 ValidString &= Fields[3].startswith_lower("c");
4919 if (ValidString)
4920 Fields[3] = Fields[3].drop_front(1);
4921 }
4922 }
4923
4924 SmallVector<int, 5> Ranges;
4925 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004926 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004927 else
4928 Ranges.append({15, 7, 15});
4929
4930 for (unsigned i=0; i<Fields.size(); ++i) {
4931 int IntField;
4932 ValidString &= !Fields[i].getAsInteger(10, IntField);
4933 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4934 }
4935
4936 if (!ValidString)
4937 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4938 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004939 } else if (IsAArch64Builtin && Fields.size() == 1) {
4940 // If the register name is one of those that appear in the condition below
4941 // and the special register builtin being used is one of the write builtins,
4942 // then we require that the argument provided for writing to the register
4943 // is an integer constant expression. This is because it will be lowered to
4944 // an MSR (immediate) instruction, so we need to know the immediate at
4945 // compile time.
4946 if (TheCall->getNumArgs() != 2)
4947 return false;
4948
4949 std::string RegLower = Reg.lower();
4950 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4951 RegLower != "pan" && RegLower != "uao")
4952 return false;
4953
4954 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4955 }
4956
4957 return false;
4958}
4959
Eli Friedmanc97d0142009-05-03 06:04:26 +00004960/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004961/// This checks that the target supports __builtin_longjmp and
4962/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004963bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004964 if (!Context.getTargetInfo().hasSjLjLowering())
4965 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4966 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4967
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004968 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004969 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004970
Eric Christopher8d0c6212010-04-17 02:26:23 +00004971 // TODO: This is less than ideal. Overload this to take a value.
4972 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4973 return true;
4974
4975 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004976 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4977 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4978
4979 return false;
4980}
4981
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004982/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4983/// This checks that the target supports __builtin_setjmp.
4984bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4985 if (!Context.getTargetInfo().hasSjLjLowering())
4986 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4987 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4988 return false;
4989}
4990
Richard Smithd7293d72013-08-05 18:49:43 +00004991namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004992
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004993class UncoveredArgHandler {
4994 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004995
4996 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004997 SmallVector<const Expr *, 4> DiagnosticExprs;
4998
4999public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005000 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005001
5002 bool hasUncoveredArg() const {
5003 return (FirstUncoveredArg >= 0);
5004 }
5005
5006 unsigned getUncoveredArg() const {
5007 assert(hasUncoveredArg() && "no uncovered argument");
5008 return FirstUncoveredArg;
5009 }
5010
5011 void setAllCovered() {
5012 // A string has been found with all arguments covered, so clear out
5013 // the diagnostics.
5014 DiagnosticExprs.clear();
5015 FirstUncoveredArg = AllCovered;
5016 }
5017
5018 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
5019 assert(NewFirstUncoveredArg >= 0 && "Outside range");
5020
5021 // Don't update if a previous string covers all arguments.
5022 if (FirstUncoveredArg == AllCovered)
5023 return;
5024
5025 // UncoveredArgHandler tracks the highest uncovered argument index
5026 // and with it all the strings that match this index.
5027 if (NewFirstUncoveredArg == FirstUncoveredArg)
5028 DiagnosticExprs.push_back(StrExpr);
5029 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
5030 DiagnosticExprs.clear();
5031 DiagnosticExprs.push_back(StrExpr);
5032 FirstUncoveredArg = NewFirstUncoveredArg;
5033 }
5034 }
5035
5036 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
5037};
5038
Richard Smithd7293d72013-08-05 18:49:43 +00005039enum StringLiteralCheckType {
5040 SLCT_NotALiteral,
5041 SLCT_UncheckedLiteral,
5042 SLCT_CheckedLiteral
5043};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005044
5045} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00005046
Stephen Hines648c3692016-09-16 01:07:04 +00005047static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
5048 BinaryOperatorKind BinOpKind,
5049 bool AddendIsRight) {
5050 unsigned BitWidth = Offset.getBitWidth();
5051 unsigned AddendBitWidth = Addend.getBitWidth();
5052 // There might be negative interim results.
5053 if (Addend.isUnsigned()) {
5054 Addend = Addend.zext(++AddendBitWidth);
5055 Addend.setIsSigned(true);
5056 }
5057 // Adjust the bit width of the APSInts.
5058 if (AddendBitWidth > BitWidth) {
5059 Offset = Offset.sext(AddendBitWidth);
5060 BitWidth = AddendBitWidth;
5061 } else if (BitWidth > AddendBitWidth) {
5062 Addend = Addend.sext(BitWidth);
5063 }
5064
5065 bool Ov = false;
5066 llvm::APSInt ResOffset = Offset;
5067 if (BinOpKind == BO_Add)
5068 ResOffset = Offset.sadd_ov(Addend, Ov);
5069 else {
5070 assert(AddendIsRight && BinOpKind == BO_Sub &&
5071 "operator must be add or sub with addend on the right");
5072 ResOffset = Offset.ssub_ov(Addend, Ov);
5073 }
5074
5075 // We add an offset to a pointer here so we should support an offset as big as
5076 // possible.
5077 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005078 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
5079 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00005080 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00005081 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
5082 return;
5083 }
5084
5085 Offset = ResOffset;
5086}
5087
5088namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005089
Stephen Hines648c3692016-09-16 01:07:04 +00005090// This is a wrapper class around StringLiteral to support offsetted string
5091// literals as format strings. It takes the offset into account when returning
5092// the string and its length or the source locations to display notes correctly.
5093class FormatStringLiteral {
5094 const StringLiteral *FExpr;
5095 int64_t Offset;
5096
5097 public:
5098 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
5099 : FExpr(fexpr), Offset(Offset) {}
5100
5101 StringRef getString() const {
5102 return FExpr->getString().drop_front(Offset);
5103 }
5104
5105 unsigned getByteLength() const {
5106 return FExpr->getByteLength() - getCharByteWidth() * Offset;
5107 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005108
Stephen Hines648c3692016-09-16 01:07:04 +00005109 unsigned getLength() const { return FExpr->getLength() - Offset; }
5110 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
5111
5112 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
5113
5114 QualType getType() const { return FExpr->getType(); }
5115
5116 bool isAscii() const { return FExpr->isAscii(); }
5117 bool isWide() const { return FExpr->isWide(); }
5118 bool isUTF8() const { return FExpr->isUTF8(); }
5119 bool isUTF16() const { return FExpr->isUTF16(); }
5120 bool isUTF32() const { return FExpr->isUTF32(); }
5121 bool isPascal() const { return FExpr->isPascal(); }
5122
5123 SourceLocation getLocationOfByte(
5124 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
5125 const TargetInfo &Target, unsigned *StartToken = nullptr,
5126 unsigned *StartTokenByteOffset = nullptr) const {
5127 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
5128 StartToken, StartTokenByteOffset);
5129 }
5130
5131 SourceLocation getLocStart() const LLVM_READONLY {
5132 return FExpr->getLocStart().getLocWithOffset(Offset);
5133 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005134
Stephen Hines648c3692016-09-16 01:07:04 +00005135 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
5136};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005137
5138} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00005139
5140static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005141 const Expr *OrigFormatExpr,
5142 ArrayRef<const Expr *> Args,
5143 bool HasVAListArg, unsigned format_idx,
5144 unsigned firstDataArg,
5145 Sema::FormatStringType Type,
5146 bool inFunctionCall,
5147 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005148 llvm::SmallBitVector &CheckedVarArgs,
5149 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005150
Richard Smith55ce3522012-06-25 20:30:08 +00005151// Determine if an expression is a string literal or constant string.
5152// If this function returns false on the arguments to a function expecting a
5153// format string, we will usually need to emit a warning.
5154// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00005155static StringLiteralCheckType
5156checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
5157 bool HasVAListArg, unsigned format_idx,
5158 unsigned firstDataArg, Sema::FormatStringType Type,
5159 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005160 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005161 UncoveredArgHandler &UncoveredArg,
5162 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00005163 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00005164 assert(Offset.isSigned() && "invalid offset");
5165
Douglas Gregorc25f7662009-05-19 22:10:17 +00005166 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00005167 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005168
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005169 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00005170
Richard Smithd7293d72013-08-05 18:49:43 +00005171 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00005172 // Technically -Wformat-nonliteral does not warn about this case.
5173 // The behavior of printf and friends in this case is implementation
5174 // dependent. Ideally if the format string cannot be null then
5175 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00005176 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00005177
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005178 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00005179 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005180 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00005181 // The expression is a literal if both sub-expressions were, and it was
5182 // completely checked only if both sub-expressions were checked.
5183 const AbstractConditionalOperator *C =
5184 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005185
5186 // Determine whether it is necessary to check both sub-expressions, for
5187 // example, because the condition expression is a constant that can be
5188 // evaluated at compile time.
5189 bool CheckLeft = true, CheckRight = true;
5190
5191 bool Cond;
5192 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
5193 if (Cond)
5194 CheckRight = false;
5195 else
5196 CheckLeft = false;
5197 }
5198
Stephen Hines648c3692016-09-16 01:07:04 +00005199 // We need to maintain the offsets for the right and the left hand side
5200 // separately to check if every possible indexed expression is a valid
5201 // string literal. They might have different offsets for different string
5202 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005203 StringLiteralCheckType Left;
5204 if (!CheckLeft)
5205 Left = SLCT_UncheckedLiteral;
5206 else {
5207 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
5208 HasVAListArg, format_idx, firstDataArg,
5209 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005210 CheckedVarArgs, UncoveredArg, Offset);
5211 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005212 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00005213 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005214 }
5215
Richard Smith55ce3522012-06-25 20:30:08 +00005216 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00005217 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005218 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005219 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005220 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005221
5222 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005223 }
5224
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005225 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00005226 E = cast<ImplicitCastExpr>(E)->getSubExpr();
5227 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005228
John McCallc07a0c72011-02-17 10:25:35 +00005229 case Stmt::OpaqueValueExprClass:
5230 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
5231 E = src;
5232 goto tryAgain;
5233 }
Richard Smith55ce3522012-06-25 20:30:08 +00005234 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00005235
Ted Kremeneka8890832011-02-24 23:03:04 +00005236 case Stmt::PredefinedExprClass:
5237 // While __func__, etc., are technically not string literals, they
5238 // cannot contain format specifiers and thus are not a security
5239 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00005240 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00005241
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005242 case Stmt::DeclRefExprClass: {
5243 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005244
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005245 // As an exception, do not flag errors for variables binding to
5246 // const string literals.
5247 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5248 bool isConstant = false;
5249 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005250
Richard Smithd7293d72013-08-05 18:49:43 +00005251 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5252 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005253 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005254 isConstant = T.isConstant(S.Context) &&
5255 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005256 } else if (T->isObjCObjectPointerType()) {
5257 // In ObjC, there is usually no "const ObjectPointer" type,
5258 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005259 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005260 }
Mike Stump11289f42009-09-09 15:08:12 +00005261
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005262 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005263 if (const Expr *Init = VD->getAnyInitializer()) {
5264 // Look through initializers like const char c[] = { "foo" }
5265 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5266 if (InitList->isStringLiteralInit())
5267 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5268 }
Richard Smithd7293d72013-08-05 18:49:43 +00005269 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005270 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005271 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005272 /*InFunctionCall*/ false, CheckedVarArgs,
5273 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005274 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005275 }
Mike Stump11289f42009-09-09 15:08:12 +00005276
Anders Carlssonb012ca92009-06-28 19:55:58 +00005277 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5278 // special check to see if the format string is a function parameter
5279 // of the function calling the printf function. If the function
5280 // has an attribute indicating it is a printf-like function, then we
5281 // should suppress warnings concerning non-literals being used in a call
5282 // to a vprintf function. For example:
5283 //
5284 // void
5285 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5286 // va_list ap;
5287 // va_start(ap, fmt);
5288 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5289 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005290 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005291 if (HasVAListArg) {
5292 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5293 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5294 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005295 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005296 // adjust for implicit parameter
5297 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5298 if (MD->isInstance())
5299 ++PVIndex;
5300 // We also check if the formats are compatible.
5301 // We can't pass a 'scanf' string to a 'printf' function.
5302 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005303 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005304 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005305 }
5306 }
5307 }
5308 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005309 }
Mike Stump11289f42009-09-09 15:08:12 +00005310
Richard Smith55ce3522012-06-25 20:30:08 +00005311 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005312 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005313
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005314 case Stmt::CallExprClass:
5315 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005316 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005317 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5318 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005319 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005320 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005321 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005322 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005323 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005324 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5325 unsigned BuiltinID = FD->getBuiltinID();
5326 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5327 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5328 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005329 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005330 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005331 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005332 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005333 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005334 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005335 }
5336 }
Mike Stump11289f42009-09-09 15:08:12 +00005337
Richard Smith55ce3522012-06-25 20:30:08 +00005338 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005339 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005340 case Stmt::ObjCMessageExprClass: {
5341 const auto *ME = cast<ObjCMessageExpr>(E);
5342 if (const auto *ND = ME->getMethodDecl()) {
5343 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005344 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005345 return checkFormatStringExpr(
5346 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5347 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5348 }
5349 }
5350
5351 return SLCT_NotALiteral;
5352 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005353 case Stmt::ObjCStringLiteralClass:
5354 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005355 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005356
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005357 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005358 StrE = ObjCFExpr->getString();
5359 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005360 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005361
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005362 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005363 if (Offset.isNegative() || Offset > StrE->getLength()) {
5364 // TODO: It would be better to have an explicit warning for out of
5365 // bounds literals.
5366 return SLCT_NotALiteral;
5367 }
5368 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5369 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005370 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005371 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005372 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005373 }
Mike Stump11289f42009-09-09 15:08:12 +00005374
Richard Smith55ce3522012-06-25 20:30:08 +00005375 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005376 }
Stephen Hines648c3692016-09-16 01:07:04 +00005377 case Stmt::BinaryOperatorClass: {
5378 llvm::APSInt LResult;
5379 llvm::APSInt RResult;
5380
5381 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5382
5383 // A string literal + an int offset is still a string literal.
5384 if (BinOp->isAdditiveOp()) {
5385 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5386 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5387
5388 if (LIsInt != RIsInt) {
5389 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5390
5391 if (LIsInt) {
5392 if (BinOpKind == BO_Add) {
5393 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5394 E = BinOp->getRHS();
5395 goto tryAgain;
5396 }
5397 } else {
5398 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5399 E = BinOp->getLHS();
5400 goto tryAgain;
5401 }
5402 }
Stephen Hines648c3692016-09-16 01:07:04 +00005403 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005404
5405 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005406 }
5407 case Stmt::UnaryOperatorClass: {
5408 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5409 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005410 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005411 llvm::APSInt IndexResult;
5412 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5413 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5414 E = ASE->getBase();
5415 goto tryAgain;
5416 }
5417 }
5418
5419 return SLCT_NotALiteral;
5420 }
Mike Stump11289f42009-09-09 15:08:12 +00005421
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005422 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005423 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005424 }
5425}
5426
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005427Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005428 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005429 .Case("scanf", FST_Scanf)
5430 .Cases("printf", "printf0", FST_Printf)
5431 .Cases("NSString", "CFString", FST_NSString)
5432 .Case("strftime", FST_Strftime)
5433 .Case("strfmon", FST_Strfmon)
5434 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5435 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5436 .Case("os_trace", FST_OSLog)
5437 .Case("os_log", FST_OSLog)
5438 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005439}
5440
Jordan Rose3e0ec582012-07-19 18:10:23 +00005441/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005442/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005443/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005444bool Sema::CheckFormatArguments(const FormatAttr *Format,
5445 ArrayRef<const Expr *> Args,
5446 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005447 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005448 SourceLocation Loc, SourceRange Range,
5449 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005450 FormatStringInfo FSI;
5451 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005452 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005453 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005454 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005455 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005456}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005457
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005458bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005459 bool HasVAListArg, unsigned format_idx,
5460 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005461 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005462 SourceLocation Loc, SourceRange Range,
5463 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005464 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005465 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005466 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005467 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005468 }
Mike Stump11289f42009-09-09 15:08:12 +00005469
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005470 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005471
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005472 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005473 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005474 // Dynamically generated format strings are difficult to
5475 // automatically vet at compile time. Requiring that format strings
5476 // are string literals: (1) permits the checking of format strings by
5477 // the compiler and thereby (2) can practically remove the source of
5478 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005479
Mike Stump11289f42009-09-09 15:08:12 +00005480 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005481 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005482 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005483 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005484 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005485 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005486 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5487 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005488 /*IsFunctionCall*/ true, CheckedVarArgs,
5489 UncoveredArg,
5490 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005491
5492 // Generate a diagnostic where an uncovered argument is detected.
5493 if (UncoveredArg.hasUncoveredArg()) {
5494 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5495 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5496 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5497 }
5498
Richard Smith55ce3522012-06-25 20:30:08 +00005499 if (CT != SLCT_NotALiteral)
5500 // Literal format string found, check done!
5501 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005502
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005503 // Strftime is particular as it always uses a single 'time' argument,
5504 // so it is safe to pass a non-literal string.
5505 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005506 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005507
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005508 // Do not emit diag when the string param is a macro expansion and the
5509 // format is either NSString or CFString. This is a hack to prevent
5510 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5511 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005512 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5513 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005514 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005515
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005516 // If there are no arguments specified, warn with -Wformat-security, otherwise
5517 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005518 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005519 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5520 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005521 switch (Type) {
5522 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005523 break;
5524 case FST_Kprintf:
5525 case FST_FreeBSDKPrintf:
5526 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005527 Diag(FormatLoc, diag::note_format_security_fixit)
5528 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005529 break;
5530 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005531 Diag(FormatLoc, diag::note_format_security_fixit)
5532 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005533 break;
5534 }
5535 } else {
5536 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005537 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005538 }
Richard Smith55ce3522012-06-25 20:30:08 +00005539 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005540}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005541
Ted Kremenekab278de2010-01-28 23:39:18 +00005542namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005543
Ted Kremenek02087932010-07-16 02:11:22 +00005544class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5545protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005546 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005547 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005548 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005549 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005550 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005551 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005552 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005553 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005554 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005555 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005556 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005557 bool usesPositionalArgs = false;
5558 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005559 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005560 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005561 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005562 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005563
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005564public:
Stephen Hines648c3692016-09-16 01:07:04 +00005565 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005566 const Expr *origFormatExpr,
5567 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005568 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005569 ArrayRef<const Expr *> Args, unsigned formatIdx,
5570 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005571 llvm::SmallBitVector &CheckedVarArgs,
5572 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005573 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5574 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5575 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005576 inFunctionCall(inFunctionCall), CallType(callType),
5577 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005578 CoveredArgs.resize(numDataArgs);
5579 CoveredArgs.reset();
5580 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005581
Ted Kremenek019d2242010-01-29 01:50:07 +00005582 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005583
Ted Kremenek02087932010-07-16 02:11:22 +00005584 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005585 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005586
Jordan Rose92303592012-09-08 04:00:03 +00005587 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005588 const analyze_format_string::FormatSpecifier &FS,
5589 const analyze_format_string::ConversionSpecifier &CS,
5590 const char *startSpecifier, unsigned specifierLen,
5591 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005592
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005593 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005594 const analyze_format_string::FormatSpecifier &FS,
5595 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005596
5597 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005598 const analyze_format_string::ConversionSpecifier &CS,
5599 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005600
Craig Toppere14c0f82014-03-12 04:55:44 +00005601 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005602
Craig Toppere14c0f82014-03-12 04:55:44 +00005603 void HandleInvalidPosition(const char *startSpecifier,
5604 unsigned specifierLen,
5605 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005606
Craig Toppere14c0f82014-03-12 04:55:44 +00005607 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005608
Craig Toppere14c0f82014-03-12 04:55:44 +00005609 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005610
Richard Trieu03cf7b72011-10-28 00:41:25 +00005611 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005612 static void
5613 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5614 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5615 bool IsStringLocation, Range StringRange,
5616 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005617
Ted Kremenek02087932010-07-16 02:11:22 +00005618protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005619 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5620 const char *startSpec,
5621 unsigned specifierLen,
5622 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005623
5624 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5625 const char *startSpec,
5626 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005627
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005628 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005629 CharSourceRange getSpecifierRange(const char *startSpecifier,
5630 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005631 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005632
Ted Kremenek5739de72010-01-29 01:06:55 +00005633 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005634
5635 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5636 const analyze_format_string::ConversionSpecifier &CS,
5637 const char *startSpecifier, unsigned specifierLen,
5638 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005639
5640 template <typename Range>
5641 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5642 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005643 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005644};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005645
5646} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005647
Ted Kremenek02087932010-07-16 02:11:22 +00005648SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005649 return OrigFormatExpr->getSourceRange();
5650}
5651
Ted Kremenek02087932010-07-16 02:11:22 +00005652CharSourceRange CheckFormatHandler::
5653getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005654 SourceLocation Start = getLocationOfByte(startSpecifier);
5655 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5656
5657 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005658 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005659
5660 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005661}
5662
Ted Kremenek02087932010-07-16 02:11:22 +00005663SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005664 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5665 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005666}
5667
Ted Kremenek02087932010-07-16 02:11:22 +00005668void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5669 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005670 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5671 getLocationOfByte(startSpecifier),
5672 /*IsStringLocation*/true,
5673 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005674}
5675
Jordan Rose92303592012-09-08 04:00:03 +00005676void CheckFormatHandler::HandleInvalidLengthModifier(
5677 const analyze_format_string::FormatSpecifier &FS,
5678 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005679 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005680 using namespace analyze_format_string;
5681
5682 const LengthModifier &LM = FS.getLengthModifier();
5683 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5684
5685 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005686 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005687 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005688 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005689 getLocationOfByte(LM.getStart()),
5690 /*IsStringLocation*/true,
5691 getSpecifierRange(startSpecifier, specifierLen));
5692
5693 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5694 << FixedLM->toString()
5695 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5696
5697 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005698 FixItHint Hint;
5699 if (DiagID == diag::warn_format_nonsensical_length)
5700 Hint = FixItHint::CreateRemoval(LMRange);
5701
5702 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005703 getLocationOfByte(LM.getStart()),
5704 /*IsStringLocation*/true,
5705 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005706 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005707 }
5708}
5709
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005710void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005711 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005712 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005713 using namespace analyze_format_string;
5714
5715 const LengthModifier &LM = FS.getLengthModifier();
5716 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5717
5718 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005719 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005720 if (FixedLM) {
5721 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5722 << LM.toString() << 0,
5723 getLocationOfByte(LM.getStart()),
5724 /*IsStringLocation*/true,
5725 getSpecifierRange(startSpecifier, specifierLen));
5726
5727 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5728 << FixedLM->toString()
5729 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5730
5731 } else {
5732 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5733 << LM.toString() << 0,
5734 getLocationOfByte(LM.getStart()),
5735 /*IsStringLocation*/true,
5736 getSpecifierRange(startSpecifier, specifierLen));
5737 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005738}
5739
5740void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5741 const analyze_format_string::ConversionSpecifier &CS,
5742 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005743 using namespace analyze_format_string;
5744
5745 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005746 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005747 if (FixedCS) {
5748 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5749 << CS.toString() << /*conversion specifier*/1,
5750 getLocationOfByte(CS.getStart()),
5751 /*IsStringLocation*/true,
5752 getSpecifierRange(startSpecifier, specifierLen));
5753
5754 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5755 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5756 << FixedCS->toString()
5757 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5758 } else {
5759 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5760 << CS.toString() << /*conversion specifier*/1,
5761 getLocationOfByte(CS.getStart()),
5762 /*IsStringLocation*/true,
5763 getSpecifierRange(startSpecifier, specifierLen));
5764 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005765}
5766
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005767void CheckFormatHandler::HandlePosition(const char *startPos,
5768 unsigned posLen) {
5769 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5770 getLocationOfByte(startPos),
5771 /*IsStringLocation*/true,
5772 getSpecifierRange(startPos, posLen));
5773}
5774
Ted Kremenekd1668192010-02-27 01:41:03 +00005775void
Ted Kremenek02087932010-07-16 02:11:22 +00005776CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5777 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005778 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5779 << (unsigned) p,
5780 getLocationOfByte(startPos), /*IsStringLocation*/true,
5781 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005782}
5783
Ted Kremenek02087932010-07-16 02:11:22 +00005784void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005785 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005786 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5787 getLocationOfByte(startPos),
5788 /*IsStringLocation*/true,
5789 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005790}
5791
Ted Kremenek02087932010-07-16 02:11:22 +00005792void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005793 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005794 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005795 EmitFormatDiagnostic(
5796 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5797 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5798 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005799 }
Ted Kremenek02087932010-07-16 02:11:22 +00005800}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005801
Jordan Rose58bbe422012-07-19 18:10:08 +00005802// Note that this may return NULL if there was an error parsing or building
5803// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005804const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005805 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005806}
5807
5808void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005809 // Does the number of data arguments exceed the number of
5810 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005811 if (!HasVAListArg) {
5812 // Find any arguments that weren't covered.
5813 CoveredArgs.flip();
5814 signed notCoveredArg = CoveredArgs.find_first();
5815 if (notCoveredArg >= 0) {
5816 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005817 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5818 } else {
5819 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005820 }
5821 }
5822}
5823
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005824void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5825 const Expr *ArgExpr) {
5826 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5827 "Invalid state");
5828
5829 if (!ArgExpr)
5830 return;
5831
5832 SourceLocation Loc = ArgExpr->getLocStart();
5833
5834 if (S.getSourceManager().isInSystemMacro(Loc))
5835 return;
5836
5837 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5838 for (auto E : DiagnosticExprs)
5839 PDiag << E->getSourceRange();
5840
5841 CheckFormatHandler::EmitFormatDiagnostic(
5842 S, IsFunctionCall, DiagnosticExprs[0],
5843 PDiag, Loc, /*IsStringLocation*/false,
5844 DiagnosticExprs[0]->getSourceRange());
5845}
5846
Ted Kremenekce815422010-07-19 21:25:57 +00005847bool
5848CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5849 SourceLocation Loc,
5850 const char *startSpec,
5851 unsigned specifierLen,
5852 const char *csStart,
5853 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005854 bool keepGoing = true;
5855 if (argIndex < NumDataArgs) {
5856 // Consider the argument coverered, even though the specifier doesn't
5857 // make sense.
5858 CoveredArgs.set(argIndex);
5859 }
5860 else {
5861 // If argIndex exceeds the number of data arguments we
5862 // don't issue a warning because that is just a cascade of warnings (and
5863 // they may have intended '%%' anyway). We don't want to continue processing
5864 // the format string after this point, however, as we will like just get
5865 // gibberish when trying to match arguments.
5866 keepGoing = false;
5867 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005868
5869 StringRef Specifier(csStart, csLen);
5870
5871 // If the specifier in non-printable, it could be the first byte of a UTF-8
5872 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5873 // hex value.
5874 std::string CodePointStr;
5875 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005876 llvm::UTF32 CodePoint;
5877 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5878 const llvm::UTF8 *E =
5879 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5880 llvm::ConversionResult Result =
5881 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005882
Justin Lebar90910552016-09-30 00:38:45 +00005883 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005884 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005885 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005886 }
5887
5888 llvm::raw_string_ostream OS(CodePointStr);
5889 if (CodePoint < 256)
5890 OS << "\\x" << llvm::format("%02x", CodePoint);
5891 else if (CodePoint <= 0xFFFF)
5892 OS << "\\u" << llvm::format("%04x", CodePoint);
5893 else
5894 OS << "\\U" << llvm::format("%08x", CodePoint);
5895 OS.flush();
5896 Specifier = CodePointStr;
5897 }
5898
5899 EmitFormatDiagnostic(
5900 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5901 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5902
Ted Kremenekce815422010-07-19 21:25:57 +00005903 return keepGoing;
5904}
5905
Richard Trieu03cf7b72011-10-28 00:41:25 +00005906void
5907CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5908 const char *startSpec,
5909 unsigned specifierLen) {
5910 EmitFormatDiagnostic(
5911 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5912 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5913}
5914
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005915bool
5916CheckFormatHandler::CheckNumArgs(
5917 const analyze_format_string::FormatSpecifier &FS,
5918 const analyze_format_string::ConversionSpecifier &CS,
5919 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5920
5921 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005922 PartialDiagnostic PDiag = FS.usesPositionalArg()
5923 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5924 << (argIndex+1) << NumDataArgs)
5925 : S.PDiag(diag::warn_printf_insufficient_data_args);
5926 EmitFormatDiagnostic(
5927 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5928 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005929
5930 // Since more arguments than conversion tokens are given, by extension
5931 // all arguments are covered, so mark this as so.
5932 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005933 return false;
5934 }
5935 return true;
5936}
5937
Richard Trieu03cf7b72011-10-28 00:41:25 +00005938template<typename Range>
5939void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5940 SourceLocation Loc,
5941 bool IsStringLocation,
5942 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005943 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005944 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005945 Loc, IsStringLocation, StringRange, FixIt);
5946}
5947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005948/// If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00005949/// so that the function call and string are in diagnostic messages.
5950///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005951/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005952/// call and only one diagnostic message will be produced. Otherwise, an
5953/// extra note will be emitted pointing to location of the format string.
5954///
5955/// \param ArgumentExpr the expression that is passed as the format string
5956/// argument in the function call. Used for getting locations when two
5957/// diagnostics are emitted.
5958///
5959/// \param PDiag the callee should already have provided any strings for the
5960/// diagnostic message. This function only adds locations and fixits
5961/// to diagnostics.
5962///
5963/// \param Loc primary location for diagnostic. If two diagnostics are
5964/// required, one will be at Loc and a new SourceLocation will be created for
5965/// the other one.
5966///
5967/// \param IsStringLocation if true, Loc points to the format string should be
5968/// used for the note. Otherwise, Loc points to the argument list and will
5969/// be used with PDiag.
5970///
5971/// \param StringRange some or all of the string to highlight. This is
5972/// templated so it can accept either a CharSourceRange or a SourceRange.
5973///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005974/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005975template <typename Range>
5976void CheckFormatHandler::EmitFormatDiagnostic(
5977 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5978 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5979 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005980 if (InFunctionCall) {
5981 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5982 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005983 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005984 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005985 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5986 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005987
5988 const Sema::SemaDiagnosticBuilder &Note =
5989 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5990 diag::note_format_string_defined);
5991
5992 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005993 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005994 }
5995}
5996
Ted Kremenek02087932010-07-16 02:11:22 +00005997//===--- CHECK: Printf format string checking ------------------------------===//
5998
5999namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006000
Ted Kremenek02087932010-07-16 02:11:22 +00006001class CheckPrintfHandler : public CheckFormatHandler {
6002public:
Stephen Hines648c3692016-09-16 01:07:04 +00006003 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006004 const Expr *origFormatExpr,
6005 const Sema::FormatStringType type, unsigned firstDataArg,
6006 unsigned numDataArgs, bool isObjC, const char *beg,
6007 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00006008 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00006009 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006010 llvm::SmallBitVector &CheckedVarArgs,
6011 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006012 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6013 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6014 inFunctionCall, CallType, CheckedVarArgs,
6015 UncoveredArg) {}
6016
6017 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
6018
6019 /// Returns true if '%@' specifiers are allowed in the format string.
6020 bool allowsObjCArg() const {
6021 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
6022 FSType == Sema::FST_OSTrace;
6023 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00006024
Ted Kremenek02087932010-07-16 02:11:22 +00006025 bool HandleInvalidPrintfConversionSpecifier(
6026 const analyze_printf::PrintfSpecifier &FS,
6027 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006028 unsigned specifierLen) override;
6029
Ted Kremenek02087932010-07-16 02:11:22 +00006030 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
6031 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006032 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006033 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6034 const char *StartSpecifier,
6035 unsigned SpecifierLen,
6036 const Expr *E);
6037
Ted Kremenek02087932010-07-16 02:11:22 +00006038 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
6039 const char *startSpecifier, unsigned specifierLen);
6040 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
6041 const analyze_printf::OptionalAmount &Amt,
6042 unsigned type,
6043 const char *startSpecifier, unsigned specifierLen);
6044 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
6045 const analyze_printf::OptionalFlag &flag,
6046 const char *startSpecifier, unsigned specifierLen);
6047 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
6048 const analyze_printf::OptionalFlag &ignoredFlag,
6049 const analyze_printf::OptionalFlag &flag,
6050 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006051 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00006052 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00006053
6054 void HandleEmptyObjCModifierFlag(const char *startFlag,
6055 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00006056
Ted Kremenek2b417712015-07-02 05:39:16 +00006057 void HandleInvalidObjCModifierFlag(const char *startFlag,
6058 unsigned flagLen) override;
6059
6060 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
6061 const char *flagsEnd,
6062 const char *conversionPosition)
6063 override;
6064};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006065
6066} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00006067
6068bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
6069 const analyze_printf::PrintfSpecifier &FS,
6070 const char *startSpecifier,
6071 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006072 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006073 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006074
Ted Kremenekce815422010-07-19 21:25:57 +00006075 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6076 getLocationOfByte(CS.getStart()),
6077 startSpecifier, specifierLen,
6078 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00006079}
6080
Ted Kremenek02087932010-07-16 02:11:22 +00006081bool CheckPrintfHandler::HandleAmount(
6082 const analyze_format_string::OptionalAmount &Amt,
6083 unsigned k, const char *startSpecifier,
6084 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006085 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006086 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00006087 unsigned argIndex = Amt.getArgIndex();
6088 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006089 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
6090 << k,
6091 getLocationOfByte(Amt.getStart()),
6092 /*IsStringLocation*/true,
6093 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006094 // Don't do any more checking. We will just emit
6095 // spurious errors.
6096 return false;
6097 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006098
Ted Kremenek5739de72010-01-29 01:06:55 +00006099 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00006100 // Although not in conformance with C99, we also allow the argument to be
6101 // an 'unsigned int' as that is a reasonably safe case. GCC also
6102 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00006103 CoveredArgs.set(argIndex);
6104 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006105 if (!Arg)
6106 return false;
6107
Ted Kremenek5739de72010-01-29 01:06:55 +00006108 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006109
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006110 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
6111 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006112
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006113 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006114 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006115 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00006116 << T << Arg->getSourceRange(),
6117 getLocationOfByte(Amt.getStart()),
6118 /*IsStringLocation*/true,
6119 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00006120 // Don't do any more checking. We will just emit
6121 // spurious errors.
6122 return false;
6123 }
6124 }
6125 }
6126 return true;
6127}
Ted Kremenek5739de72010-01-29 01:06:55 +00006128
Tom Careb49ec692010-06-17 19:00:27 +00006129void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00006130 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006131 const analyze_printf::OptionalAmount &Amt,
6132 unsigned type,
6133 const char *startSpecifier,
6134 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006135 const analyze_printf::PrintfConversionSpecifier &CS =
6136 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00006137
Richard Trieu03cf7b72011-10-28 00:41:25 +00006138 FixItHint fixit =
6139 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
6140 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
6141 Amt.getConstantLength()))
6142 : FixItHint();
6143
6144 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
6145 << type << CS.toString(),
6146 getLocationOfByte(Amt.getStart()),
6147 /*IsStringLocation*/true,
6148 getSpecifierRange(startSpecifier, specifierLen),
6149 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00006150}
6151
Ted Kremenek02087932010-07-16 02:11:22 +00006152void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006153 const analyze_printf::OptionalFlag &flag,
6154 const char *startSpecifier,
6155 unsigned specifierLen) {
6156 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006157 const analyze_printf::PrintfConversionSpecifier &CS =
6158 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00006159 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
6160 << flag.toString() << CS.toString(),
6161 getLocationOfByte(flag.getPosition()),
6162 /*IsStringLocation*/true,
6163 getSpecifierRange(startSpecifier, specifierLen),
6164 FixItHint::CreateRemoval(
6165 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006166}
6167
6168void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00006169 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00006170 const analyze_printf::OptionalFlag &ignoredFlag,
6171 const analyze_printf::OptionalFlag &flag,
6172 const char *startSpecifier,
6173 unsigned specifierLen) {
6174 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00006175 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
6176 << ignoredFlag.toString() << flag.toString(),
6177 getLocationOfByte(ignoredFlag.getPosition()),
6178 /*IsStringLocation*/true,
6179 getSpecifierRange(startSpecifier, specifierLen),
6180 FixItHint::CreateRemoval(
6181 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00006182}
6183
Ted Kremenek2b417712015-07-02 05:39:16 +00006184void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
6185 unsigned flagLen) {
6186 // Warn about an empty flag.
6187 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
6188 getLocationOfByte(startFlag),
6189 /*IsStringLocation*/true,
6190 getSpecifierRange(startFlag, flagLen));
6191}
6192
6193void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
6194 unsigned flagLen) {
6195 // Warn about an invalid flag.
6196 auto Range = getSpecifierRange(startFlag, flagLen);
6197 StringRef flag(startFlag, flagLen);
6198 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
6199 getLocationOfByte(startFlag),
6200 /*IsStringLocation*/true,
6201 Range, FixItHint::CreateRemoval(Range));
6202}
6203
6204void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
6205 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
6206 // Warn about using '[...]' without a '@' conversion.
6207 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
6208 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
6209 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
6210 getLocationOfByte(conversionPosition),
6211 /*IsStringLocation*/true,
6212 Range, FixItHint::CreateRemoval(Range));
6213}
6214
Richard Smith55ce3522012-06-25 20:30:08 +00006215// Determines if the specified is a C++ class or struct containing
6216// a member with the specified name and kind (e.g. a CXXMethodDecl named
6217// "c_str()").
6218template<typename MemberKind>
6219static llvm::SmallPtrSet<MemberKind*, 1>
6220CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
6221 const RecordType *RT = Ty->getAs<RecordType>();
6222 llvm::SmallPtrSet<MemberKind*, 1> Results;
6223
6224 if (!RT)
6225 return Results;
6226 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00006227 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00006228 return Results;
6229
Alp Tokerb6cc5922014-05-03 03:45:55 +00006230 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00006231 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00006232 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00006233
6234 // We just need to include all members of the right kind turned up by the
6235 // filter, at this point.
6236 if (S.LookupQualifiedName(R, RT->getDecl()))
6237 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6238 NamedDecl *decl = (*I)->getUnderlyingDecl();
6239 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
6240 Results.insert(FK);
6241 }
6242 return Results;
6243}
6244
Richard Smith2868a732014-02-28 01:36:39 +00006245/// Check if we could call '.c_str()' on an object.
6246///
6247/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6248/// allow the call, or if it would be ambiguous).
6249bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006250 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6251
Richard Smith2868a732014-02-28 01:36:39 +00006252 MethodSet Results =
6253 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6254 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6255 MI != ME; ++MI)
6256 if ((*MI)->getMinRequiredArguments() == 0)
6257 return true;
6258 return false;
6259}
6260
Richard Smith55ce3522012-06-25 20:30:08 +00006261// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006262// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006263// Returns true when a c_str() conversion method is found.
6264bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006265 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006266 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006267
6268 MethodSet Results =
6269 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6270
6271 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6272 MI != ME; ++MI) {
6273 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006274 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006275 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006276 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006277 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006278 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6279 << "c_str()"
6280 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6281 return true;
6282 }
6283 }
6284
6285 return false;
6286}
6287
Ted Kremenekab278de2010-01-28 23:39:18 +00006288bool
Ted Kremenek02087932010-07-16 02:11:22 +00006289CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006290 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006291 const char *startSpecifier,
6292 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006293 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006294 using namespace analyze_printf;
6295
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006296 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006297
Ted Kremenek6cd69422010-07-19 22:01:06 +00006298 if (FS.consumesDataArgument()) {
6299 if (atFirstArg) {
6300 atFirstArg = false;
6301 usesPositionalArgs = FS.usesPositionalArg();
6302 }
6303 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006304 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6305 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006306 return false;
6307 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006308 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006309
Ted Kremenekd1668192010-02-27 01:41:03 +00006310 // First check if the field width, precision, and conversion specifier
6311 // have matching data arguments.
6312 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6313 startSpecifier, specifierLen)) {
6314 return false;
6315 }
6316
6317 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6318 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006319 return false;
6320 }
6321
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006322 if (!CS.consumesDataArgument()) {
6323 // FIXME: Technically specifying a precision or field width here
6324 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006325 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006326 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006327
Ted Kremenek4a49d982010-02-26 19:18:41 +00006328 // Consume the argument.
6329 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006330 if (argIndex < NumDataArgs) {
6331 // The check to see if the argIndex is valid will come later.
6332 // We set the bit here because we may exit early from this
6333 // function if we encounter some other error.
6334 CoveredArgs.set(argIndex);
6335 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006336
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006337 // FreeBSD kernel extensions.
6338 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6339 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6340 // We need at least two arguments.
6341 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6342 return false;
6343
6344 // Claim the second argument.
6345 CoveredArgs.set(argIndex + 1);
6346
6347 // Type check the first argument (int for %b, pointer for %D)
6348 const Expr *Ex = getDataArg(argIndex);
6349 const analyze_printf::ArgType &AT =
6350 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6351 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6352 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6353 EmitFormatDiagnostic(
6354 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6355 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6356 << false << Ex->getSourceRange(),
6357 Ex->getLocStart(), /*IsStringLocation*/false,
6358 getSpecifierRange(startSpecifier, specifierLen));
6359
6360 // Type check the second argument (char * for both %b and %D)
6361 Ex = getDataArg(argIndex + 1);
6362 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6363 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6364 EmitFormatDiagnostic(
6365 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6366 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6367 << false << Ex->getSourceRange(),
6368 Ex->getLocStart(), /*IsStringLocation*/false,
6369 getSpecifierRange(startSpecifier, specifierLen));
6370
6371 return true;
6372 }
6373
Ted Kremenek4a49d982010-02-26 19:18:41 +00006374 // Check for using an Objective-C specific conversion specifier
6375 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006376 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006377 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6378 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006379 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006380
Mehdi Amini06d367c2016-10-24 20:39:34 +00006381 // %P can only be used with os_log.
6382 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6383 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6384 specifierLen);
6385 }
6386
6387 // %n is not allowed with os_log.
6388 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6389 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6390 getLocationOfByte(CS.getStart()),
6391 /*IsStringLocation*/ false,
6392 getSpecifierRange(startSpecifier, specifierLen));
6393
6394 return true;
6395 }
6396
6397 // Only scalars are allowed for os_trace.
6398 if (FSType == Sema::FST_OSTrace &&
6399 (CS.getKind() == ConversionSpecifier::PArg ||
6400 CS.getKind() == ConversionSpecifier::sArg ||
6401 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6402 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6403 specifierLen);
6404 }
6405
6406 // Check for use of public/private annotation outside of os_log().
6407 if (FSType != Sema::FST_OSLog) {
6408 if (FS.isPublic().isSet()) {
6409 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6410 << "public",
6411 getLocationOfByte(FS.isPublic().getPosition()),
6412 /*IsStringLocation*/ false,
6413 getSpecifierRange(startSpecifier, specifierLen));
6414 }
6415 if (FS.isPrivate().isSet()) {
6416 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6417 << "private",
6418 getLocationOfByte(FS.isPrivate().getPosition()),
6419 /*IsStringLocation*/ false,
6420 getSpecifierRange(startSpecifier, specifierLen));
6421 }
6422 }
6423
Tom Careb49ec692010-06-17 19:00:27 +00006424 // Check for invalid use of field width
6425 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006426 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006427 startSpecifier, specifierLen);
6428 }
6429
6430 // Check for invalid use of precision
6431 if (!FS.hasValidPrecision()) {
6432 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6433 startSpecifier, specifierLen);
6434 }
6435
Mehdi Amini06d367c2016-10-24 20:39:34 +00006436 // Precision is mandatory for %P specifier.
6437 if (CS.getKind() == ConversionSpecifier::PArg &&
6438 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6439 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6440 getLocationOfByte(startSpecifier),
6441 /*IsStringLocation*/ false,
6442 getSpecifierRange(startSpecifier, specifierLen));
6443 }
6444
Tom Careb49ec692010-06-17 19:00:27 +00006445 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006446 if (!FS.hasValidThousandsGroupingPrefix())
6447 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006448 if (!FS.hasValidLeadingZeros())
6449 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6450 if (!FS.hasValidPlusPrefix())
6451 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006452 if (!FS.hasValidSpacePrefix())
6453 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006454 if (!FS.hasValidAlternativeForm())
6455 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6456 if (!FS.hasValidLeftJustified())
6457 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6458
6459 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006460 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6461 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6462 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006463 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6464 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6465 startSpecifier, specifierLen);
6466
6467 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006468 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006469 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6470 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006471 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006472 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006473 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006474 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6475 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006476
Jordan Rose92303592012-09-08 04:00:03 +00006477 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6478 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6479
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006480 // The remaining checks depend on the data arguments.
6481 if (HasVAListArg)
6482 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006483
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006484 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006485 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006486
Jordan Rose58bbe422012-07-19 18:10:08 +00006487 const Expr *Arg = getDataArg(argIndex);
6488 if (!Arg)
6489 return true;
6490
6491 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006492}
6493
Jordan Roseaee34382012-09-05 22:56:26 +00006494static bool requiresParensToAddCast(const Expr *E) {
6495 // FIXME: We should have a general way to reason about operator
6496 // precedence and whether parens are actually needed here.
6497 // Take care of a few common cases where they aren't.
6498 const Expr *Inside = E->IgnoreImpCasts();
6499 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6500 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6501
6502 switch (Inside->getStmtClass()) {
6503 case Stmt::ArraySubscriptExprClass:
6504 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006505 case Stmt::CharacterLiteralClass:
6506 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006507 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006508 case Stmt::FloatingLiteralClass:
6509 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006510 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006511 case Stmt::ObjCArrayLiteralClass:
6512 case Stmt::ObjCBoolLiteralExprClass:
6513 case Stmt::ObjCBoxedExprClass:
6514 case Stmt::ObjCDictionaryLiteralClass:
6515 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006516 case Stmt::ObjCIvarRefExprClass:
6517 case Stmt::ObjCMessageExprClass:
6518 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006519 case Stmt::ObjCStringLiteralClass:
6520 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006521 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006522 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006523 case Stmt::UnaryOperatorClass:
6524 return false;
6525 default:
6526 return true;
6527 }
6528}
6529
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006530static std::pair<QualType, StringRef>
6531shouldNotPrintDirectly(const ASTContext &Context,
6532 QualType IntendedTy,
6533 const Expr *E) {
6534 // Use a 'while' to peel off layers of typedefs.
6535 QualType TyTy = IntendedTy;
6536 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6537 StringRef Name = UserTy->getDecl()->getName();
6538 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006539 .Case("CFIndex", Context.getNSIntegerType())
6540 .Case("NSInteger", Context.getNSIntegerType())
6541 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006542 .Case("SInt32", Context.IntTy)
6543 .Case("UInt32", Context.UnsignedIntTy)
6544 .Default(QualType());
6545
6546 if (!CastTy.isNull())
6547 return std::make_pair(CastTy, Name);
6548
6549 TyTy = UserTy->desugar();
6550 }
6551
6552 // Strip parens if necessary.
6553 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6554 return shouldNotPrintDirectly(Context,
6555 PE->getSubExpr()->getType(),
6556 PE->getSubExpr());
6557
6558 // If this is a conditional expression, then its result type is constructed
6559 // via usual arithmetic conversions and thus there might be no necessary
6560 // typedef sugar there. Recurse to operands to check for NSInteger &
6561 // Co. usage condition.
6562 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6563 QualType TrueTy, FalseTy;
6564 StringRef TrueName, FalseName;
6565
6566 std::tie(TrueTy, TrueName) =
6567 shouldNotPrintDirectly(Context,
6568 CO->getTrueExpr()->getType(),
6569 CO->getTrueExpr());
6570 std::tie(FalseTy, FalseName) =
6571 shouldNotPrintDirectly(Context,
6572 CO->getFalseExpr()->getType(),
6573 CO->getFalseExpr());
6574
6575 if (TrueTy == FalseTy)
6576 return std::make_pair(TrueTy, TrueName);
6577 else if (TrueTy.isNull())
6578 return std::make_pair(FalseTy, FalseName);
6579 else if (FalseTy.isNull())
6580 return std::make_pair(TrueTy, TrueName);
6581 }
6582
6583 return std::make_pair(QualType(), StringRef());
6584}
6585
Richard Smith55ce3522012-06-25 20:30:08 +00006586bool
6587CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6588 const char *StartSpecifier,
6589 unsigned SpecifierLen,
6590 const Expr *E) {
6591 using namespace analyze_format_string;
6592 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006593
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006594 // Now type check the data expression that matches the
6595 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006596 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006597 if (!AT.isValid())
6598 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006599
Jordan Rose598ec092012-12-05 18:44:40 +00006600 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006601 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6602 ExprTy = TET->getUnderlyingExpr()->getType();
6603 }
6604
Seth Cantrellb4802962015-03-04 03:12:10 +00006605 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6606
6607 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006608 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006609 }
Jordan Rose98709982012-06-04 22:48:57 +00006610
Jordan Rose22b74712012-09-05 22:56:19 +00006611 // Look through argument promotions for our error message's reported type.
6612 // This includes the integral and floating promotions, but excludes array
6613 // and function pointer decay; seeing that an argument intended to be a
6614 // string has type 'char [6]' is probably more confusing than 'char *'.
6615 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6616 if (ICE->getCastKind() == CK_IntegralCast ||
6617 ICE->getCastKind() == CK_FloatingCast) {
6618 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006619 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006620
6621 // Check if we didn't match because of an implicit cast from a 'char'
6622 // or 'short' to an 'int'. This is done because printf is a varargs
6623 // function.
6624 if (ICE->getType() == S.Context.IntTy ||
6625 ICE->getType() == S.Context.UnsignedIntTy) {
6626 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006627 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006628 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006629 }
Jordan Rose98709982012-06-04 22:48:57 +00006630 }
Jordan Rose598ec092012-12-05 18:44:40 +00006631 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6632 // Special case for 'a', which has type 'int' in C.
6633 // Note, however, that we do /not/ want to treat multibyte constants like
6634 // 'MooV' as characters! This form is deprecated but still exists.
6635 if (ExprTy == S.Context.IntTy)
6636 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6637 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006638 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006639
Jordan Rosebc53ed12014-05-31 04:12:14 +00006640 // Look through enums to their underlying type.
6641 bool IsEnum = false;
6642 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6643 ExprTy = EnumTy->getDecl()->getIntegerType();
6644 IsEnum = true;
6645 }
6646
Jordan Rose0e5badd2012-12-05 18:44:49 +00006647 // %C in an Objective-C context prints a unichar, not a wchar_t.
6648 // If the argument is an integer of some kind, believe the %C and suggest
6649 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006650 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006651 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006652 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6653 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6654 !ExprTy->isCharType()) {
6655 // 'unichar' is defined as a typedef of unsigned short, but we should
6656 // prefer using the typedef if it is visible.
6657 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006658
6659 // While we are here, check if the value is an IntegerLiteral that happens
6660 // to be within the valid range.
6661 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6662 const llvm::APInt &V = IL->getValue();
6663 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6664 return true;
6665 }
6666
Jordan Rose0e5badd2012-12-05 18:44:49 +00006667 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6668 Sema::LookupOrdinaryName);
6669 if (S.LookupName(Result, S.getCurScope())) {
6670 NamedDecl *ND = Result.getFoundDecl();
6671 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6672 if (TD->getUnderlyingType() == IntendedTy)
6673 IntendedTy = S.Context.getTypedefType(TD);
6674 }
6675 }
6676 }
6677
6678 // Special-case some of Darwin's platform-independence types by suggesting
6679 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006680 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006681 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006682 QualType CastTy;
6683 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6684 if (!CastTy.isNull()) {
6685 IntendedTy = CastTy;
6686 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006687 }
6688 }
6689
Jordan Rose22b74712012-09-05 22:56:19 +00006690 // We may be able to offer a FixItHint if it is a supported type.
6691 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006692 bool success =
6693 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006694
Jordan Rose22b74712012-09-05 22:56:19 +00006695 if (success) {
6696 // Get the fix string from the fixed format specifier
6697 SmallString<16> buf;
6698 llvm::raw_svector_ostream os(buf);
6699 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006700
Jordan Roseaee34382012-09-05 22:56:26 +00006701 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6702
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006703 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006704 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6705 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6706 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6707 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006708 // In this case, the specifier is wrong and should be changed to match
6709 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006710 EmitFormatDiagnostic(S.PDiag(diag)
6711 << AT.getRepresentativeTypeName(S.Context)
6712 << IntendedTy << IsEnum << E->getSourceRange(),
6713 E->getLocStart(),
6714 /*IsStringLocation*/ false, SpecRange,
6715 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006716 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006717 // The canonical type for formatting this value is different from the
6718 // actual type of the expression. (This occurs, for example, with Darwin's
6719 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6720 // should be printed as 'long' for 64-bit compatibility.)
6721 // Rather than emitting a normal format/argument mismatch, we want to
6722 // add a cast to the recommended type (and correct the format string
6723 // if necessary).
6724 SmallString<16> CastBuf;
6725 llvm::raw_svector_ostream CastFix(CastBuf);
6726 CastFix << "(";
6727 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6728 CastFix << ")";
6729
6730 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006731 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006732 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6733
6734 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6735 // If there's already a cast present, just replace it.
6736 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6737 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6738
6739 } else if (!requiresParensToAddCast(E)) {
6740 // If the expression has high enough precedence,
6741 // just write the C-style cast.
6742 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6743 CastFix.str()));
6744 } else {
6745 // Otherwise, add parens around the expression as well as the cast.
6746 CastFix << "(";
6747 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6748 CastFix.str()));
6749
Alp Tokerb6cc5922014-05-03 03:45:55 +00006750 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006751 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6752 }
6753
Jordan Rose0e5badd2012-12-05 18:44:49 +00006754 if (ShouldNotPrintDirectly) {
6755 // The expression has a type that should not be printed directly.
6756 // We extract the name from the typedef because we don't want to show
6757 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006758 StringRef Name;
6759 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6760 Name = TypedefTy->getDecl()->getName();
6761 else
6762 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006763 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006764 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006765 << E->getSourceRange(),
6766 E->getLocStart(), /*IsStringLocation=*/false,
6767 SpecRange, Hints);
6768 } else {
6769 // In this case, the expression could be printed using a different
6770 // specifier, but we've decided that the specifier is probably correct
6771 // and we should cast instead. Just use the normal warning message.
6772 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006773 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6774 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006775 << E->getSourceRange(),
6776 E->getLocStart(), /*IsStringLocation*/false,
6777 SpecRange, Hints);
6778 }
Jordan Roseaee34382012-09-05 22:56:26 +00006779 }
Jordan Rose22b74712012-09-05 22:56:19 +00006780 } else {
6781 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6782 SpecifierLen);
6783 // Since the warning for passing non-POD types to variadic functions
6784 // was deferred until now, we emit a warning for non-POD
6785 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006786 switch (S.isValidVarArgType(ExprTy)) {
6787 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006788 case Sema::VAK_ValidInCXX11: {
6789 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6790 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6791 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6792 }
Richard Smithd7293d72013-08-05 18:49:43 +00006793
Seth Cantrellb4802962015-03-04 03:12:10 +00006794 EmitFormatDiagnostic(
6795 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6796 << IsEnum << CSR << E->getSourceRange(),
6797 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6798 break;
6799 }
Richard Smithd7293d72013-08-05 18:49:43 +00006800 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006801 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006802 EmitFormatDiagnostic(
6803 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006804 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006805 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006806 << CallType
6807 << AT.getRepresentativeTypeName(S.Context)
6808 << CSR
6809 << E->getSourceRange(),
6810 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006811 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006812 break;
6813
6814 case Sema::VAK_Invalid:
6815 if (ExprTy->isObjCObjectType())
6816 EmitFormatDiagnostic(
6817 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6818 << S.getLangOpts().CPlusPlus11
6819 << ExprTy
6820 << CallType
6821 << AT.getRepresentativeTypeName(S.Context)
6822 << CSR
6823 << E->getSourceRange(),
6824 E->getLocStart(), /*IsStringLocation*/false, CSR);
6825 else
6826 // FIXME: If this is an initializer list, suggest removing the braces
6827 // or inserting a cast to the target type.
6828 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6829 << isa<InitListExpr>(E) << ExprTy << CallType
6830 << AT.getRepresentativeTypeName(S.Context)
6831 << E->getSourceRange();
6832 break;
6833 }
6834
6835 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6836 "format string specifier index out of range");
6837 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006838 }
6839
Ted Kremenekab278de2010-01-28 23:39:18 +00006840 return true;
6841}
6842
Ted Kremenek02087932010-07-16 02:11:22 +00006843//===--- CHECK: Scanf format string checking ------------------------------===//
6844
6845namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006846
Ted Kremenek02087932010-07-16 02:11:22 +00006847class CheckScanfHandler : public CheckFormatHandler {
6848public:
Stephen Hines648c3692016-09-16 01:07:04 +00006849 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006850 const Expr *origFormatExpr, Sema::FormatStringType type,
6851 unsigned firstDataArg, unsigned numDataArgs,
6852 const char *beg, bool hasVAListArg,
6853 ArrayRef<const Expr *> Args, unsigned formatIdx,
6854 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006855 llvm::SmallBitVector &CheckedVarArgs,
6856 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006857 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6858 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6859 inFunctionCall, CallType, CheckedVarArgs,
6860 UncoveredArg) {}
6861
Ted Kremenek02087932010-07-16 02:11:22 +00006862 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6863 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006864 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006865
6866 bool HandleInvalidScanfConversionSpecifier(
6867 const analyze_scanf::ScanfSpecifier &FS,
6868 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006869 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006870
Craig Toppere14c0f82014-03-12 04:55:44 +00006871 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006872};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006873
6874} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006875
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006876void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6877 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006878 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6879 getLocationOfByte(end), /*IsStringLocation*/true,
6880 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006881}
6882
Ted Kremenekce815422010-07-19 21:25:57 +00006883bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6884 const analyze_scanf::ScanfSpecifier &FS,
6885 const char *startSpecifier,
6886 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006887 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006888 FS.getConversionSpecifier();
6889
6890 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6891 getLocationOfByte(CS.getStart()),
6892 startSpecifier, specifierLen,
6893 CS.getStart(), CS.getLength());
6894}
6895
Ted Kremenek02087932010-07-16 02:11:22 +00006896bool CheckScanfHandler::HandleScanfSpecifier(
6897 const analyze_scanf::ScanfSpecifier &FS,
6898 const char *startSpecifier,
6899 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006900 using namespace analyze_scanf;
6901 using namespace analyze_format_string;
6902
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006903 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006904
Ted Kremenek6cd69422010-07-19 22:01:06 +00006905 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6906 // be used to decide if we are using positional arguments consistently.
6907 if (FS.consumesDataArgument()) {
6908 if (atFirstArg) {
6909 atFirstArg = false;
6910 usesPositionalArgs = FS.usesPositionalArg();
6911 }
6912 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006913 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6914 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006915 return false;
6916 }
Ted Kremenek02087932010-07-16 02:11:22 +00006917 }
6918
6919 // Check if the field with is non-zero.
6920 const OptionalAmount &Amt = FS.getFieldWidth();
6921 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6922 if (Amt.getConstantAmount() == 0) {
6923 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6924 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006925 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6926 getLocationOfByte(Amt.getStart()),
6927 /*IsStringLocation*/true, R,
6928 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006929 }
6930 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006931
Ted Kremenek02087932010-07-16 02:11:22 +00006932 if (!FS.consumesDataArgument()) {
6933 // FIXME: Technically specifying a precision or field width here
6934 // makes no sense. Worth issuing a warning at some point.
6935 return true;
6936 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006937
Ted Kremenek02087932010-07-16 02:11:22 +00006938 // Consume the argument.
6939 unsigned argIndex = FS.getArgIndex();
6940 if (argIndex < NumDataArgs) {
6941 // The check to see if the argIndex is valid will come later.
6942 // We set the bit here because we may exit early from this
6943 // function if we encounter some other error.
6944 CoveredArgs.set(argIndex);
6945 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006946
Ted Kremenek4407ea42010-07-20 20:04:47 +00006947 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006948 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006949 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6950 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006951 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006952 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006953 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006954 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6955 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006956
Jordan Rose92303592012-09-08 04:00:03 +00006957 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6958 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6959
Ted Kremenek02087932010-07-16 02:11:22 +00006960 // The remaining checks depend on the data arguments.
6961 if (HasVAListArg)
6962 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006963
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006964 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006965 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006966
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006967 // Check that the argument type matches the format specifier.
6968 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006969 if (!Ex)
6970 return true;
6971
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006972 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006973
6974 if (!AT.isValid()) {
6975 return true;
6976 }
6977
Seth Cantrellb4802962015-03-04 03:12:10 +00006978 analyze_format_string::ArgType::MatchKind match =
6979 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006980 if (match == analyze_format_string::ArgType::Match) {
6981 return true;
6982 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006983
Seth Cantrell79340072015-03-04 05:58:08 +00006984 ScanfSpecifier fixedFS = FS;
6985 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6986 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006987
Seth Cantrell79340072015-03-04 05:58:08 +00006988 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6989 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6990 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6991 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006992
Seth Cantrell79340072015-03-04 05:58:08 +00006993 if (success) {
6994 // Get the fix string from the fixed format specifier.
6995 SmallString<128> buf;
6996 llvm::raw_svector_ostream os(buf);
6997 fixedFS.toString(os);
6998
6999 EmitFormatDiagnostic(
7000 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
7001 << Ex->getType() << false << Ex->getSourceRange(),
7002 Ex->getLocStart(),
7003 /*IsStringLocation*/ false,
7004 getSpecifierRange(startSpecifier, specifierLen),
7005 FixItHint::CreateReplacement(
7006 getSpecifierRange(startSpecifier, specifierLen), os.str()));
7007 } else {
7008 EmitFormatDiagnostic(S.PDiag(diag)
7009 << AT.getRepresentativeTypeName(S.Context)
7010 << Ex->getType() << false << Ex->getSourceRange(),
7011 Ex->getLocStart(),
7012 /*IsStringLocation*/ false,
7013 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00007014 }
7015
Ted Kremenek02087932010-07-16 02:11:22 +00007016 return true;
7017}
7018
Stephen Hines648c3692016-09-16 01:07:04 +00007019static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007020 const Expr *OrigFormatExpr,
7021 ArrayRef<const Expr *> Args,
7022 bool HasVAListArg, unsigned format_idx,
7023 unsigned firstDataArg,
7024 Sema::FormatStringType Type,
7025 bool inFunctionCall,
7026 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00007027 llvm::SmallBitVector &CheckedVarArgs,
7028 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00007029 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00007030 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007031 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007032 S, inFunctionCall, Args[format_idx],
7033 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007034 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007035 return;
7036 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007037
Ted Kremenekab278de2010-01-28 23:39:18 +00007038 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007039 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00007040 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007041 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007042 const ConstantArrayType *T =
7043 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007044 assert(T && "String literal not of constant array type!");
7045 size_t TypeSize = T->getSize().getZExtValue();
7046 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00007047 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007048
7049 // Emit a warning if the string literal is truncated and does not contain an
7050 // embedded null character.
7051 if (TypeSize <= StrRef.size() &&
7052 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
7053 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007054 S, inFunctionCall, Args[format_idx],
7055 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00007056 FExpr->getLocStart(),
7057 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
7058 return;
7059 }
7060
Ted Kremenekab278de2010-01-28 23:39:18 +00007061 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00007062 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00007063 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007064 S, inFunctionCall, Args[format_idx],
7065 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00007066 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00007067 return;
7068 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007069
7070 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00007071 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
7072 Type == Sema::FST_OSTrace) {
7073 CheckPrintfHandler H(
7074 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
7075 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
7076 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
7077 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007078
Hans Wennborg23926bd2011-12-15 10:25:47 +00007079 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007080 S.getLangOpts(),
7081 S.Context.getTargetInfo(),
7082 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00007083 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007084 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00007085 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
7086 numDataArgs, Str, HasVAListArg, Args, format_idx,
7087 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007088
Hans Wennborg23926bd2011-12-15 10:25:47 +00007089 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00007090 S.getLangOpts(),
7091 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00007092 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00007093 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00007094}
7095
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00007096bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
7097 // Str - The format string. NOTE: this is NOT null-terminated!
7098 StringRef StrRef = FExpr->getString();
7099 const char *Str = StrRef.data();
7100 // Account for cases where the string literal is truncated in a declaration.
7101 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
7102 assert(T && "String literal not of constant array type!");
7103 size_t TypeSize = T->getSize().getZExtValue();
7104 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
7105 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
7106 getLangOpts(),
7107 Context.getTargetInfo());
7108}
7109
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007110//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
7111
7112// Returns the related absolute value function that is larger, of 0 if one
7113// does not exist.
7114static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
7115 switch (AbsFunction) {
7116 default:
7117 return 0;
7118
7119 case Builtin::BI__builtin_abs:
7120 return Builtin::BI__builtin_labs;
7121 case Builtin::BI__builtin_labs:
7122 return Builtin::BI__builtin_llabs;
7123 case Builtin::BI__builtin_llabs:
7124 return 0;
7125
7126 case Builtin::BI__builtin_fabsf:
7127 return Builtin::BI__builtin_fabs;
7128 case Builtin::BI__builtin_fabs:
7129 return Builtin::BI__builtin_fabsl;
7130 case Builtin::BI__builtin_fabsl:
7131 return 0;
7132
7133 case Builtin::BI__builtin_cabsf:
7134 return Builtin::BI__builtin_cabs;
7135 case Builtin::BI__builtin_cabs:
7136 return Builtin::BI__builtin_cabsl;
7137 case Builtin::BI__builtin_cabsl:
7138 return 0;
7139
7140 case Builtin::BIabs:
7141 return Builtin::BIlabs;
7142 case Builtin::BIlabs:
7143 return Builtin::BIllabs;
7144 case Builtin::BIllabs:
7145 return 0;
7146
7147 case Builtin::BIfabsf:
7148 return Builtin::BIfabs;
7149 case Builtin::BIfabs:
7150 return Builtin::BIfabsl;
7151 case Builtin::BIfabsl:
7152 return 0;
7153
7154 case Builtin::BIcabsf:
7155 return Builtin::BIcabs;
7156 case Builtin::BIcabs:
7157 return Builtin::BIcabsl;
7158 case Builtin::BIcabsl:
7159 return 0;
7160 }
7161}
7162
7163// Returns the argument type of the absolute value function.
7164static QualType getAbsoluteValueArgumentType(ASTContext &Context,
7165 unsigned AbsType) {
7166 if (AbsType == 0)
7167 return QualType();
7168
7169 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
7170 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
7171 if (Error != ASTContext::GE_None)
7172 return QualType();
7173
7174 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
7175 if (!FT)
7176 return QualType();
7177
7178 if (FT->getNumParams() != 1)
7179 return QualType();
7180
7181 return FT->getParamType(0);
7182}
7183
7184// Returns the best absolute value function, or zero, based on type and
7185// current absolute value function.
7186static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
7187 unsigned AbsFunctionKind) {
7188 unsigned BestKind = 0;
7189 uint64_t ArgSize = Context.getTypeSize(ArgType);
7190 for (unsigned Kind = AbsFunctionKind; Kind != 0;
7191 Kind = getLargerAbsoluteValueFunction(Kind)) {
7192 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
7193 if (Context.getTypeSize(ParamType) >= ArgSize) {
7194 if (BestKind == 0)
7195 BestKind = Kind;
7196 else if (Context.hasSameType(ParamType, ArgType)) {
7197 BestKind = Kind;
7198 break;
7199 }
7200 }
7201 }
7202 return BestKind;
7203}
7204
7205enum AbsoluteValueKind {
7206 AVK_Integer,
7207 AVK_Floating,
7208 AVK_Complex
7209};
7210
7211static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
7212 if (T->isIntegralOrEnumerationType())
7213 return AVK_Integer;
7214 if (T->isRealFloatingType())
7215 return AVK_Floating;
7216 if (T->isAnyComplexType())
7217 return AVK_Complex;
7218
7219 llvm_unreachable("Type not integer, floating, or complex");
7220}
7221
7222// Changes the absolute value function to a different type. Preserves whether
7223// the function is a builtin.
7224static unsigned changeAbsFunction(unsigned AbsKind,
7225 AbsoluteValueKind ValueKind) {
7226 switch (ValueKind) {
7227 case AVK_Integer:
7228 switch (AbsKind) {
7229 default:
7230 return 0;
7231 case Builtin::BI__builtin_fabsf:
7232 case Builtin::BI__builtin_fabs:
7233 case Builtin::BI__builtin_fabsl:
7234 case Builtin::BI__builtin_cabsf:
7235 case Builtin::BI__builtin_cabs:
7236 case Builtin::BI__builtin_cabsl:
7237 return Builtin::BI__builtin_abs;
7238 case Builtin::BIfabsf:
7239 case Builtin::BIfabs:
7240 case Builtin::BIfabsl:
7241 case Builtin::BIcabsf:
7242 case Builtin::BIcabs:
7243 case Builtin::BIcabsl:
7244 return Builtin::BIabs;
7245 }
7246 case AVK_Floating:
7247 switch (AbsKind) {
7248 default:
7249 return 0;
7250 case Builtin::BI__builtin_abs:
7251 case Builtin::BI__builtin_labs:
7252 case Builtin::BI__builtin_llabs:
7253 case Builtin::BI__builtin_cabsf:
7254 case Builtin::BI__builtin_cabs:
7255 case Builtin::BI__builtin_cabsl:
7256 return Builtin::BI__builtin_fabsf;
7257 case Builtin::BIabs:
7258 case Builtin::BIlabs:
7259 case Builtin::BIllabs:
7260 case Builtin::BIcabsf:
7261 case Builtin::BIcabs:
7262 case Builtin::BIcabsl:
7263 return Builtin::BIfabsf;
7264 }
7265 case AVK_Complex:
7266 switch (AbsKind) {
7267 default:
7268 return 0;
7269 case Builtin::BI__builtin_abs:
7270 case Builtin::BI__builtin_labs:
7271 case Builtin::BI__builtin_llabs:
7272 case Builtin::BI__builtin_fabsf:
7273 case Builtin::BI__builtin_fabs:
7274 case Builtin::BI__builtin_fabsl:
7275 return Builtin::BI__builtin_cabsf;
7276 case Builtin::BIabs:
7277 case Builtin::BIlabs:
7278 case Builtin::BIllabs:
7279 case Builtin::BIfabsf:
7280 case Builtin::BIfabs:
7281 case Builtin::BIfabsl:
7282 return Builtin::BIcabsf;
7283 }
7284 }
7285 llvm_unreachable("Unable to convert function");
7286}
7287
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007288static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007289 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7290 if (!FnInfo)
7291 return 0;
7292
7293 switch (FDecl->getBuiltinID()) {
7294 default:
7295 return 0;
7296 case Builtin::BI__builtin_abs:
7297 case Builtin::BI__builtin_fabs:
7298 case Builtin::BI__builtin_fabsf:
7299 case Builtin::BI__builtin_fabsl:
7300 case Builtin::BI__builtin_labs:
7301 case Builtin::BI__builtin_llabs:
7302 case Builtin::BI__builtin_cabs:
7303 case Builtin::BI__builtin_cabsf:
7304 case Builtin::BI__builtin_cabsl:
7305 case Builtin::BIabs:
7306 case Builtin::BIlabs:
7307 case Builtin::BIllabs:
7308 case Builtin::BIfabs:
7309 case Builtin::BIfabsf:
7310 case Builtin::BIfabsl:
7311 case Builtin::BIcabs:
7312 case Builtin::BIcabsf:
7313 case Builtin::BIcabsl:
7314 return FDecl->getBuiltinID();
7315 }
7316 llvm_unreachable("Unknown Builtin type");
7317}
7318
7319// If the replacement is valid, emit a note with replacement function.
7320// Additionally, suggest including the proper header if not already included.
7321static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007322 unsigned AbsKind, QualType ArgType) {
7323 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007324 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007325 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007326 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7327 FunctionName = "std::abs";
7328 if (ArgType->isIntegralOrEnumerationType()) {
7329 HeaderName = "cstdlib";
7330 } else if (ArgType->isRealFloatingType()) {
7331 HeaderName = "cmath";
7332 } else {
7333 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007334 }
Richard Trieubeffb832014-04-15 23:47:53 +00007335
7336 // Lookup all std::abs
7337 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007338 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007339 R.suppressDiagnostics();
7340 S.LookupQualifiedName(R, Std);
7341
7342 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007343 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007344 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7345 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7346 } else {
7347 FDecl = dyn_cast<FunctionDecl>(I);
7348 }
7349 if (!FDecl)
7350 continue;
7351
7352 // Found std::abs(), check that they are the right ones.
7353 if (FDecl->getNumParams() != 1)
7354 continue;
7355
7356 // Check that the parameter type can handle the argument.
7357 QualType ParamType = FDecl->getParamDecl(0)->getType();
7358 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7359 S.Context.getTypeSize(ArgType) <=
7360 S.Context.getTypeSize(ParamType)) {
7361 // Found a function, don't need the header hint.
7362 EmitHeaderHint = false;
7363 break;
7364 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007365 }
Richard Trieubeffb832014-04-15 23:47:53 +00007366 }
7367 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007368 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007369 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7370
7371 if (HeaderName) {
7372 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7373 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7374 R.suppressDiagnostics();
7375 S.LookupName(R, S.getCurScope());
7376
7377 if (R.isSingleResult()) {
7378 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7379 if (FD && FD->getBuiltinID() == AbsKind) {
7380 EmitHeaderHint = false;
7381 } else {
7382 return;
7383 }
7384 } else if (!R.empty()) {
7385 return;
7386 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007387 }
7388 }
7389
7390 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007391 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007392
Richard Trieubeffb832014-04-15 23:47:53 +00007393 if (!HeaderName)
7394 return;
7395
7396 if (!EmitHeaderHint)
7397 return;
7398
Alp Toker5d96e0a2014-07-11 20:53:51 +00007399 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7400 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007401}
7402
Richard Trieua7f30b12016-12-06 01:42:28 +00007403template <std::size_t StrLen>
7404static bool IsStdFunction(const FunctionDecl *FDecl,
7405 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007406 if (!FDecl)
7407 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007408 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007409 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007410 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007411 return false;
7412
7413 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007414}
7415
7416// Warn when using the wrong abs() function.
7417void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007418 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007419 if (Call->getNumArgs() != 1)
7420 return;
7421
7422 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007423 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007424 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007425 return;
7426
7427 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7428 QualType ParamType = Call->getArg(0)->getType();
7429
Alp Toker5d96e0a2014-07-11 20:53:51 +00007430 // Unsigned types cannot be negative. Suggest removing the absolute value
7431 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007432 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007433 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007434 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007435 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7436 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007437 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007438 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7439 return;
7440 }
7441
David Majnemer7f77eb92015-11-15 03:04:34 +00007442 // Taking the absolute value of a pointer is very suspicious, they probably
7443 // wanted to index into an array, dereference a pointer, call a function, etc.
7444 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7445 unsigned DiagType = 0;
7446 if (ArgType->isFunctionType())
7447 DiagType = 1;
7448 else if (ArgType->isArrayType())
7449 DiagType = 2;
7450
7451 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7452 return;
7453 }
7454
Richard Trieubeffb832014-04-15 23:47:53 +00007455 // std::abs has overloads which prevent most of the absolute value problems
7456 // from occurring.
7457 if (IsStdAbs)
7458 return;
7459
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007460 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7461 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7462
7463 // The argument and parameter are the same kind. Check if they are the right
7464 // size.
7465 if (ArgValueKind == ParamValueKind) {
7466 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7467 return;
7468
7469 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7470 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7471 << FDecl << ArgType << ParamType;
7472
7473 if (NewAbsKind == 0)
7474 return;
7475
7476 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007477 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007478 return;
7479 }
7480
7481 // ArgValueKind != ParamValueKind
7482 // The wrong type of absolute value function was used. Attempt to find the
7483 // proper one.
7484 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7485 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7486 if (NewAbsKind == 0)
7487 return;
7488
7489 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7490 << FDecl << ParamValueKind << ArgValueKind;
7491
7492 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007493 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007494}
7495
Richard Trieu67c00712016-12-05 23:41:46 +00007496//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007497void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7498 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007499 if (!Call || !FDecl) return;
7500
7501 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007502 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007503 if (Call->getExprLoc().isMacroID()) return;
7504
7505 // Only care about the one template argument, two function parameter std::max
7506 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007507 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007508 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7509 if (!ArgList) return;
7510 if (ArgList->size() != 1) return;
7511
7512 // Check that template type argument is unsigned integer.
7513 const auto& TA = ArgList->get(0);
7514 if (TA.getKind() != TemplateArgument::Type) return;
7515 QualType ArgType = TA.getAsType();
7516 if (!ArgType->isUnsignedIntegerType()) return;
7517
7518 // See if either argument is a literal zero.
7519 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7520 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7521 if (!MTE) return false;
7522 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7523 if (!Num) return false;
7524 if (Num->getValue() != 0) return false;
7525 return true;
7526 };
7527
7528 const Expr *FirstArg = Call->getArg(0);
7529 const Expr *SecondArg = Call->getArg(1);
7530 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7531 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7532
7533 // Only warn when exactly one argument is zero.
7534 if (IsFirstArgZero == IsSecondArgZero) return;
7535
7536 SourceRange FirstRange = FirstArg->getSourceRange();
7537 SourceRange SecondRange = SecondArg->getSourceRange();
7538
7539 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7540
7541 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7542 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7543
7544 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7545 SourceRange RemovalRange;
7546 if (IsFirstArgZero) {
7547 RemovalRange = SourceRange(FirstRange.getBegin(),
7548 SecondRange.getBegin().getLocWithOffset(-1));
7549 } else {
7550 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7551 SecondRange.getEnd());
7552 }
7553
7554 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7555 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7556 << FixItHint::CreateRemoval(RemovalRange);
7557}
7558
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007559//===--- CHECK: Standard memory functions ---------------------------------===//
7560
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007561/// Takes the expression passed to the size_t parameter of functions
Nico Weber0e6daef2013-12-26 23:38:39 +00007562/// such as memcmp, strncat, etc and warns if it's a comparison.
7563///
7564/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7565static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7566 IdentifierInfo *FnName,
7567 SourceLocation FnLoc,
7568 SourceLocation RParenLoc) {
7569 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7570 if (!Size)
7571 return false;
7572
Richard Smithc70f1d62017-12-14 15:16:18 +00007573 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7574 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007575 return false;
7576
Nico Weber0e6daef2013-12-26 23:38:39 +00007577 SourceRange SizeRange = Size->getSourceRange();
7578 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7579 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007580 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007581 << FnName << FixItHint::CreateInsertion(
7582 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007583 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007584 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007585 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007586 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7587 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007588
7589 return true;
7590}
7591
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007592/// Determine whether the given type is or contains a dynamic class type
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007593/// (e.g., whether it has a vtable).
7594static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7595 bool &IsContained) {
7596 // Look through array types while ignoring qualifiers.
7597 const Type *Ty = T->getBaseElementTypeUnsafe();
7598 IsContained = false;
7599
7600 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7601 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007602 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007603 return nullptr;
7604
7605 if (RD->isDynamicClass())
7606 return RD;
7607
7608 // Check all the fields. If any bases were dynamic, the class is dynamic.
7609 // It's impossible for a class to transitively contain itself by value, so
7610 // infinite recursion is impossible.
7611 for (auto *FD : RD->fields()) {
7612 bool SubContained;
7613 if (const CXXRecordDecl *ContainedRD =
7614 getContainedDynamicClass(FD->getType(), SubContained)) {
7615 IsContained = true;
7616 return ContainedRD;
7617 }
7618 }
7619
7620 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007621}
7622
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007623/// If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007624/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007625static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007626 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007627 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007628 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007629 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007630
Craig Topperc3ec1492014-05-26 06:22:03 +00007631 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007632}
7633
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007634/// If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007635static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007636 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7637 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007638 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007639 return SizeOf->getTypeOfArgument();
7640
7641 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007642}
7643
Akira Hatanaka2be04412018-04-17 19:13:41 +00007644namespace {
7645
7646struct SearchNonTrivialToInitializeField
7647 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7648 using Super =
7649 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7650
7651 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7652
7653 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7654 SourceLocation SL) {
7655 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7656 asDerived().visitArray(PDIK, AT, SL);
7657 return;
7658 }
7659
7660 Super::visitWithKind(PDIK, FT, SL);
7661 }
7662
7663 void visitARCStrong(QualType FT, SourceLocation SL) {
7664 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7665 }
7666 void visitARCWeak(QualType FT, SourceLocation SL) {
7667 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7668 }
7669 void visitStruct(QualType FT, SourceLocation SL) {
7670 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7671 visit(FD->getType(), FD->getLocation());
7672 }
7673 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7674 const ArrayType *AT, SourceLocation SL) {
7675 visit(getContext().getBaseElementType(AT), SL);
7676 }
7677 void visitTrivial(QualType FT, SourceLocation SL) {}
7678
7679 static void diag(QualType RT, const Expr *E, Sema &S) {
7680 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7681 }
7682
7683 ASTContext &getContext() { return S.getASTContext(); }
7684
7685 const Expr *E;
7686 Sema &S;
7687};
7688
7689struct SearchNonTrivialToCopyField
7690 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7691 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7692
7693 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7694
7695 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7696 SourceLocation SL) {
7697 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7698 asDerived().visitArray(PCK, AT, SL);
7699 return;
7700 }
7701
7702 Super::visitWithKind(PCK, FT, SL);
7703 }
7704
7705 void visitARCStrong(QualType FT, SourceLocation SL) {
7706 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7707 }
7708 void visitARCWeak(QualType FT, SourceLocation SL) {
7709 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7710 }
7711 void visitStruct(QualType FT, SourceLocation SL) {
7712 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7713 visit(FD->getType(), FD->getLocation());
7714 }
7715 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7716 SourceLocation SL) {
7717 visit(getContext().getBaseElementType(AT), SL);
7718 }
7719 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7720 SourceLocation SL) {}
7721 void visitTrivial(QualType FT, SourceLocation SL) {}
7722 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7723
7724 static void diag(QualType RT, const Expr *E, Sema &S) {
7725 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7726 }
7727
7728 ASTContext &getContext() { return S.getASTContext(); }
7729
7730 const Expr *E;
7731 Sema &S;
7732};
7733
7734}
7735
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007736/// Check for dangerous or invalid arguments to memset().
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007737///
Chandler Carruthac687262011-06-03 06:23:57 +00007738/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007739/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7740/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007741///
7742/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007743void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007744 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007745 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007746 assert(BId != 0);
7747
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007748 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007749 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007750 unsigned ExpectedNumArgs =
7751 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007752 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007753 return;
7754
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007755 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007756 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007757 unsigned LenArg =
7758 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007759 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007760
Nico Weber0e6daef2013-12-26 23:38:39 +00007761 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7762 Call->getLocStart(), Call->getRParenLoc()))
7763 return;
7764
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007765 // We have special checking when the length is a sizeof expression.
7766 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7767 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7768 llvm::FoldingSetNodeID SizeOfArgID;
7769
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007770 // Although widely used, 'bzero' is not a standard function. Be more strict
7771 // with the argument types before allowing diagnostics and only allow the
7772 // form bzero(ptr, sizeof(...)).
7773 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7774 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7775 return;
7776
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007777 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7778 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007779 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007780
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007781 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007782 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007783 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007784 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007785
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007786 // Never warn about void type pointers. This can be used to suppress
7787 // false positives.
7788 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007789 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007790
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007791 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7792 // actually comparing the expressions for equality. Because computing the
7793 // expression IDs can be expensive, we only do this if the diagnostic is
7794 // enabled.
7795 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007796 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7797 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007798 // We only compute IDs for expressions if the warning is enabled, and
7799 // cache the sizeof arg's ID.
7800 if (SizeOfArgID == llvm::FoldingSetNodeID())
7801 SizeOfArg->Profile(SizeOfArgID, Context, true);
7802 llvm::FoldingSetNodeID DestID;
7803 Dest->Profile(DestID, Context, true);
7804 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007805 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7806 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007807 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007808 StringRef ReadableName = FnName->getName();
7809
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007810 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007811 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007812 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007813 if (!PointeeTy->isIncompleteType() &&
7814 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007815 ActionIdx = 2; // If the pointee's size is sizeof(char),
7816 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007817
7818 // If the function is defined as a builtin macro, do not show macro
7819 // expansion.
7820 SourceLocation SL = SizeOfArg->getExprLoc();
7821 SourceRange DSR = Dest->getSourceRange();
7822 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007823 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007824
7825 if (SM.isMacroArgExpansion(SL)) {
7826 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7827 SL = SM.getSpellingLoc(SL);
7828 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7829 SM.getSpellingLoc(DSR.getEnd()));
7830 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7831 SM.getSpellingLoc(SSR.getEnd()));
7832 }
7833
Anna Zaksd08d9152012-05-30 23:14:52 +00007834 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007835 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007836 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007837 << PointeeTy
7838 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007839 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007840 << SSR);
7841 DiagRuntimeBehavior(SL, SizeOfArg,
7842 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7843 << ActionIdx
7844 << SSR);
7845
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007846 break;
7847 }
7848 }
7849
7850 // Also check for cases where the sizeof argument is the exact same
7851 // type as the memory argument, and where it points to a user-defined
7852 // record type.
7853 if (SizeOfArgTy != QualType()) {
7854 if (PointeeTy->isRecordType() &&
7855 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7856 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7857 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7858 << FnName << SizeOfArgTy << ArgIdx
7859 << PointeeTy << Dest->getSourceRange()
7860 << LenExpr->getSourceRange());
7861 break;
7862 }
Nico Weberc5e73862011-06-14 16:14:58 +00007863 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007864 } else if (DestTy->isArrayType()) {
7865 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007866 }
Nico Weberc5e73862011-06-14 16:14:58 +00007867
Nico Weberc44b35e2015-03-21 17:37:46 +00007868 if (PointeeTy == QualType())
7869 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007870
Nico Weberc44b35e2015-03-21 17:37:46 +00007871 // Always complain about dynamic classes.
7872 bool IsContained;
7873 if (const CXXRecordDecl *ContainedRD =
7874 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007875
Nico Weberc44b35e2015-03-21 17:37:46 +00007876 unsigned OperationType = 0;
7877 // "overwritten" if we're warning about the destination for any call
7878 // but memcmp; otherwise a verb appropriate to the call.
7879 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7880 if (BId == Builtin::BImemcpy)
7881 OperationType = 1;
7882 else if(BId == Builtin::BImemmove)
7883 OperationType = 2;
7884 else if (BId == Builtin::BImemcmp)
7885 OperationType = 3;
7886 }
7887
John McCall31168b02011-06-15 23:02:42 +00007888 DiagRuntimeBehavior(
7889 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007890 PDiag(diag::warn_dyn_class_memaccess)
7891 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7892 << FnName << IsContained << ContainedRD << OperationType
7893 << Call->getCallee()->getSourceRange());
7894 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7895 BId != Builtin::BImemset)
7896 DiagRuntimeBehavior(
7897 Dest->getExprLoc(), Dest,
7898 PDiag(diag::warn_arc_object_memaccess)
7899 << ArgIdx << FnName << PointeeTy
7900 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00007901 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
7902 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
7903 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
7904 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7905 PDiag(diag::warn_cstruct_memaccess)
7906 << ArgIdx << FnName << PointeeTy << 0);
7907 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
7908 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
7909 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
7910 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7911 PDiag(diag::warn_cstruct_memaccess)
7912 << ArgIdx << FnName << PointeeTy << 1);
7913 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
7914 } else {
7915 continue;
7916 }
7917 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00007918 continue;
7919
7920 DiagRuntimeBehavior(
7921 Dest->getExprLoc(), Dest,
7922 PDiag(diag::note_bad_memaccess_silence)
7923 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7924 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007925 }
7926}
7927
Ted Kremenek6865f772011-08-18 20:55:45 +00007928// A little helper routine: ignore addition and subtraction of integer literals.
7929// This intentionally does not ignore all integer constant expressions because
7930// we don't want to remove sizeof().
7931static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7932 Ex = Ex->IgnoreParenCasts();
7933
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007934 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00007935 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7936 if (!BO || !BO->isAdditiveOp())
7937 break;
7938
7939 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7940 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7941
7942 if (isa<IntegerLiteral>(RHS))
7943 Ex = LHS;
7944 else if (isa<IntegerLiteral>(LHS))
7945 Ex = RHS;
7946 else
7947 break;
7948 }
7949
7950 return Ex;
7951}
7952
Anna Zaks13b08572012-08-08 21:42:23 +00007953static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7954 ASTContext &Context) {
7955 // Only handle constant-sized or VLAs, but not flexible members.
7956 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7957 // Only issue the FIXIT for arrays of size > 1.
7958 if (CAT->getSize().getSExtValue() <= 1)
7959 return false;
7960 } else if (!Ty->isVariableArrayType()) {
7961 return false;
7962 }
7963 return true;
7964}
7965
Ted Kremenek6865f772011-08-18 20:55:45 +00007966// Warn if the user has made the 'size' argument to strlcpy or strlcat
7967// be the size of the source, instead of the destination.
7968void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7969 IdentifierInfo *FnName) {
7970
7971 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007972 unsigned NumArgs = Call->getNumArgs();
7973 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007974 return;
7975
7976 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7977 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007978 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007979
7980 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7981 Call->getLocStart(), Call->getRParenLoc()))
7982 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007983
7984 // Look for 'strlcpy(dst, x, sizeof(x))'
7985 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7986 CompareWithSrc = Ex;
7987 else {
7988 // Look for 'strlcpy(dst, x, strlen(x))'
7989 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007990 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7991 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007992 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7993 }
7994 }
7995
7996 if (!CompareWithSrc)
7997 return;
7998
7999 // Determine if the argument to sizeof/strlen is equal to the source
8000 // argument. In principle there's all kinds of things you could do
8001 // here, for instance creating an == expression and evaluating it with
8002 // EvaluateAsBooleanCondition, but this uses a more direct technique:
8003 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
8004 if (!SrcArgDRE)
8005 return;
8006
8007 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
8008 if (!CompareWithSrcDRE ||
8009 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
8010 return;
8011
8012 const Expr *OriginalSizeArg = Call->getArg(2);
8013 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
8014 << OriginalSizeArg->getSourceRange() << FnName;
8015
8016 // Output a FIXIT hint if the destination is an array (rather than a
8017 // pointer to an array). This could be enhanced to handle some
8018 // pointers if we know the actual size, like if DstArg is 'array+2'
8019 // we could say 'sizeof(array)-2'.
8020 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00008021 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00008022 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008023
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008024 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00008025 llvm::raw_svector_ostream OS(sizeString);
8026 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008027 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00008028 OS << ")";
8029
8030 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
8031 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
8032 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00008033}
8034
Anna Zaks314cd092012-02-01 19:08:57 +00008035/// Check if two expressions refer to the same declaration.
8036static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
8037 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
8038 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
8039 return D1->getDecl() == D2->getDecl();
8040 return false;
8041}
8042
8043static const Expr *getStrlenExprArg(const Expr *E) {
8044 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8045 const FunctionDecl *FD = CE->getDirectCallee();
8046 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00008047 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008048 return CE->getArg(0)->IgnoreParenCasts();
8049 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008050 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00008051}
8052
8053// Warn on anti-patterns as the 'size' argument to strncat.
8054// The correct size argument should look like following:
8055// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
8056void Sema::CheckStrncatArguments(const CallExpr *CE,
8057 IdentifierInfo *FnName) {
8058 // Don't crash if the user has the wrong number of arguments.
8059 if (CE->getNumArgs() < 3)
8060 return;
8061 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
8062 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
8063 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
8064
Nico Weber0e6daef2013-12-26 23:38:39 +00008065 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
8066 CE->getRParenLoc()))
8067 return;
8068
Anna Zaks314cd092012-02-01 19:08:57 +00008069 // Identify common expressions, which are wrongly used as the size argument
8070 // to strncat and may lead to buffer overflows.
8071 unsigned PatternType = 0;
8072 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
8073 // - sizeof(dst)
8074 if (referToTheSameDecl(SizeOfArg, DstArg))
8075 PatternType = 1;
8076 // - sizeof(src)
8077 else if (referToTheSameDecl(SizeOfArg, SrcArg))
8078 PatternType = 2;
8079 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
8080 if (BE->getOpcode() == BO_Sub) {
8081 const Expr *L = BE->getLHS()->IgnoreParenCasts();
8082 const Expr *R = BE->getRHS()->IgnoreParenCasts();
8083 // - sizeof(dst) - strlen(dst)
8084 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
8085 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
8086 PatternType = 1;
8087 // - sizeof(src) - (anything)
8088 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
8089 PatternType = 2;
8090 }
8091 }
8092
8093 if (PatternType == 0)
8094 return;
8095
Anna Zaks5069aa32012-02-03 01:27:37 +00008096 // Generate the diagnostic.
8097 SourceLocation SL = LenArg->getLocStart();
8098 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00008099 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00008100
8101 // If the function is defined as a builtin macro, do not show macro expansion.
8102 if (SM.isMacroArgExpansion(SL)) {
8103 SL = SM.getSpellingLoc(SL);
8104 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
8105 SM.getSpellingLoc(SR.getEnd()));
8106 }
8107
Anna Zaks13b08572012-08-08 21:42:23 +00008108 // Check if the destination is an array (rather than a pointer to an array).
8109 QualType DstTy = DstArg->getType();
8110 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
8111 Context);
8112 if (!isKnownSizeArray) {
8113 if (PatternType == 1)
8114 Diag(SL, diag::warn_strncat_wrong_size) << SR;
8115 else
8116 Diag(SL, diag::warn_strncat_src_size) << SR;
8117 return;
8118 }
8119
Anna Zaks314cd092012-02-01 19:08:57 +00008120 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00008121 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008122 else
Anna Zaks5069aa32012-02-03 01:27:37 +00008123 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00008124
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00008125 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00008126 llvm::raw_svector_ostream OS(sizeString);
8127 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008128 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008129 OS << ") - ";
8130 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00008131 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00008132 OS << ") - 1";
8133
Anna Zaks5069aa32012-02-03 01:27:37 +00008134 Diag(SL, diag::note_strncat_wrong_size)
8135 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00008136}
8137
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008138//===--- CHECK: Return Address of Stack Variable --------------------------===//
8139
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008140static const Expr *EvalVal(const Expr *E,
8141 SmallVectorImpl<const DeclRefExpr *> &refVars,
8142 const Decl *ParentDecl);
8143static const Expr *EvalAddr(const Expr *E,
8144 SmallVectorImpl<const DeclRefExpr *> &refVars,
8145 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008146
8147/// CheckReturnStackAddr - Check if a return statement returns the address
8148/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008149static void
8150CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
8151 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008152 const Expr *stackE = nullptr;
8153 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008154
8155 // Perform checking for returned stack addresses, local blocks,
8156 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00008157 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008158 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008159 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00008160 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00008161 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008162 }
8163
Craig Topperc3ec1492014-05-26 06:22:03 +00008164 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008165 return; // Nothing suspicious was found.
8166
Simon Pilgrim750bde62017-03-31 11:00:53 +00008167 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00008168 // of a parameter reference doesn't need a warning.
8169 for (auto *DRE : refVars)
8170 if (isa<ParmVarDecl>(DRE->getDecl()))
8171 return;
8172
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008173 SourceLocation diagLoc;
8174 SourceRange diagRange;
8175 if (refVars.empty()) {
8176 diagLoc = stackE->getLocStart();
8177 diagRange = stackE->getSourceRange();
8178 } else {
8179 // We followed through a reference variable. 'stackE' contains the
8180 // problematic expression but we will warn at the return statement pointing
8181 // at the reference variable. We will later display the "trail" of
8182 // reference variables using notes.
8183 diagLoc = refVars[0]->getLocStart();
8184 diagRange = refVars[0]->getSourceRange();
8185 }
8186
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008187 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
8188 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00008189 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008190 << DR->getDecl()->getDeclName() << diagRange;
8191 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008192 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008193 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008194 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008195 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00008196 // If there is an LValue->RValue conversion, then the value of the
8197 // reference type is used, not the reference.
8198 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
8199 if (ICE->getCastKind() == CK_LValueToRValue) {
8200 return;
8201 }
8202 }
Craig Topperda7b27f2015-11-17 05:40:09 +00008203 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
8204 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008205 }
8206
8207 // Display the "trail" of reference variables that we followed until we
8208 // found the problematic expression using notes.
8209 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008210 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008211 // If this var binds to another reference var, show the range of the next
8212 // var, otherwise the var binds to the problematic expression, in which case
8213 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008214 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
8215 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008216 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
8217 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008218 }
8219}
8220
8221/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
8222/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008223/// to a location on the stack, a local block, an address of a label, or a
8224/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008225/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008226/// encounter a subexpression that (1) clearly does not lead to one of the
8227/// above problematic expressions (2) is something we cannot determine leads to
8228/// a problematic expression based on such local checking.
8229///
8230/// Both EvalAddr and EvalVal follow through reference variables to evaluate
8231/// the expression that they point to. Such variables are added to the
8232/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008233///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00008234/// EvalAddr processes expressions that are pointers that are used as
8235/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008236/// At the base case of the recursion is a check for the above problematic
8237/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008238///
8239/// This implementation handles:
8240///
8241/// * pointer-to-pointer casts
8242/// * implicit conversions from array references to pointers
8243/// * taking the address of fields
8244/// * arbitrary interplay between "&" and "*" operators
8245/// * pointer arithmetic from an address of a stack variable
8246/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008247static const Expr *EvalAddr(const Expr *E,
8248 SmallVectorImpl<const DeclRefExpr *> &refVars,
8249 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008250 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008251 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008252
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008253 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008254 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008255 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008256 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008257 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008258
Peter Collingbourne91147592011-04-15 00:35:48 +00008259 E = E->IgnoreParens();
8260
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008261 // Our "symbolic interpreter" is just a dispatch off the currently
8262 // viewed AST node. We then recursively traverse the AST by calling
8263 // EvalAddr and EvalVal appropriately.
8264 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008265 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008266 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008267
Richard Smith40f08eb2014-01-30 22:05:38 +00008268 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008269 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008270 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008271
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008272 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008273 // If this is a reference variable, follow through to the expression that
8274 // it points to.
8275 if (V->hasLocalStorage() &&
8276 V->getType()->isReferenceType() && V->hasInit()) {
8277 // Add the reference variable to the "trail".
8278 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008279 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008280 }
8281
Craig Topperc3ec1492014-05-26 06:22:03 +00008282 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008283 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008284
Chris Lattner934edb22007-12-28 05:31:15 +00008285 case Stmt::UnaryOperatorClass: {
8286 // The only unary operator that make sense to handle here
8287 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008288 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008289
John McCalle3027922010-08-25 11:45:40 +00008290 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008291 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008292 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008293 }
Mike Stump11289f42009-09-09 15:08:12 +00008294
Chris Lattner934edb22007-12-28 05:31:15 +00008295 case Stmt::BinaryOperatorClass: {
8296 // Handle pointer arithmetic. All other binary operators are not valid
8297 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008298 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008299 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008300
John McCalle3027922010-08-25 11:45:40 +00008301 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008302 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008303
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008304 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008305
8306 // Determine which argument is the real pointer base. It could be
8307 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008308 if (!Base->getType()->isPointerType())
8309 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008310
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008311 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008312 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008313 }
Steve Naroff2752a172008-09-10 19:17:48 +00008314
Chris Lattner934edb22007-12-28 05:31:15 +00008315 // For conditional operators we need to see if either the LHS or RHS are
8316 // valid DeclRefExpr*s. If one of them is valid, we return it.
8317 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008318 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008319
Chris Lattner934edb22007-12-28 05:31:15 +00008320 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008321 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008322 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008323 // In C++, we can have a throw-expression, which has 'void' type.
8324 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008325 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008326 return LHS;
8327 }
Chris Lattner934edb22007-12-28 05:31:15 +00008328
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008329 // In C++, we can have a throw-expression, which has 'void' type.
8330 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008331 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008332
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008333 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008334 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008335
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008336 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008337 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008338 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008339 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008340
8341 case Stmt::AddrLabelExprClass:
8342 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008343
John McCall28fc7092011-11-10 05:35:25 +00008344 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008345 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8346 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008347
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008348 // For casts, we need to handle conversions from arrays to
8349 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008350 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008351 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008352 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008353 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008354 case Stmt::CXXStaticCastExprClass:
8355 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008356 case Stmt::CXXConstCastExprClass:
8357 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008358 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008359 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008360 case CK_LValueToRValue:
8361 case CK_NoOp:
8362 case CK_BaseToDerived:
8363 case CK_DerivedToBase:
8364 case CK_UncheckedDerivedToBase:
8365 case CK_Dynamic:
8366 case CK_CPointerToObjCPointerCast:
8367 case CK_BlockPointerToObjCPointerCast:
8368 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008369 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008370
8371 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008372 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008373
Richard Trieudadefde2014-07-02 04:39:38 +00008374 case CK_BitCast:
8375 if (SubExpr->getType()->isAnyPointerType() ||
8376 SubExpr->getType()->isBlockPointerType() ||
8377 SubExpr->getType()->isObjCQualifiedIdType())
8378 return EvalAddr(SubExpr, refVars, ParentDecl);
8379 else
8380 return nullptr;
8381
Eli Friedman8195ad72012-02-23 23:04:32 +00008382 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008383 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008384 }
Chris Lattner934edb22007-12-28 05:31:15 +00008385 }
Mike Stump11289f42009-09-09 15:08:12 +00008386
Douglas Gregorfe314812011-06-21 17:03:29 +00008387 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008388 if (const Expr *Result =
8389 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8390 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008391 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008392 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008393
Chris Lattner934edb22007-12-28 05:31:15 +00008394 // Everything else: we simply don't reason about them.
8395 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008396 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008397 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008398}
Mike Stump11289f42009-09-09 15:08:12 +00008399
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008400/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8401/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008402static const Expr *EvalVal(const Expr *E,
8403 SmallVectorImpl<const DeclRefExpr *> &refVars,
8404 const Decl *ParentDecl) {
8405 do {
8406 // We should only be called for evaluating non-pointer expressions, or
8407 // expressions with a pointer type that are not used as references but
8408 // instead
8409 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008410
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008411 // Our "symbolic interpreter" is just a dispatch off the currently
8412 // viewed AST node. We then recursively traverse the AST by calling
8413 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008414
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008415 E = E->IgnoreParens();
8416 switch (E->getStmtClass()) {
8417 case Stmt::ImplicitCastExprClass: {
8418 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8419 if (IE->getValueKind() == VK_LValue) {
8420 E = IE->getSubExpr();
8421 continue;
8422 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008423 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008424 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008425
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008426 case Stmt::ExprWithCleanupsClass:
8427 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8428 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008429
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008430 case Stmt::DeclRefExprClass: {
8431 // When we hit a DeclRefExpr we are looking at code that refers to a
8432 // variable's name. If it's not a reference variable we check if it has
8433 // local storage within the function, and if so, return the expression.
8434 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8435
8436 // If we leave the immediate function, the lifetime isn't about to end.
8437 if (DR->refersToEnclosingVariableOrCapture())
8438 return nullptr;
8439
8440 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8441 // Check if it refers to itself, e.g. "int& i = i;".
8442 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008443 return DR;
8444
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008445 if (V->hasLocalStorage()) {
8446 if (!V->getType()->isReferenceType())
8447 return DR;
8448
8449 // Reference variable, follow through to the expression that
8450 // it points to.
8451 if (V->hasInit()) {
8452 // Add the reference variable to the "trail".
8453 refVars.push_back(DR);
8454 return EvalVal(V->getInit(), refVars, V);
8455 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008456 }
8457 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008458
8459 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008460 }
Mike Stump11289f42009-09-09 15:08:12 +00008461
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008462 case Stmt::UnaryOperatorClass: {
8463 // The only unary operator that make sense to handle here
8464 // is Deref. All others don't resolve to a "name." This includes
8465 // handling all sorts of rvalues passed to a unary operator.
8466 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008467
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008468 if (U->getOpcode() == UO_Deref)
8469 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008470
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008471 return nullptr;
8472 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008473
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008474 case Stmt::ArraySubscriptExprClass: {
8475 // Array subscripts are potential references to data on the stack. We
8476 // retrieve the DeclRefExpr* for the array variable if it indeed
8477 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008478 const auto *ASE = cast<ArraySubscriptExpr>(E);
8479 if (ASE->isTypeDependent())
8480 return nullptr;
8481 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008482 }
Mike Stump11289f42009-09-09 15:08:12 +00008483
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008484 case Stmt::OMPArraySectionExprClass: {
8485 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8486 ParentDecl);
8487 }
Mike Stump11289f42009-09-09 15:08:12 +00008488
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008489 case Stmt::ConditionalOperatorClass: {
8490 // For conditional operators we need to see if either the LHS or RHS are
8491 // non-NULL Expr's. If one is non-NULL, we return it.
8492 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008493
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008494 // Handle the GNU extension for missing LHS.
8495 if (const Expr *LHSExpr = C->getLHS()) {
8496 // In C++, we can have a throw-expression, which has 'void' type.
8497 if (!LHSExpr->getType()->isVoidType())
8498 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8499 return LHS;
8500 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008501
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008502 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008503 if (C->getRHS()->getType()->isVoidType())
8504 return nullptr;
8505
8506 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008507 }
8508
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008509 // Accesses to members are potential references to data on the stack.
8510 case Stmt::MemberExprClass: {
8511 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008512
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008513 // Check for indirect access. We only want direct field accesses.
8514 if (M->isArrow())
8515 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008516
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008517 // Check whether the member type is itself a reference, in which case
8518 // we're not going to refer to the member, but to what the member refers
8519 // to.
8520 if (M->getMemberDecl()->getType()->isReferenceType())
8521 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008522
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008523 return EvalVal(M->getBase(), refVars, ParentDecl);
8524 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008525
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008526 case Stmt::MaterializeTemporaryExprClass:
8527 if (const Expr *Result =
8528 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8529 refVars, ParentDecl))
8530 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008531 return E;
8532
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008533 default:
8534 // Check that we don't return or take the address of a reference to a
8535 // temporary. This is only useful in C++.
8536 if (!E->isTypeDependent() && E->isRValue())
8537 return E;
8538
8539 // Everything else: we simply don't reason about them.
8540 return nullptr;
8541 }
8542 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008543}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008544
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008545void
8546Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8547 SourceLocation ReturnLoc,
8548 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008549 const AttrVec *Attrs,
8550 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008551 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8552
8553 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008554 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8555 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008556 CheckNonNullExpr(*this, RetValExp))
8557 Diag(ReturnLoc, diag::warn_null_ret)
8558 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008559
8560 // C++11 [basic.stc.dynamic.allocation]p4:
8561 // If an allocation function declared with a non-throwing
8562 // exception-specification fails to allocate storage, it shall return
8563 // a null pointer. Any other allocation function that fails to allocate
8564 // storage shall indicate failure only by throwing an exception [...]
8565 if (FD) {
8566 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8567 if (Op == OO_New || Op == OO_Array_New) {
8568 const FunctionProtoType *Proto
8569 = FD->getType()->castAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00008570 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
Artyom Skrobov9f213442014-01-24 11:10:39 +00008571 CheckNonNullExpr(*this, RetValExp))
8572 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8573 << FD << getLangOpts().CPlusPlus11;
8574 }
8575 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008576}
8577
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008578//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8579
8580/// Check for comparisons of floating point operands using != and ==.
8581/// Issue a warning if these are no self-comparisons, as they are not likely
8582/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008583void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008584 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8585 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008586
8587 // Special case: check for x == x (which is OK).
8588 // Do not emit warnings for such cases.
8589 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8590 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8591 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008592 return;
Mike Stump11289f42009-09-09 15:08:12 +00008593
Ted Kremenekeda40e22007-11-29 00:59:04 +00008594 // Special case: check for comparisons against literals that can be exactly
8595 // represented by APFloat. In such cases, do not emit a warning. This
8596 // is a heuristic: often comparison against such literals are used to
8597 // detect if a value in a variable has not changed. This clearly can
8598 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008599 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8600 if (FLL->isExact())
8601 return;
8602 } else
8603 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8604 if (FLR->isExact())
8605 return;
Mike Stump11289f42009-09-09 15:08:12 +00008606
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008607 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008608 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008609 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008610 return;
Mike Stump11289f42009-09-09 15:08:12 +00008611
David Blaikie1f4ff152012-07-16 20:47:22 +00008612 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008613 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008614 return;
Mike Stump11289f42009-09-09 15:08:12 +00008615
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008616 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008617 Diag(Loc, diag::warn_floatingpoint_eq)
8618 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008619}
John McCallca01b222010-01-04 23:21:16 +00008620
John McCall70aa5392010-01-06 05:24:50 +00008621//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8622//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008623
John McCall70aa5392010-01-06 05:24:50 +00008624namespace {
John McCallca01b222010-01-04 23:21:16 +00008625
John McCall70aa5392010-01-06 05:24:50 +00008626/// Structure recording the 'active' range of an integer-valued
8627/// expression.
8628struct IntRange {
8629 /// The number of bits active in the int.
8630 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008631
John McCall70aa5392010-01-06 05:24:50 +00008632 /// True if the int is known not to have negative values.
8633 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008634
John McCall70aa5392010-01-06 05:24:50 +00008635 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008636 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008637
John McCall817d4af2010-11-10 23:38:19 +00008638 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008639 static IntRange forBoolType() {
8640 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008641 }
8642
John McCall817d4af2010-11-10 23:38:19 +00008643 /// Returns the range of an opaque value of the given integral type.
8644 static IntRange forValueOfType(ASTContext &C, QualType T) {
8645 return forValueOfCanonicalType(C,
8646 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008647 }
8648
John McCall817d4af2010-11-10 23:38:19 +00008649 /// Returns the range of an opaque value of a canonical integral type.
8650 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008651 assert(T->isCanonicalUnqualified());
8652
8653 if (const VectorType *VT = dyn_cast<VectorType>(T))
8654 T = VT->getElementType().getTypePtr();
8655 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8656 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008657 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8658 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008659
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008660 if (!C.getLangOpts().CPlusPlus) {
8661 // For enum types in C code, use the underlying datatype.
8662 if (const EnumType *ET = dyn_cast<EnumType>(T))
8663 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8664 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8665 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008666 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008667 // In C++11, enums can have a fixed underlying type. Use this type to
8668 // compute the range.
8669 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008670 return IntRange(C.getIntWidth(QualType(T, 0)),
8671 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008672 }
John McCall18a2c2c2010-11-09 22:22:12 +00008673
David Majnemer6a426652013-06-07 22:07:20 +00008674 unsigned NumPositive = Enum->getNumPositiveBits();
8675 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008676
David Majnemer6a426652013-06-07 22:07:20 +00008677 if (NumNegative == 0)
8678 return IntRange(NumPositive, true/*NonNegative*/);
8679 else
8680 return IntRange(std::max(NumPositive + 1, NumNegative),
8681 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008682 }
John McCall70aa5392010-01-06 05:24:50 +00008683
8684 const BuiltinType *BT = cast<BuiltinType>(T);
8685 assert(BT->isInteger());
8686
8687 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8688 }
8689
John McCall817d4af2010-11-10 23:38:19 +00008690 /// Returns the "target" range of a canonical integral type, i.e.
8691 /// the range of values expressible in the type.
8692 ///
8693 /// This matches forValueOfCanonicalType except that enums have the
8694 /// full range of their type, not the range of their enumerators.
8695 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8696 assert(T->isCanonicalUnqualified());
8697
8698 if (const VectorType *VT = dyn_cast<VectorType>(T))
8699 T = VT->getElementType().getTypePtr();
8700 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8701 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008702 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8703 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008704 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008705 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008706
8707 const BuiltinType *BT = cast<BuiltinType>(T);
8708 assert(BT->isInteger());
8709
8710 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8711 }
8712
8713 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008714 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008715 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008716 L.NonNegative && R.NonNegative);
8717 }
8718
John McCall817d4af2010-11-10 23:38:19 +00008719 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008720 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008721 return IntRange(std::min(L.Width, R.Width),
8722 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008723 }
8724};
8725
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008726} // namespace
8727
8728static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8729 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008730 if (value.isSigned() && value.isNegative())
8731 return IntRange(value.getMinSignedBits(), false);
8732
8733 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008734 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008735
8736 // isNonNegative() just checks the sign bit without considering
8737 // signedness.
8738 return IntRange(value.getActiveBits(), true);
8739}
8740
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008741static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8742 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008743 if (result.isInt())
8744 return GetValueRange(C, result.getInt(), MaxWidth);
8745
8746 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008747 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8748 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8749 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8750 R = IntRange::join(R, El);
8751 }
John McCall70aa5392010-01-06 05:24:50 +00008752 return R;
8753 }
8754
8755 if (result.isComplexInt()) {
8756 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8757 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8758 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008759 }
8760
8761 // This can happen with lossless casts to intptr_t of "based" lvalues.
8762 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008763 // FIXME: The only reason we need to pass the type in here is to get
8764 // the sign right on this one case. It would be nice if APValue
8765 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008766 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008767 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008768}
John McCall70aa5392010-01-06 05:24:50 +00008769
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008770static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008771 QualType Ty = E->getType();
8772 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8773 Ty = AtomicRHS->getValueType();
8774 return Ty;
8775}
8776
John McCall70aa5392010-01-06 05:24:50 +00008777/// Pseudo-evaluate the given integer expression, estimating the
8778/// range of values it might take.
8779///
8780/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008781static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008782 E = E->IgnoreParens();
8783
8784 // Try a full evaluation first.
8785 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008786 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008787 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008788
8789 // I think we only want to look through implicit casts here; if the
8790 // user has an explicit widening cast, we should treat the value as
8791 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008792 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008793 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008794 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8795
Eli Friedmane6d33952013-07-08 20:20:06 +00008796 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008797
George Burgess IVdf1ed002016-01-13 01:52:39 +00008798 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8799 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008800
John McCall70aa5392010-01-06 05:24:50 +00008801 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008802 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008803 return OutputTypeRange;
8804
8805 IntRange SubRange
8806 = GetExprRange(C, CE->getSubExpr(),
8807 std::min(MaxWidth, OutputTypeRange.Width));
8808
8809 // Bail out if the subexpr's range is as wide as the cast type.
8810 if (SubRange.Width >= OutputTypeRange.Width)
8811 return OutputTypeRange;
8812
8813 // Otherwise, we take the smaller width, and we're non-negative if
8814 // either the output type or the subexpr is.
8815 return IntRange(SubRange.Width,
8816 SubRange.NonNegative || OutputTypeRange.NonNegative);
8817 }
8818
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008819 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008820 // If we can fold the condition, just take that operand.
8821 bool CondResult;
8822 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8823 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8824 : CO->getFalseExpr(),
8825 MaxWidth);
8826
8827 // Otherwise, conservatively merge.
8828 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8829 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8830 return IntRange::join(L, R);
8831 }
8832
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008833 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008834 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008835 case BO_Cmp:
8836 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008837
8838 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008839 case BO_LAnd:
8840 case BO_LOr:
8841 case BO_LT:
8842 case BO_GT:
8843 case BO_LE:
8844 case BO_GE:
8845 case BO_EQ:
8846 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008847 return IntRange::forBoolType();
8848
John McCallc3688382011-07-13 06:35:24 +00008849 // The type of the assignments is the type of the LHS, so the RHS
8850 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008851 case BO_MulAssign:
8852 case BO_DivAssign:
8853 case BO_RemAssign:
8854 case BO_AddAssign:
8855 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008856 case BO_XorAssign:
8857 case BO_OrAssign:
8858 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008859 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008860
John McCallc3688382011-07-13 06:35:24 +00008861 // Simple assignments just pass through the RHS, which will have
8862 // been coerced to the LHS type.
8863 case BO_Assign:
8864 // TODO: bitfields?
8865 return GetExprRange(C, BO->getRHS(), MaxWidth);
8866
John McCall70aa5392010-01-06 05:24:50 +00008867 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008868 case BO_PtrMemD:
8869 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008870 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008871
John McCall2ce81ad2010-01-06 22:07:33 +00008872 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008873 case BO_And:
8874 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008875 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8876 GetExprRange(C, BO->getRHS(), MaxWidth));
8877
John McCall70aa5392010-01-06 05:24:50 +00008878 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008879 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008880 // ...except that we want to treat '1 << (blah)' as logically
8881 // positive. It's an important idiom.
8882 if (IntegerLiteral *I
8883 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8884 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008885 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008886 return IntRange(R.Width, /*NonNegative*/ true);
8887 }
8888 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008889 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00008890
John McCalle3027922010-08-25 11:45:40 +00008891 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008892 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008893
John McCall2ce81ad2010-01-06 22:07:33 +00008894 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008895 case BO_Shr:
8896 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008897 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8898
8899 // If the shift amount is a positive constant, drop the width by
8900 // that much.
8901 llvm::APSInt shift;
8902 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8903 shift.isNonNegative()) {
8904 unsigned zext = shift.getZExtValue();
8905 if (zext >= L.Width)
8906 L.Width = (L.NonNegative ? 0 : 1);
8907 else
8908 L.Width -= zext;
8909 }
8910
8911 return L;
8912 }
8913
8914 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008915 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008916 return GetExprRange(C, BO->getRHS(), MaxWidth);
8917
John McCall2ce81ad2010-01-06 22:07:33 +00008918 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008919 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008920 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008921 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008922 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008923
John McCall51431812011-07-14 22:39:48 +00008924 // The width of a division result is mostly determined by the size
8925 // of the LHS.
8926 case BO_Div: {
8927 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008928 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008929 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8930
8931 // If the divisor is constant, use that.
8932 llvm::APSInt divisor;
8933 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8934 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8935 if (log2 >= L.Width)
8936 L.Width = (L.NonNegative ? 0 : 1);
8937 else
8938 L.Width = std::min(L.Width - log2, MaxWidth);
8939 return L;
8940 }
8941
8942 // Otherwise, just use the LHS's width.
8943 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8944 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8945 }
8946
8947 // The result of a remainder can't be larger than the result of
8948 // either side.
8949 case BO_Rem: {
8950 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008951 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008952 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8953 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8954
8955 IntRange meet = IntRange::meet(L, R);
8956 meet.Width = std::min(meet.Width, MaxWidth);
8957 return meet;
8958 }
8959
8960 // The default behavior is okay for these.
8961 case BO_Mul:
8962 case BO_Add:
8963 case BO_Xor:
8964 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008965 break;
8966 }
8967
John McCall51431812011-07-14 22:39:48 +00008968 // The default case is to treat the operation as if it were closed
8969 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008970 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8971 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8972 return IntRange::join(L, R);
8973 }
8974
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008975 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008976 switch (UO->getOpcode()) {
8977 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008978 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008979 return IntRange::forBoolType();
8980
8981 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008982 case UO_Deref:
8983 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008984 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008985
8986 default:
8987 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8988 }
8989 }
8990
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008991 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008992 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8993
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008994 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008995 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008996 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008997
Eli Friedmane6d33952013-07-08 20:20:06 +00008998 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008999}
John McCall263a48b2010-01-04 23:31:57 +00009000
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009001static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00009002 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00009003}
9004
John McCall263a48b2010-01-04 23:31:57 +00009005/// Checks whether the given value, which currently has the given
9006/// source semantics, has the same value when coerced through the
9007/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009008static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9009 const llvm::fltSemantics &Src,
9010 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009011 llvm::APFloat truncated = value;
9012
9013 bool ignored;
9014 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9015 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9016
9017 return truncated.bitwiseIsEqual(value);
9018}
9019
9020/// Checks whether the given value, which currently has the given
9021/// source semantics, has the same value when coerced through the
9022/// target semantics.
9023///
9024/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009025static bool IsSameFloatAfterCast(const APValue &value,
9026 const llvm::fltSemantics &Src,
9027 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00009028 if (value.isFloat())
9029 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9030
9031 if (value.isVector()) {
9032 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9033 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9034 return false;
9035 return true;
9036 }
9037
9038 assert(value.isComplexFloat());
9039 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9040 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9041}
9042
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009043static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009044
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009045static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00009046 // Suppress cases where we are comparing against an enum constant.
9047 if (const DeclRefExpr *DR =
9048 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9049 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00009050 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009051
9052 // Suppress cases where the '0' value is expanded from a macro.
9053 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00009054 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00009055
Roman Lebedev6de129e2017-10-15 20:13:17 +00009056 return false;
9057}
9058
Richard Smith692f66ab2017-12-06 19:23:19 +00009059static bool isKnownToHaveUnsignedValue(Expr *E) {
9060 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00009061 (!E->getType()->isSignedIntegerType() ||
9062 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9063}
9064
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009065namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00009066/// The promoted range of values of a type. In general this has the
9067/// following structure:
9068///
9069/// |-----------| . . . |-----------|
9070/// ^ ^ ^ ^
9071/// Min HoleMin HoleMax Max
9072///
9073/// ... where there is only a hole if a signed type is promoted to unsigned
9074/// (in which case Min and Max are the smallest and largest representable
9075/// values).
9076struct PromotedRange {
9077 // Min, or HoleMax if there is a hole.
9078 llvm::APSInt PromotedMin;
9079 // Max, or HoleMin if there is a hole.
9080 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009081
Richard Smitha5370fb2017-12-08 22:57:11 +00009082 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9083 if (R.Width == 0)
9084 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9085 else if (R.Width >= BitWidth && !Unsigned) {
9086 // Promotion made the type *narrower*. This happens when promoting
9087 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9088 // Treat all values of 'signed int' as being in range for now.
9089 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9090 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9091 } else {
9092 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9093 .extOrTrunc(BitWidth);
9094 PromotedMin.setIsUnsigned(Unsigned);
9095
9096 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9097 .extOrTrunc(BitWidth);
9098 PromotedMax.setIsUnsigned(Unsigned);
9099 }
9100 }
9101
9102 // Determine whether this range is contiguous (has no hole).
9103 bool isContiguous() const { return PromotedMin <= PromotedMax; }
9104
9105 // Where a constant value is within the range.
9106 enum ComparisonResult {
9107 LT = 0x1,
9108 LE = 0x2,
9109 GT = 0x4,
9110 GE = 0x8,
9111 EQ = 0x10,
9112 NE = 0x20,
9113 InRangeFlag = 0x40,
9114
9115 Less = LE | LT | NE,
9116 Min = LE | InRangeFlag,
9117 InRange = InRangeFlag,
9118 Max = GE | InRangeFlag,
9119 Greater = GE | GT | NE,
9120
9121 OnlyValue = LE | GE | EQ | InRangeFlag,
9122 InHole = NE
9123 };
9124
9125 ComparisonResult compare(const llvm::APSInt &Value) const {
9126 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9127 Value.isUnsigned() == PromotedMin.isUnsigned());
9128 if (!isContiguous()) {
9129 assert(Value.isUnsigned() && "discontiguous range for signed compare");
9130 if (Value.isMinValue()) return Min;
9131 if (Value.isMaxValue()) return Max;
9132 if (Value >= PromotedMin) return InRange;
9133 if (Value <= PromotedMax) return InRange;
9134 return InHole;
9135 }
9136
9137 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9138 case -1: return Less;
9139 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9140 case 1:
9141 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9142 case -1: return InRange;
9143 case 0: return Max;
9144 case 1: return Greater;
9145 }
9146 }
9147
9148 llvm_unreachable("impossible compare result");
9149 }
9150
Richard Smithc70f1d62017-12-14 15:16:18 +00009151 static llvm::Optional<StringRef>
9152 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9153 if (Op == BO_Cmp) {
9154 ComparisonResult LTFlag = LT, GTFlag = GT;
9155 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9156
9157 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9158 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9159 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9160 return llvm::None;
9161 }
9162
Richard Smitha5370fb2017-12-08 22:57:11 +00009163 ComparisonResult TrueFlag, FalseFlag;
9164 if (Op == BO_EQ) {
9165 TrueFlag = EQ;
9166 FalseFlag = NE;
9167 } else if (Op == BO_NE) {
9168 TrueFlag = NE;
9169 FalseFlag = EQ;
9170 } else {
9171 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9172 TrueFlag = LT;
9173 FalseFlag = GE;
9174 } else {
9175 TrueFlag = GT;
9176 FalseFlag = LE;
9177 }
9178 if (Op == BO_GE || Op == BO_LE)
9179 std::swap(TrueFlag, FalseFlag);
9180 }
9181 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009182 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00009183 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00009184 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00009185 return llvm::None;
9186 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00009187};
John McCallcc7e5bf2010-05-06 08:58:33 +00009188}
9189
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009190static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00009191 // Strip off implicit integral promotions.
9192 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009193 if (ICE->getCastKind() != CK_IntegralCast &&
9194 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00009195 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00009196 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00009197 }
9198
9199 return E->getType()->isEnumeralType();
9200}
9201
Richard Smith692f66ab2017-12-06 19:23:19 +00009202static int classifyConstantValue(Expr *Constant) {
9203 // The values of this enumeration are used in the diagnostics
9204 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9205 enum ConstantValueKind {
9206 Miscellaneous = 0,
9207 LiteralTrue,
9208 LiteralFalse
9209 };
9210 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9211 return BL->getValue() ? ConstantValueKind::LiteralTrue
9212 : ConstantValueKind::LiteralFalse;
9213 return ConstantValueKind::Miscellaneous;
9214}
9215
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009216static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9217 Expr *Constant, Expr *Other,
9218 const llvm::APSInt &Value,
9219 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009220 if (S.inTemplateInstantiation())
9221 return false;
9222
Richard Smitha5370fb2017-12-08 22:57:11 +00009223 Expr *OriginalOther = Other;
9224
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009225 Constant = Constant->IgnoreParenImpCasts();
9226 Other = Other->IgnoreParenImpCasts();
9227
Richard Smitha5370fb2017-12-08 22:57:11 +00009228 // Suppress warnings on tautological comparisons between values of the same
9229 // enumeration type. There are only two ways we could warn on this:
9230 // - If the constant is outside the range of representable values of
9231 // the enumeration. In such a case, we should warn about the cast
9232 // to enumeration type, not about the comparison.
9233 // - If the constant is the maximum / minimum in-range value. For an
9234 // enumeratin type, such comparisons can be meaningful and useful.
9235 if (Constant->getType()->isEnumeralType() &&
9236 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9237 return false;
9238
Hans Wennborg5bb88e02017-12-08 05:19:12 +00009239 // TODO: Investigate using GetExprRange() to get tighter bounds
9240 // on the bit ranges.
9241 QualType OtherT = Other->getType();
9242 if (const auto *AT = OtherT->getAs<AtomicType>())
9243 OtherT = AT->getValueType();
9244 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9245
9246 // Whether we're treating Other as being a bool because of the form of
9247 // expression despite it having another type (typically 'int' in C).
9248 bool OtherIsBooleanDespiteType =
9249 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9250 if (OtherIsBooleanDespiteType)
9251 OtherRange = IntRange::forBoolType();
9252
Richard Smitha5370fb2017-12-08 22:57:11 +00009253 // Determine the promoted range of the other type and see if a comparison of
9254 // the constant against that range is tautological.
9255 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9256 Value.isUnsigned());
9257 auto Cmp = OtherPromotedRange.compare(Value);
9258 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9259 if (!Result)
9260 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009261
Richard Smitha5370fb2017-12-08 22:57:11 +00009262 // Suppress the diagnostic for an in-range comparison if the constant comes
9263 // from a macro or enumerator. We don't want to diagnose
9264 //
9265 // some_long_value <= INT_MAX
9266 //
9267 // when sizeof(int) == sizeof(long).
9268 bool InRange = Cmp & PromotedRange::InRangeFlag;
9269 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9270 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009271
9272 // If this is a comparison to an enum constant, include that
9273 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009274 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009275 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9276 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9277
Richard Smitha5370fb2017-12-08 22:57:11 +00009278 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009279 SmallString<64> PrettySourceValue;
9280 llvm::raw_svector_ostream OS(PrettySourceValue);
9281 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009282 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009283 else
9284 OS << Value;
9285
Richard Smitha5370fb2017-12-08 22:57:11 +00009286 // FIXME: We use a somewhat different formatting for the in-range cases and
9287 // cases involving boolean values for historical reasons. We should pick a
9288 // consistent way of presenting these diagnostics.
9289 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9290 S.DiagRuntimeBehavior(
9291 E->getOperatorLoc(), E,
9292 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9293 : diag::warn_tautological_bool_compare)
9294 << OS.str() << classifyConstantValue(Constant)
9295 << OtherT << OtherIsBooleanDespiteType << *Result
9296 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9297 } else {
9298 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9299 ? (HasEnumType(OriginalOther)
9300 ? diag::warn_unsigned_enum_always_true_comparison
9301 : diag::warn_unsigned_always_true_comparison)
9302 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009303
Richard Smitha5370fb2017-12-08 22:57:11 +00009304 S.Diag(E->getOperatorLoc(), Diag)
9305 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9306 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9307 }
9308
9309 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009310}
9311
John McCallcc7e5bf2010-05-06 08:58:33 +00009312/// Analyze the operands of the given comparison. Implements the
9313/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009314static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009315 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9316 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009317}
John McCall263a48b2010-01-04 23:31:57 +00009318
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009319/// Implements -Wsign-compare.
John McCallca01b222010-01-04 23:21:16 +00009320///
Richard Trieu82402a02011-09-15 21:56:47 +00009321/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009322static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009323 // The type the comparison is being performed in.
9324 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009325
9326 // Only analyze comparison operators where both sides have been converted to
9327 // the same type.
9328 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9329 return AnalyzeImpConvsInComparison(S, E);
9330
9331 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009332 if (E->isValueDependent())
9333 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009334
Roman Lebedev6de129e2017-10-15 20:13:17 +00009335 Expr *LHS = E->getLHS();
9336 Expr *RHS = E->getRHS();
9337
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009338 if (T->isIntegralType(S.Context)) {
9339 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009340 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009341
Roman Lebedev6de129e2017-10-15 20:13:17 +00009342 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9343 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009344
Roman Lebedev6de129e2017-10-15 20:13:17 +00009345 // We don't care about expressions whose result is a constant.
9346 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9347 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009348
Roman Lebedev6de129e2017-10-15 20:13:17 +00009349 // We only care about expressions where just one side is literal
9350 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9351 // Is the constant on the RHS or LHS?
9352 const bool RhsConstant = IsRHSIntegralLiteral;
9353 Expr *Const = RhsConstant ? RHS : LHS;
9354 Expr *Other = RhsConstant ? LHS : RHS;
9355 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9356
9357 // Check whether an integer constant comparison results in a value
9358 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009359 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9360 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009361 }
9362 }
9363
9364 if (!T->hasUnsignedIntegerRepresentation()) {
9365 // We don't do anything special if this isn't an unsigned integral
9366 // comparison: we're only interested in integral comparisons, and
9367 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009368 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009369 }
9370
9371 LHS = LHS->IgnoreParenImpCasts();
9372 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009373
Alex Lorenzb57409f2018-02-07 20:45:39 +00009374 if (!S.getLangOpts().CPlusPlus) {
9375 // Avoid warning about comparison of integers with different signs when
9376 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9377 // the type of `E`.
9378 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9379 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9380 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9381 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9382 }
9383
John McCallcc7e5bf2010-05-06 08:58:33 +00009384 // Check to see if one of the (unmodified) operands is of different
9385 // signedness.
9386 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009387 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9388 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009389 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009390 signedOperand = LHS;
9391 unsignedOperand = RHS;
9392 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9393 signedOperand = RHS;
9394 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009395 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009396 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009397 }
9398
John McCallcc7e5bf2010-05-06 08:58:33 +00009399 // Otherwise, calculate the effective range of the signed operand.
9400 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009401
John McCallcc7e5bf2010-05-06 08:58:33 +00009402 // Go ahead and analyze implicit conversions in the operands. Note
9403 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009404 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9405 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009406
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009407 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009408 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009409 return;
John McCallca01b222010-01-04 23:21:16 +00009410
9411 // For (in)equality comparisons, if the unsigned operand is a
9412 // constant which cannot collide with a overflowed signed operand,
9413 // then reinterpreting the signed operand as unsigned will not
9414 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009415 if (E->isEqualityOp()) {
9416 unsigned comparisonWidth = S.Context.getIntWidth(T);
9417 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009418
John McCallcc7e5bf2010-05-06 08:58:33 +00009419 // We should never be unable to prove that the unsigned operand is
9420 // non-negative.
9421 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9422
9423 if (unsignedRange.Width < comparisonWidth)
9424 return;
9425 }
9426
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009427 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9428 S.PDiag(diag::warn_mixed_sign_comparison)
9429 << LHS->getType() << RHS->getType()
9430 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009431}
9432
John McCall1f425642010-11-11 03:21:53 +00009433/// Analyzes an attempt to assign the given value to a bitfield.
9434///
9435/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009436static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9437 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009438 assert(Bitfield->isBitField());
9439 if (Bitfield->isInvalidDecl())
9440 return false;
9441
John McCalldeebbcf2010-11-11 05:33:51 +00009442 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009443 QualType BitfieldType = Bitfield->getType();
9444 if (BitfieldType->isBooleanType())
9445 return false;
9446
9447 if (BitfieldType->isEnumeralType()) {
9448 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9449 // If the underlying enum type was not explicitly specified as an unsigned
9450 // type and the enum contain only positive values, MSVC++ will cause an
9451 // inconsistency by storing this as a signed type.
9452 if (S.getLangOpts().CPlusPlus11 &&
9453 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9454 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9455 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9456 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9457 << BitfieldEnumDecl->getNameAsString();
9458 }
9459 }
9460
John McCalldeebbcf2010-11-11 05:33:51 +00009461 if (Bitfield->getType()->isBooleanType())
9462 return false;
9463
Douglas Gregor789adec2011-02-04 13:09:01 +00009464 // Ignore value- or type-dependent expressions.
9465 if (Bitfield->getBitWidth()->isValueDependent() ||
9466 Bitfield->getBitWidth()->isTypeDependent() ||
9467 Init->isValueDependent() ||
9468 Init->isTypeDependent())
9469 return false;
9470
John McCall1f425642010-11-11 03:21:53 +00009471 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009472 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009473
Richard Smith5fab0c92011-12-28 19:48:30 +00009474 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009475 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9476 Expr::SE_AllowSideEffects)) {
9477 // The RHS is not constant. If the RHS has an enum type, make sure the
9478 // bitfield is wide enough to hold all the values of the enum without
9479 // truncation.
9480 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9481 EnumDecl *ED = EnumTy->getDecl();
9482 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9483
9484 // Enum types are implicitly signed on Windows, so check if there are any
9485 // negative enumerators to see if the enum was intended to be signed or
9486 // not.
9487 bool SignedEnum = ED->getNumNegativeBits() > 0;
9488
9489 // Check for surprising sign changes when assigning enum values to a
9490 // bitfield of different signedness. If the bitfield is signed and we
9491 // have exactly the right number of bits to store this unsigned enum,
9492 // suggest changing the enum to an unsigned type. This typically happens
9493 // on Windows where unfixed enums always use an underlying type of 'int'.
9494 unsigned DiagID = 0;
9495 if (SignedEnum && !SignedBitfield) {
9496 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9497 } else if (SignedBitfield && !SignedEnum &&
9498 ED->getNumPositiveBits() == FieldWidth) {
9499 DiagID = diag::warn_signed_bitfield_enum_conversion;
9500 }
9501
9502 if (DiagID) {
9503 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9504 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9505 SourceRange TypeRange =
9506 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9507 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9508 << SignedEnum << TypeRange;
9509 }
9510
9511 // Compute the required bitwidth. If the enum has negative values, we need
9512 // one more bit than the normal number of positive bits to represent the
9513 // sign bit.
9514 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9515 ED->getNumNegativeBits())
9516 : ED->getNumPositiveBits();
9517
9518 // Check the bitwidth.
9519 if (BitsNeeded > FieldWidth) {
9520 Expr *WidthExpr = Bitfield->getBitWidth();
9521 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9522 << Bitfield << ED;
9523 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9524 << BitsNeeded << ED << WidthExpr->getSourceRange();
9525 }
9526 }
9527
John McCall1f425642010-11-11 03:21:53 +00009528 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009529 }
John McCall1f425642010-11-11 03:21:53 +00009530
John McCall1f425642010-11-11 03:21:53 +00009531 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009532
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009533 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009534 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009535 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9536 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009537
John McCall1f425642010-11-11 03:21:53 +00009538 if (OriginalWidth <= FieldWidth)
9539 return false;
9540
Eli Friedmanc267a322012-01-26 23:11:39 +00009541 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009542 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009543 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009544
Eli Friedmanc267a322012-01-26 23:11:39 +00009545 // Check whether the stored value is equal to the original value.
9546 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009547 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009548 return false;
9549
Eli Friedmanc267a322012-01-26 23:11:39 +00009550 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009551 // therefore don't strictly fit into a signed bitfield of width 1.
9552 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009553 return false;
9554
John McCall1f425642010-11-11 03:21:53 +00009555 std::string PrettyValue = Value.toString(10);
9556 std::string PrettyTrunc = TruncatedValue.toString(10);
9557
9558 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9559 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9560 << Init->getSourceRange();
9561
9562 return true;
9563}
9564
John McCalld2a53122010-11-09 23:24:47 +00009565/// Analyze the given simple or compound assignment for warning-worthy
9566/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009567static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009568 // Just recurse on the LHS.
9569 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9570
9571 // We want to recurse on the RHS as normal unless we're assigning to
9572 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009573 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009574 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009575 E->getOperatorLoc())) {
9576 // Recurse, ignoring any implicit conversions on the RHS.
9577 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9578 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009579 }
9580 }
9581
9582 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9583}
9584
John McCall263a48b2010-01-04 23:31:57 +00009585/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009586static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9587 SourceLocation CContext, unsigned diag,
9588 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009589 if (pruneControlFlow) {
9590 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9591 S.PDiag(diag)
9592 << SourceType << T << E->getSourceRange()
9593 << SourceRange(CContext));
9594 return;
9595 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009596 S.Diag(E->getExprLoc(), diag)
9597 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9598}
9599
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009600/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009601static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9602 SourceLocation CContext,
9603 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009604 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009605}
9606
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009607/// Analyze the given compound assignment for the possible losing of
9608/// floating-point precision.
9609static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9610 assert(isa<CompoundAssignOperator>(E) &&
9611 "Must be compound assignment operation");
9612 // Recurse on the LHS and RHS in here
9613 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9614 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9615
9616 // Now check the outermost expression
9617 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9618 const auto *RBT = cast<CompoundAssignOperator>(E)
9619 ->getComputationResultType()
9620 ->getAs<BuiltinType>();
9621
9622 // If both source and target are floating points.
9623 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9624 // Builtin FP kinds are ordered by increasing FP rank.
9625 if (ResultBT->getKind() < RBT->getKind())
9626 // We don't want to warn for system macro.
9627 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9628 // warn about dropping FP rank.
9629 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9630 E->getOperatorLoc(),
9631 diag::warn_impcast_float_result_precision);
9632}
Richard Trieube234c32016-04-21 21:04:55 +00009633
9634/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009635static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9636 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009637 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009638 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009639
9640 Expr *InnerE = E->IgnoreParenImpCasts();
9641 // We also want to warn on, e.g., "int i = -1.234"
9642 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9643 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9644 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9645
9646 const bool IsLiteral =
9647 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9648
9649 llvm::APFloat Value(0.0);
9650 bool IsConstant =
9651 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9652 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009653 return DiagnoseImpCast(S, E, T, CContext,
9654 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009655 }
9656
Chandler Carruth016ef402011-04-10 08:36:24 +00009657 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009658
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009659 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9660 T->hasUnsignedIntegerRepresentation());
Erich Keanea4c48c62018-05-08 21:26:21 +00009661 llvm::APFloat::opStatus Result = Value.convertToInteger(
9662 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
9663
9664 if (Result == llvm::APFloat::opOK && isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009665 if (IsLiteral) return;
9666 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9667 PruneWarnings);
9668 }
9669
Erich Keanea4c48c62018-05-08 21:26:21 +00009670 // Conversion of a floating-point value to a non-bool integer where the
9671 // integral part cannot be represented by the integer type is undefined.
9672 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
9673 return DiagnoseImpCast(
9674 S, E, T, CContext,
9675 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
9676 : diag::warn_impcast_float_to_integer_out_of_range);
9677
Richard Trieube234c32016-04-21 21:04:55 +00009678 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009679 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009680 // Warn on floating point literal to integer.
9681 DiagID = diag::warn_impcast_literal_float_to_integer;
9682 } else if (IntegerValue == 0) {
9683 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9684 return DiagnoseImpCast(S, E, T, CContext,
9685 diag::warn_impcast_float_integer, PruneWarnings);
9686 }
9687 // Warn on non-zero to zero conversion.
9688 DiagID = diag::warn_impcast_float_to_integer_zero;
9689 } else {
9690 if (IntegerValue.isUnsigned()) {
9691 if (!IntegerValue.isMaxValue()) {
9692 return DiagnoseImpCast(S, E, T, CContext,
9693 diag::warn_impcast_float_integer, PruneWarnings);
9694 }
9695 } else { // IntegerValue.isSigned()
9696 if (!IntegerValue.isMaxSignedValue() &&
9697 !IntegerValue.isMinSignedValue()) {
9698 return DiagnoseImpCast(S, E, T, CContext,
9699 diag::warn_impcast_float_integer, PruneWarnings);
9700 }
9701 }
9702 // Warn on evaluatable floating point expression to integer conversion.
9703 DiagID = diag::warn_impcast_float_to_integer;
9704 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009705
Eli Friedman07185912013-08-29 23:44:43 +00009706 // FIXME: Force the precision of the source value down so we don't print
9707 // digits which are usually useless (we don't really care here if we
9708 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9709 // would automatically print the shortest representation, but it's a bit
9710 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009711 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009712 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9713 precision = (precision * 59 + 195) / 196;
9714 Value.toString(PrettySourceValue, precision);
9715
David Blaikie9b88cc02012-05-15 17:18:27 +00009716 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009717 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009718 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009719 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009720 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009721
Richard Trieube234c32016-04-21 21:04:55 +00009722 if (PruneWarnings) {
9723 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9724 S.PDiag(DiagID)
9725 << E->getType() << T.getUnqualifiedType()
9726 << PrettySourceValue << PrettyTargetValue
9727 << E->getSourceRange() << SourceRange(CContext));
9728 } else {
9729 S.Diag(E->getExprLoc(), DiagID)
9730 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9731 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9732 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009733}
9734
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009735static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9736 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009737 if (!Range.Width) return "0";
9738
9739 llvm::APSInt ValueInRange = Value;
9740 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009741 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009742 return ValueInRange.toString(10);
9743}
9744
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009745static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009746 if (!isa<ImplicitCastExpr>(Ex))
9747 return false;
9748
9749 Expr *InnerE = Ex->IgnoreParenImpCasts();
9750 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9751 const Type *Source =
9752 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9753 if (Target->isDependentType())
9754 return false;
9755
9756 const BuiltinType *FloatCandidateBT =
9757 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9758 const Type *BoolCandidateType = ToBool ? Target : Source;
9759
9760 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9761 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9762}
9763
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009764static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9765 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009766 unsigned NumArgs = TheCall->getNumArgs();
9767 for (unsigned i = 0; i < NumArgs; ++i) {
9768 Expr *CurrA = TheCall->getArg(i);
9769 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9770 continue;
9771
9772 bool IsSwapped = ((i > 0) &&
9773 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9774 IsSwapped |= ((i < (NumArgs - 1)) &&
9775 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9776 if (IsSwapped) {
9777 // Warn on this floating-point to bool conversion.
9778 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9779 CurrA->getType(), CC,
9780 diag::warn_impcast_floating_point_to_bool);
9781 }
9782 }
9783}
9784
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009785static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9786 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009787 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9788 E->getExprLoc()))
9789 return;
9790
Richard Trieu09d6b802016-01-08 23:35:06 +00009791 // Don't warn on functions which have return type nullptr_t.
9792 if (isa<CallExpr>(E))
9793 return;
9794
Richard Trieu5b993502014-10-15 03:42:06 +00009795 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9796 const Expr::NullPointerConstantKind NullKind =
9797 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9798 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9799 return;
9800
9801 // Return if target type is a safe conversion.
9802 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9803 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9804 return;
9805
9806 SourceLocation Loc = E->getSourceRange().getBegin();
9807
Richard Trieu0a5e1662016-02-13 00:58:53 +00009808 // Venture through the macro stacks to get to the source of macro arguments.
9809 // The new location is a better location than the complete location that was
9810 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009811 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9812 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009813
Richard Trieu5b993502014-10-15 03:42:06 +00009814 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009815 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9816 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9817 Loc, S.SourceMgr, S.getLangOpts());
9818 if (MacroName == "NULL")
Richard Smithb5f81712018-04-30 05:25:48 +00009819 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
Richard Trieu5b993502014-10-15 03:42:06 +00009820 }
9821
9822 // Only warn if the null and context location are in the same macro expansion.
9823 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9824 return;
9825
9826 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009827 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009828 << FixItHint::CreateReplacement(Loc,
9829 S.getFixItZeroLiteralForType(T, Loc));
9830}
9831
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009832static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9833 ObjCArrayLiteral *ArrayLiteral);
9834
9835static void
9836checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9837 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009838
9839/// Check a single element within a collection literal against the
9840/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009841static void checkObjCCollectionLiteralElement(Sema &S,
9842 QualType TargetElementType,
9843 Expr *Element,
9844 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009845 // Skip a bitcast to 'id' or qualified 'id'.
9846 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9847 if (ICE->getCastKind() == CK_BitCast &&
9848 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9849 Element = ICE->getSubExpr();
9850 }
9851
9852 QualType ElementType = Element->getType();
9853 ExprResult ElementResult(Element);
9854 if (ElementType->getAs<ObjCObjectPointerType>() &&
9855 S.CheckSingleAssignmentConstraints(TargetElementType,
9856 ElementResult,
9857 false, false)
9858 != Sema::Compatible) {
9859 S.Diag(Element->getLocStart(),
9860 diag::warn_objc_collection_literal_element)
9861 << ElementType << ElementKind << TargetElementType
9862 << Element->getSourceRange();
9863 }
9864
9865 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9866 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9867 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9868 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9869}
9870
9871/// Check an Objective-C array literal being converted to the given
9872/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009873static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9874 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009875 if (!S.NSArrayDecl)
9876 return;
9877
9878 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9879 if (!TargetObjCPtr)
9880 return;
9881
9882 if (TargetObjCPtr->isUnspecialized() ||
9883 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9884 != S.NSArrayDecl->getCanonicalDecl())
9885 return;
9886
9887 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9888 if (TypeArgs.size() != 1)
9889 return;
9890
9891 QualType TargetElementType = TypeArgs[0];
9892 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9893 checkObjCCollectionLiteralElement(S, TargetElementType,
9894 ArrayLiteral->getElement(I),
9895 0);
9896 }
9897}
9898
9899/// Check an Objective-C dictionary literal being converted to the given
9900/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009901static void
9902checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9903 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009904 if (!S.NSDictionaryDecl)
9905 return;
9906
9907 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9908 if (!TargetObjCPtr)
9909 return;
9910
9911 if (TargetObjCPtr->isUnspecialized() ||
9912 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9913 != S.NSDictionaryDecl->getCanonicalDecl())
9914 return;
9915
9916 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9917 if (TypeArgs.size() != 2)
9918 return;
9919
9920 QualType TargetKeyType = TypeArgs[0];
9921 QualType TargetObjectType = TypeArgs[1];
9922 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9923 auto Element = DictionaryLiteral->getKeyValueElement(I);
9924 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9925 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9926 }
9927}
9928
Richard Trieufc404c72016-02-05 23:02:38 +00009929// Helper function to filter out cases for constant width constant conversion.
9930// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009931static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9932 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009933 // If initializing from a constant, and the constant starts with '0',
9934 // then it is a binary, octal, or hexadecimal. Allow these constants
9935 // to fill all the bits, even if there is a sign change.
9936 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9937 const char FirstLiteralCharacter =
9938 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9939 if (FirstLiteralCharacter == '0')
9940 return false;
9941 }
9942
9943 // If the CC location points to a '{', and the type is char, then assume
9944 // assume it is an array initialization.
9945 if (CC.isValid() && T->isCharType()) {
9946 const char FirstContextCharacter =
9947 S.getSourceManager().getCharacterData(CC)[0];
9948 if (FirstContextCharacter == '{')
9949 return false;
9950 }
9951
9952 return true;
9953}
9954
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009955static void
9956CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9957 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009958 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009959
John McCallcc7e5bf2010-05-06 08:58:33 +00009960 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9961 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9962 if (Source == Target) return;
9963 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009964
Chandler Carruthc22845a2011-07-26 05:40:03 +00009965 // If the conversion context location is invalid don't complain. We also
9966 // don't want to emit a warning if the issue occurs from the expansion of
9967 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9968 // delay this check as long as possible. Once we detect we are in that
9969 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009970 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009971 return;
9972
Richard Trieu021baa32011-09-23 20:10:00 +00009973 // Diagnose implicit casts to bool.
9974 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9975 if (isa<StringLiteral>(E))
9976 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009977 // and expressions, for instance, assert(0 && "error here"), are
9978 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009979 return DiagnoseImpCast(S, E, T, CC,
9980 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009981 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9982 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9983 // This covers the literal expressions that evaluate to Objective-C
9984 // objects.
9985 return DiagnoseImpCast(S, E, T, CC,
9986 diag::warn_impcast_objective_c_literal_to_bool);
9987 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009988 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9989 // Warn on pointer to bool conversion that is always true.
9990 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9991 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009992 }
Richard Trieu021baa32011-09-23 20:10:00 +00009993 }
John McCall263a48b2010-01-04 23:31:57 +00009994
Douglas Gregor5054cb02015-07-07 03:58:22 +00009995 // Check implicit casts from Objective-C collection literals to specialized
9996 // collection types, e.g., NSArray<NSString *> *.
9997 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9998 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9999 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10000 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10001
John McCall263a48b2010-01-04 23:31:57 +000010002 // Strip vector types.
10003 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010004 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010005 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010006 return;
John McCallacf0ee52010-10-08 02:01:28 +000010007 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010008 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010009
Chris Lattneree7286f2011-06-14 04:51:15 +000010010 // If the vector cast is cast between two vectors of the same size, it is
10011 // a bitcast, not a conversion.
10012 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10013 return;
John McCall263a48b2010-01-04 23:31:57 +000010014
10015 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10016 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10017 }
Stephen Canon3ba640d2014-04-03 10:33:25 +000010018 if (auto VecTy = dyn_cast<VectorType>(Target))
10019 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +000010020
10021 // Strip complex types.
10022 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010023 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +000010024 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010025 return;
10026
Tim Northover02416372017-08-08 23:18:05 +000010027 return DiagnoseImpCast(S, E, T, CC,
10028 S.getLangOpts().CPlusPlus
10029 ? diag::err_impcast_complex_scalar
10030 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010031 }
John McCall263a48b2010-01-04 23:31:57 +000010032
10033 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10034 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10035 }
10036
10037 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10038 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10039
10040 // If the source is floating point...
10041 if (SourceBT && SourceBT->isFloatingPoint()) {
10042 // ...and the target is floating point...
10043 if (TargetBT && TargetBT->isFloatingPoint()) {
10044 // ...then warn if we're dropping FP rank.
10045
10046 // Builtin FP kinds are ordered by increasing FP rank.
10047 if (SourceBT->getKind() > TargetBT->getKind()) {
10048 // Don't warn about float constants that are precisely
10049 // representable in the target type.
10050 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +000010051 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +000010052 // Value might be a float, a float vector, or a float complex.
10053 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +000010054 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10055 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +000010056 return;
10057 }
10058
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010059 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010060 return;
10061
John McCallacf0ee52010-10-08 02:01:28 +000010062 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +000010063 }
10064 // ... or possibly if we're increasing rank, too
10065 else if (TargetBT->getKind() > SourceBT->getKind()) {
10066 if (S.SourceMgr.isInSystemMacro(CC))
10067 return;
10068
10069 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +000010070 }
10071 return;
10072 }
10073
Richard Trieube234c32016-04-21 21:04:55 +000010074 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +000010075 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010076 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010077 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +000010078
Richard Trieube234c32016-04-21 21:04:55 +000010079 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +000010080 }
John McCall263a48b2010-01-04 23:31:57 +000010081
Richard Smith54894fd2015-12-30 01:06:52 +000010082 // Detect the case where a call result is converted from floating-point to
10083 // to bool, and the final argument to the call is converted from bool, to
10084 // discover this typo:
10085 //
10086 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
10087 //
10088 // FIXME: This is an incredibly special case; is there some more general
10089 // way to detect this class of misplaced-parentheses bug?
10090 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010091 // Check last argument of function call to see if it is an
10092 // implicit cast from a type matching the type the result
10093 // is being cast to.
10094 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +000010095 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010096 Expr *LastA = CEx->getArg(NumArgs - 1);
10097 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +000010098 if (isa<ImplicitCastExpr>(LastA) &&
10099 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010100 // Warn on this floating-point to bool conversion
10101 DiagnoseImpCast(S, E, T, CC,
10102 diag::warn_impcast_floating_point_to_bool);
10103 }
10104 }
10105 }
John McCall263a48b2010-01-04 23:31:57 +000010106 return;
10107 }
10108
Richard Trieu5b993502014-10-15 03:42:06 +000010109 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +000010110
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010111 S.DiscardMisalignedMemberAddress(Target, E);
10112
David Blaikie9366d2b2012-06-19 21:19:06 +000010113 if (!Source->isIntegerType() || !Target->isIntegerType())
10114 return;
10115
David Blaikie7555b6a2012-05-15 16:56:36 +000010116 // TODO: remove this early return once the false positives for constant->bool
10117 // in templates, macros, etc, are reduced or removed.
10118 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10119 return;
10120
John McCallcc7e5bf2010-05-06 08:58:33 +000010121 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +000010122 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +000010123
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010124 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +000010125 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010126 // TODO: this should happen for bitfield stores, too.
10127 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +000010128 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010129 if (S.SourceMgr.isInSystemMacro(CC))
10130 return;
10131
John McCall18a2c2c2010-11-09 22:22:12 +000010132 std::string PrettySourceValue = Value.toString(10);
10133 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010134
Ted Kremenek33ba9952011-10-22 02:37:33 +000010135 S.DiagRuntimeBehavior(E->getExprLoc(), E,
10136 S.PDiag(diag::warn_impcast_integer_precision_constant)
10137 << PrettySourceValue << PrettyTargetValue
10138 << E->getType() << T << E->getSourceRange()
10139 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +000010140 return;
10141 }
10142
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010143 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10144 if (S.SourceMgr.isInSystemMacro(CC))
10145 return;
10146
David Blaikie9455da02012-04-12 22:40:54 +000010147 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +000010148 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10149 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +000010150 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +000010151 }
10152
Richard Trieudcb55572016-01-29 23:51:16 +000010153 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10154 SourceRange.NonNegative && Source->isSignedIntegerType()) {
10155 // Warn when doing a signed to signed conversion, warn if the positive
10156 // source value is exactly the width of the target type, which will
10157 // cause a negative value to be stored.
10158
10159 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +000010160 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10161 !S.SourceMgr.isInSystemMacro(CC)) {
10162 if (isSameWidthConstantConversion(S, E, T, CC)) {
10163 std::string PrettySourceValue = Value.toString(10);
10164 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +000010165
Richard Trieufc404c72016-02-05 23:02:38 +000010166 S.DiagRuntimeBehavior(
10167 E->getExprLoc(), E,
10168 S.PDiag(diag::warn_impcast_integer_precision_constant)
10169 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10170 << E->getSourceRange() << clang::SourceRange(CC));
10171 return;
Richard Trieudcb55572016-01-29 23:51:16 +000010172 }
10173 }
Richard Trieufc404c72016-02-05 23:02:38 +000010174
Richard Trieudcb55572016-01-29 23:51:16 +000010175 // Fall through for non-constants to give a sign conversion warning.
10176 }
10177
John McCallcc7e5bf2010-05-06 08:58:33 +000010178 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10179 (!TargetRange.NonNegative && SourceRange.NonNegative &&
10180 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010181 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010182 return;
10183
John McCallcc7e5bf2010-05-06 08:58:33 +000010184 unsigned DiagID = diag::warn_impcast_integer_sign;
10185
10186 // Traditionally, gcc has warned about this under -Wsign-compare.
10187 // We also want to warn about it in -Wconversion.
10188 // So if -Wconversion is off, use a completely identical diagnostic
10189 // in the sign-compare group.
10190 // The conditional-checking code will
10191 if (ICContext) {
10192 DiagID = diag::warn_impcast_integer_sign_conditional;
10193 *ICContext = true;
10194 }
10195
John McCallacf0ee52010-10-08 02:01:28 +000010196 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +000010197 }
10198
Douglas Gregora78f1932011-02-22 02:45:07 +000010199 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +000010200 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10201 // type, to give us better diagnostics.
10202 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +000010203 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +000010204 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10205 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10206 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10207 SourceType = S.Context.getTypeDeclType(Enum);
10208 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10209 }
10210 }
10211
Douglas Gregora78f1932011-02-22 02:45:07 +000010212 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10213 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +000010214 if (SourceEnum->getDecl()->hasNameForLinkage() &&
10215 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010216 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +000010217 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010218 return;
10219
Douglas Gregor364f7db2011-03-12 00:14:31 +000010220 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +000010221 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +000010222 }
John McCall263a48b2010-01-04 23:31:57 +000010223}
10224
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010225static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10226 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010227
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010228static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10229 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010230 E = E->IgnoreParenImpCasts();
10231
10232 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +000010233 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010234
John McCallacf0ee52010-10-08 02:01:28 +000010235 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010236 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010237 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +000010238}
10239
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010240static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10241 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +000010242 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +000010243
10244 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +000010245 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10246 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010247
10248 // If -Wconversion would have warned about either of the candidates
10249 // for a signedness conversion to the context type...
10250 if (!Suspicious) return;
10251
10252 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000010253 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010254 return;
10255
John McCallcc7e5bf2010-05-06 08:58:33 +000010256 // ...then check whether it would have warned about either of the
10257 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010258 if (E->getType() == T) return;
10259
10260 Suspicious = false;
10261 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10262 E->getType(), CC, &Suspicious);
10263 if (!Suspicious)
10264 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010265 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010266}
10267
Richard Trieu65724892014-11-15 06:37:39 +000010268/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10269/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010270static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010271 if (S.getLangOpts().Bool)
10272 return;
10273 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10274}
10275
John McCallcc7e5bf2010-05-06 08:58:33 +000010276/// AnalyzeImplicitConversions - Find and report any interesting
10277/// implicit conversions in the given expression. There are a couple
10278/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010279static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10280 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010281 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010282 Expr *E = OrigE->IgnoreParenImpCasts();
10283
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010284 if (E->isTypeDependent() || E->isValueDependent())
10285 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010286
John McCallcc7e5bf2010-05-06 08:58:33 +000010287 // For conditional operators, we analyze the arguments as if they
10288 // were being fed directly into the output.
10289 if (isa<ConditionalOperator>(E)) {
10290 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010291 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010292 return;
10293 }
10294
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010295 // Check implicit argument conversions for function calls.
10296 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10297 CheckImplicitArgumentConversions(S, Call, CC);
10298
John McCallcc7e5bf2010-05-06 08:58:33 +000010299 // Go ahead and check any implicit conversions we might have skipped.
10300 // The non-canonical typecheck is just an optimization;
10301 // CheckImplicitConversion will filter out dead implicit conversions.
10302 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010303 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010304
10305 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010306
10307 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10308 // The bound subexpressions in a PseudoObjectExpr are not reachable
10309 // as transitive children.
10310 // FIXME: Use a more uniform representation for this.
10311 for (auto *SE : POE->semantics())
10312 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10313 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010314 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010315
John McCallcc7e5bf2010-05-06 08:58:33 +000010316 // Skip past explicit casts.
10317 if (isa<ExplicitCastExpr>(E)) {
10318 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010319 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010320 }
10321
John McCalld2a53122010-11-09 23:24:47 +000010322 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10323 // Do a somewhat different check with comparison operators.
10324 if (BO->isComparisonOp())
10325 return AnalyzeComparison(S, BO);
10326
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010327 // And with simple assignments.
10328 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010329 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010330 // And with compound assignments.
10331 if (BO->isAssignmentOp())
10332 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010333 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010334
10335 // These break the otherwise-useful invariant below. Fortunately,
10336 // we don't really need to recurse into them, because any internal
10337 // expressions should have been analyzed already when they were
10338 // built into statements.
10339 if (isa<StmtExpr>(E)) return;
10340
10341 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010342 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010343
10344 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010345 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010346 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010347 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010348 for (Stmt *SubStmt : E->children()) {
10349 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010350 if (!ChildExpr)
10351 continue;
10352
Richard Trieu955231d2014-01-25 01:10:35 +000010353 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010354 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010355 // Ignore checking string literals that are in logical and operators.
10356 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010357 continue;
10358 AnalyzeImplicitConversions(S, ChildExpr, CC);
10359 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010360
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010361 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010362 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10363 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010364 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010365
10366 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10367 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010368 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010369 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010370
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010371 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10372 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010373 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010374}
10375
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010376/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010377static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10378 // Taking into account implicit conversions,
10379 // allow any integer.
10380 if (!E->getType()->isIntegerType()) {
10381 S.Diag(E->getLocStart(),
10382 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10383 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010384 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010385 // Potentially emit standard warnings for implicit conversions if enabled
10386 // using -Wconversion.
10387 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10388 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010389}
10390
Richard Trieuc1888e02014-06-28 23:25:37 +000010391// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10392// Returns true when emitting a warning about taking the address of a reference.
10393static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010394 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010395 E = E->IgnoreParenImpCasts();
10396
10397 const FunctionDecl *FD = nullptr;
10398
10399 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10400 if (!DRE->getDecl()->getType()->isReferenceType())
10401 return false;
10402 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10403 if (!M->getMemberDecl()->getType()->isReferenceType())
10404 return false;
10405 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010406 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010407 return false;
10408 FD = Call->getDirectCallee();
10409 } else {
10410 return false;
10411 }
10412
10413 SemaRef.Diag(E->getExprLoc(), PD);
10414
10415 // If possible, point to location of function.
10416 if (FD) {
10417 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10418 }
10419
10420 return true;
10421}
10422
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010423// Returns true if the SourceLocation is expanded from any macro body.
10424// Returns false if the SourceLocation is invalid, is from not in a macro
10425// expansion, or is from expanded from a top-level macro argument.
10426static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10427 if (Loc.isInvalid())
10428 return false;
10429
10430 while (Loc.isMacroID()) {
10431 if (SM.isMacroBodyExpansion(Loc))
10432 return true;
10433 Loc = SM.getImmediateMacroCallerLoc(Loc);
10434 }
10435
10436 return false;
10437}
10438
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010439/// Diagnose pointers that are always non-null.
Richard Trieu3bb8b562014-02-26 02:36:06 +000010440/// \param E the expression containing the pointer
10441/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10442/// compared to a null pointer
10443/// \param IsEqual True when the comparison is equal to a null pointer
10444/// \param Range Extra SourceRange to highlight in the diagnostic
10445void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10446 Expr::NullPointerConstantKind NullKind,
10447 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010448 if (!E)
10449 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010450
10451 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010452 if (E->getExprLoc().isMacroID()) {
10453 const SourceManager &SM = getSourceManager();
10454 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10455 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010456 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010457 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010458 E = E->IgnoreImpCasts();
10459
10460 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10461
Richard Trieuf7432752014-06-06 21:39:26 +000010462 if (isa<CXXThisExpr>(E)) {
10463 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10464 : diag::warn_this_bool_conversion;
10465 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10466 return;
10467 }
10468
Richard Trieu3bb8b562014-02-26 02:36:06 +000010469 bool IsAddressOf = false;
10470
10471 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10472 if (UO->getOpcode() != UO_AddrOf)
10473 return;
10474 IsAddressOf = true;
10475 E = UO->getSubExpr();
10476 }
10477
Richard Trieuc1888e02014-06-28 23:25:37 +000010478 if (IsAddressOf) {
10479 unsigned DiagID = IsCompare
10480 ? diag::warn_address_of_reference_null_compare
10481 : diag::warn_address_of_reference_bool_conversion;
10482 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10483 << IsEqual;
10484 if (CheckForReference(*this, E, PD)) {
10485 return;
10486 }
10487 }
10488
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010489 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10490 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010491 std::string Str;
10492 llvm::raw_string_ostream S(Str);
10493 E->printPretty(S, nullptr, getPrintingPolicy());
10494 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10495 : diag::warn_cast_nonnull_to_bool;
10496 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10497 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010498 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010499 };
10500
10501 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10502 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10503 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010504 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10505 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010506 return;
10507 }
10508 }
10509 }
10510
Richard Trieu3bb8b562014-02-26 02:36:06 +000010511 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010512 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010513 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10514 D = R->getDecl();
10515 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10516 D = M->getMemberDecl();
10517 }
10518
10519 // Weak Decls can be null.
10520 if (!D || D->isWeak())
10521 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010522
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010523 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010524 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10525 if (getCurFunction() &&
10526 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010527 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10528 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010529 return;
10530 }
10531
10532 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010533 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010534 assert(ParamIter != FD->param_end());
10535 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10536
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010537 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10538 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010539 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010540 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010541 }
George Burgess IV850269a2015-12-08 22:02:00 +000010542
Joel E. Denny81508102018-03-13 14:51:22 +000010543 for (const ParamIdx &ArgNo : NonNull->args()) {
10544 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010545 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010546 return;
10547 }
George Burgess IV850269a2015-12-08 22:02:00 +000010548 }
10549 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010550 }
10551 }
George Burgess IV850269a2015-12-08 22:02:00 +000010552 }
10553
Richard Trieu3bb8b562014-02-26 02:36:06 +000010554 QualType T = D->getType();
10555 const bool IsArray = T->isArrayType();
10556 const bool IsFunction = T->isFunctionType();
10557
Richard Trieuc1888e02014-06-28 23:25:37 +000010558 // Address of function is used to silence the function warning.
10559 if (IsAddressOf && IsFunction) {
10560 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010561 }
10562
10563 // Found nothing.
10564 if (!IsAddressOf && !IsFunction && !IsArray)
10565 return;
10566
10567 // Pretty print the expression for the diagnostic.
10568 std::string Str;
10569 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010570 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010571
10572 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10573 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010574 enum {
10575 AddressOf,
10576 FunctionPointer,
10577 ArrayPointer
10578 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010579 if (IsAddressOf)
10580 DiagType = AddressOf;
10581 else if (IsFunction)
10582 DiagType = FunctionPointer;
10583 else if (IsArray)
10584 DiagType = ArrayPointer;
10585 else
10586 llvm_unreachable("Could not determine diagnostic.");
10587 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10588 << Range << IsEqual;
10589
10590 if (!IsFunction)
10591 return;
10592
10593 // Suggest '&' to silence the function warning.
10594 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10595 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10596
10597 // Check to see if '()' fixit should be emitted.
10598 QualType ReturnType;
10599 UnresolvedSet<4> NonTemplateOverloads;
10600 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10601 if (ReturnType.isNull())
10602 return;
10603
10604 if (IsCompare) {
10605 // There are two cases here. If there is null constant, the only suggest
10606 // for a pointer return type. If the null is 0, then suggest if the return
10607 // type is a pointer or an integer type.
10608 if (!ReturnType->isPointerType()) {
10609 if (NullKind == Expr::NPCK_ZeroExpression ||
10610 NullKind == Expr::NPCK_ZeroLiteral) {
10611 if (!ReturnType->isIntegerType())
10612 return;
10613 } else {
10614 return;
10615 }
10616 }
10617 } else { // !IsCompare
10618 // For function to bool, only suggest if the function pointer has bool
10619 // return type.
10620 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10621 return;
10622 }
10623 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010624 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010625}
10626
John McCallcc7e5bf2010-05-06 08:58:33 +000010627/// Diagnoses "dangerous" implicit conversions within the given
10628/// expression (which is a full expression). Implements -Wconversion
10629/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010630///
10631/// \param CC the "context" location of the implicit conversion, i.e.
10632/// the most location of the syntactic entity requiring the implicit
10633/// conversion
10634void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010635 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010636 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010637 return;
10638
10639 // Don't diagnose for value- or type-dependent expressions.
10640 if (E->isTypeDependent() || E->isValueDependent())
10641 return;
10642
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010643 // Check for array bounds violations in cases where the check isn't triggered
10644 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10645 // ArraySubscriptExpr is on the RHS of a variable initialization.
10646 CheckArrayAccess(E);
10647
John McCallacf0ee52010-10-08 02:01:28 +000010648 // This is not the right CC for (e.g.) a variable initialization.
10649 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010650}
10651
Richard Trieu65724892014-11-15 06:37:39 +000010652/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10653/// Input argument E is a logical expression.
10654void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10655 ::CheckBoolLikeConversion(*this, E, CC);
10656}
10657
Richard Smith9f7df0c2017-06-26 23:19:32 +000010658/// Diagnose when expression is an integer constant expression and its evaluation
10659/// results in integer overflow
10660void Sema::CheckForIntOverflow (Expr *E) {
10661 // Use a work list to deal with nested struct initializers.
10662 SmallVector<Expr *, 2> Exprs(1, E);
10663
10664 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010665 Expr *OriginalE = Exprs.pop_back_val();
10666 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010667
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010668 if (isa<BinaryOperator>(E)) {
10669 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010670 continue;
10671 }
10672
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010673 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010674 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010675 else if (isa<ObjCBoxedExpr>(OriginalE))
10676 E->EvaluateForOverflow(Context);
10677 else if (auto Call = dyn_cast<CallExpr>(E))
10678 Exprs.append(Call->arg_begin(), Call->arg_end());
10679 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10680 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010681 } while (!Exprs.empty());
10682}
10683
Richard Smithc406cb72013-01-17 01:17:56 +000010684namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010685
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010686/// Visitor for expressions which looks for unsequenced operations on the
Richard Smithc406cb72013-01-17 01:17:56 +000010687/// same object.
10688class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010689 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010690
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010691 /// A tree of sequenced regions within an expression. Two regions are
Richard Smithc406cb72013-01-17 01:17:56 +000010692 /// unsequenced if one is an ancestor or a descendent of the other. When we
10693 /// finish processing an expression with sequencing, such as a comma
10694 /// expression, we fold its tree nodes into its parent, since they are
10695 /// unsequenced with respect to nodes we will visit later.
10696 class SequenceTree {
10697 struct Value {
10698 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10699 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010700 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010701 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010702 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010703
10704 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010705 /// A region within an expression which may be sequenced with respect
Richard Smithc406cb72013-01-17 01:17:56 +000010706 /// to some other region.
10707 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010708 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010709
10710 unsigned Index = 0;
10711
10712 explicit Seq(unsigned N) : Index(N) {}
10713
Richard Smithc406cb72013-01-17 01:17:56 +000010714 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010715 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010716 };
10717
10718 SequenceTree() { Values.push_back(Value(0)); }
10719 Seq root() const { return Seq(0); }
10720
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010721 /// Create a new sequence of operations, which is an unsequenced
Richard Smithc406cb72013-01-17 01:17:56 +000010722 /// subset of \p Parent. This sequence of operations is sequenced with
10723 /// respect to other children of \p Parent.
10724 Seq allocate(Seq Parent) {
10725 Values.push_back(Value(Parent.Index));
10726 return Seq(Values.size() - 1);
10727 }
10728
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010729 /// Merge a sequence of operations into its parent.
Richard Smithc406cb72013-01-17 01:17:56 +000010730 void merge(Seq S) {
10731 Values[S.Index].Merged = true;
10732 }
10733
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010734 /// Determine whether two operations are unsequenced. This operation
Richard Smithc406cb72013-01-17 01:17:56 +000010735 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10736 /// should have been merged into its parent as appropriate.
10737 bool isUnsequenced(Seq Cur, Seq Old) {
10738 unsigned C = representative(Cur.Index);
10739 unsigned Target = representative(Old.Index);
10740 while (C >= Target) {
10741 if (C == Target)
10742 return true;
10743 C = Values[C].Parent;
10744 }
10745 return false;
10746 }
10747
10748 private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010749 /// Pick a representative for a sequence.
Richard Smithc406cb72013-01-17 01:17:56 +000010750 unsigned representative(unsigned K) {
10751 if (Values[K].Merged)
10752 // Perform path compression as we go.
10753 return Values[K].Parent = representative(Values[K].Parent);
10754 return K;
10755 }
10756 };
10757
10758 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010759 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010760
10761 /// Different flavors of object usage which we track. We only track the
10762 /// least-sequenced usage of each kind.
10763 enum UsageKind {
10764 /// A read of an object. Multiple unsequenced reads are OK.
10765 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010766
Richard Smithc406cb72013-01-17 01:17:56 +000010767 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010768 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010769 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010770
Richard Smithc406cb72013-01-17 01:17:56 +000010771 /// A modification of an object which is not sequenced before the value
10772 /// computation of the expression, such as n++.
10773 UK_ModAsSideEffect,
10774
10775 UK_Count = UK_ModAsSideEffect + 1
10776 };
10777
10778 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010779 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010780 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010781
10782 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010783 };
10784
10785 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010786 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010787
Richard Smithc406cb72013-01-17 01:17:56 +000010788 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010789 bool Diagnosed = false;
10790
10791 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010792 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010793 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010794
10795 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010796
Richard Smithc406cb72013-01-17 01:17:56 +000010797 /// Sequenced regions within the expression.
10798 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010799
Richard Smithc406cb72013-01-17 01:17:56 +000010800 /// Declaration modifications and references which we have seen.
10801 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010802
Richard Smithc406cb72013-01-17 01:17:56 +000010803 /// The region we are currently within.
10804 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010805
Richard Smithc406cb72013-01-17 01:17:56 +000010806 /// Filled in with declarations which were modified as a side-effect
10807 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010808 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10809
Richard Smithd33f5202013-01-17 23:18:09 +000010810 /// Expressions to check later. We defer checking these to reduce
10811 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010812 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010813
10814 /// RAII object wrapping the visitation of a sequenced subexpression of an
10815 /// expression. At the end of this process, the side-effects of the evaluation
10816 /// become sequenced with respect to the value computation of the result, so
10817 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10818 /// UK_ModAsValue.
10819 struct SequencedSubexpression {
10820 SequencedSubexpression(SequenceChecker &Self)
10821 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10822 Self.ModAsSideEffect = &ModAsSideEffect;
10823 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010824
Richard Smithc406cb72013-01-17 01:17:56 +000010825 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010826 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10827 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010828 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010829 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10830 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010831 }
10832 Self.ModAsSideEffect = OldModAsSideEffect;
10833 }
10834
10835 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010836 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010837 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010838 };
10839
Richard Smith40238f02013-06-20 22:21:56 +000010840 /// RAII object wrapping the visitation of a subexpression which we might
10841 /// choose to evaluate as a constant. If any subexpression is evaluated and
10842 /// found to be non-constant, this allows us to suppress the evaluation of
10843 /// the outer expression.
10844 class EvaluationTracker {
10845 public:
10846 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010847 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010848 Self.EvalTracker = this;
10849 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010850
Richard Smith40238f02013-06-20 22:21:56 +000010851 ~EvaluationTracker() {
10852 Self.EvalTracker = Prev;
10853 if (Prev)
10854 Prev->EvalOK &= EvalOK;
10855 }
10856
10857 bool evaluate(const Expr *E, bool &Result) {
10858 if (!EvalOK || E->isValueDependent())
10859 return false;
10860 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10861 return EvalOK;
10862 }
10863
10864 private:
10865 SequenceChecker &Self;
10866 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010867 bool EvalOK = true;
10868 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010869
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010870 /// Find the object which is produced by the specified expression,
Richard Smithc406cb72013-01-17 01:17:56 +000010871 /// if any.
10872 Object getObject(Expr *E, bool Mod) const {
10873 E = E->IgnoreParenCasts();
10874 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10875 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10876 return getObject(UO->getSubExpr(), Mod);
10877 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10878 if (BO->getOpcode() == BO_Comma)
10879 return getObject(BO->getRHS(), Mod);
10880 if (Mod && BO->isAssignmentOp())
10881 return getObject(BO->getLHS(), Mod);
10882 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10883 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10884 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10885 return ME->getMemberDecl();
10886 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10887 // FIXME: If this is a reference, map through to its value.
10888 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010889 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010890 }
10891
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010892 /// Note that an object was modified or used by an expression.
Richard Smithc406cb72013-01-17 01:17:56 +000010893 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10894 Usage &U = UI.Uses[UK];
10895 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10896 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10897 ModAsSideEffect->push_back(std::make_pair(O, U));
10898 U.Use = Ref;
10899 U.Seq = Region;
10900 }
10901 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010902
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010903 /// Check whether a modification or use conflicts with a prior usage.
Richard Smithc406cb72013-01-17 01:17:56 +000010904 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10905 bool IsModMod) {
10906 if (UI.Diagnosed)
10907 return;
10908
10909 const Usage &U = UI.Uses[OtherKind];
10910 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10911 return;
10912
10913 Expr *Mod = U.Use;
10914 Expr *ModOrUse = Ref;
10915 if (OtherKind == UK_Use)
10916 std::swap(Mod, ModOrUse);
10917
10918 SemaRef.Diag(Mod->getExprLoc(),
10919 IsModMod ? diag::warn_unsequenced_mod_mod
10920 : diag::warn_unsequenced_mod_use)
10921 << O << SourceRange(ModOrUse->getExprLoc());
10922 UI.Diagnosed = true;
10923 }
10924
10925 void notePreUse(Object O, Expr *Use) {
10926 UsageInfo &U = UsageMap[O];
10927 // Uses conflict with other modifications.
10928 checkUsage(O, U, Use, UK_ModAsValue, false);
10929 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010930
Richard Smithc406cb72013-01-17 01:17:56 +000010931 void notePostUse(Object O, Expr *Use) {
10932 UsageInfo &U = UsageMap[O];
10933 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10934 addUsage(U, O, Use, UK_Use);
10935 }
10936
10937 void notePreMod(Object O, Expr *Mod) {
10938 UsageInfo &U = UsageMap[O];
10939 // Modifications conflict with other modifications and with uses.
10940 checkUsage(O, U, Mod, UK_ModAsValue, true);
10941 checkUsage(O, U, Mod, UK_Use, false);
10942 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010943
Richard Smithc406cb72013-01-17 01:17:56 +000010944 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10945 UsageInfo &U = UsageMap[O];
10946 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10947 addUsage(U, O, Use, UK);
10948 }
10949
10950public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010951 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010952 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000010953 Visit(E);
10954 }
10955
10956 void VisitStmt(Stmt *S) {
10957 // Skip all statements which aren't expressions for now.
10958 }
10959
10960 void VisitExpr(Expr *E) {
10961 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010962 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010963 }
10964
10965 void VisitCastExpr(CastExpr *E) {
10966 Object O = Object();
10967 if (E->getCastKind() == CK_LValueToRValue)
10968 O = getObject(E->getSubExpr(), false);
10969
10970 if (O)
10971 notePreUse(O, E);
10972 VisitExpr(E);
10973 if (O)
10974 notePostUse(O, E);
10975 }
10976
10977 void VisitBinComma(BinaryOperator *BO) {
10978 // C++11 [expr.comma]p1:
10979 // Every value computation and side effect associated with the left
10980 // expression is sequenced before every value computation and side
10981 // effect associated with the right expression.
10982 SequenceTree::Seq LHS = Tree.allocate(Region);
10983 SequenceTree::Seq RHS = Tree.allocate(Region);
10984 SequenceTree::Seq OldRegion = Region;
10985
10986 {
10987 SequencedSubexpression SeqLHS(*this);
10988 Region = LHS;
10989 Visit(BO->getLHS());
10990 }
10991
10992 Region = RHS;
10993 Visit(BO->getRHS());
10994
10995 Region = OldRegion;
10996
10997 // Forget that LHS and RHS are sequenced. They are both unsequenced
10998 // with respect to other stuff.
10999 Tree.merge(LHS);
11000 Tree.merge(RHS);
11001 }
11002
11003 void VisitBinAssign(BinaryOperator *BO) {
11004 // The modification is sequenced after the value computation of the LHS
11005 // and RHS, so check it before inspecting the operands and update the
11006 // map afterwards.
11007 Object O = getObject(BO->getLHS(), true);
11008 if (!O)
11009 return VisitExpr(BO);
11010
11011 notePreMod(O, BO);
11012
11013 // C++11 [expr.ass]p7:
11014 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11015 // only once.
11016 //
11017 // Therefore, for a compound assignment operator, O is considered used
11018 // everywhere except within the evaluation of E1 itself.
11019 if (isa<CompoundAssignOperator>(BO))
11020 notePreUse(O, BO);
11021
11022 Visit(BO->getLHS());
11023
11024 if (isa<CompoundAssignOperator>(BO))
11025 notePostUse(O, BO);
11026
11027 Visit(BO->getRHS());
11028
Richard Smith83e37bee2013-06-26 23:16:51 +000011029 // C++11 [expr.ass]p1:
11030 // the assignment is sequenced [...] before the value computation of the
11031 // assignment expression.
11032 // C11 6.5.16/3 has no such rule.
11033 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11034 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011035 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000011036
Richard Smithc406cb72013-01-17 01:17:56 +000011037 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11038 VisitBinAssign(CAO);
11039 }
11040
11041 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11042 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11043 void VisitUnaryPreIncDec(UnaryOperator *UO) {
11044 Object O = getObject(UO->getSubExpr(), true);
11045 if (!O)
11046 return VisitExpr(UO);
11047
11048 notePreMod(O, UO);
11049 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000011050 // C++11 [expr.pre.incr]p1:
11051 // the expression ++x is equivalent to x+=1
11052 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11053 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000011054 }
11055
11056 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11057 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11058 void VisitUnaryPostIncDec(UnaryOperator *UO) {
11059 Object O = getObject(UO->getSubExpr(), true);
11060 if (!O)
11061 return VisitExpr(UO);
11062
11063 notePreMod(O, UO);
11064 Visit(UO->getSubExpr());
11065 notePostMod(O, UO, UK_ModAsSideEffect);
11066 }
11067
11068 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11069 void VisitBinLOr(BinaryOperator *BO) {
11070 // The side-effects of the LHS of an '&&' are sequenced before the
11071 // value computation of the RHS, and hence before the value computation
11072 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11073 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000011074 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011075 {
11076 SequencedSubexpression Sequenced(*this);
11077 Visit(BO->getLHS());
11078 }
11079
11080 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011081 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011082 if (!Result)
11083 Visit(BO->getRHS());
11084 } else {
11085 // Check for unsequenced operations in the RHS, treating it as an
11086 // entirely separate evaluation.
11087 //
11088 // FIXME: If there are operations in the RHS which are unsequenced
11089 // with respect to operations outside the RHS, and those operations
11090 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000011091 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011092 }
Richard Smithc406cb72013-01-17 01:17:56 +000011093 }
11094 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000011095 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000011096 {
11097 SequencedSubexpression Sequenced(*this);
11098 Visit(BO->getLHS());
11099 }
11100
11101 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011102 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000011103 if (Result)
11104 Visit(BO->getRHS());
11105 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000011106 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000011107 }
Richard Smithc406cb72013-01-17 01:17:56 +000011108 }
11109
11110 // Only visit the condition, unless we can be sure which subexpression will
11111 // be chosen.
11112 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000011113 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000011114 {
11115 SequencedSubexpression Sequenced(*this);
11116 Visit(CO->getCond());
11117 }
Richard Smithc406cb72013-01-17 01:17:56 +000011118
11119 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000011120 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000011121 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011122 else {
Richard Smithd33f5202013-01-17 23:18:09 +000011123 WorkList.push_back(CO->getTrueExpr());
11124 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000011125 }
Richard Smithc406cb72013-01-17 01:17:56 +000011126 }
11127
Richard Smithe3dbfe02013-06-30 10:40:20 +000011128 void VisitCallExpr(CallExpr *CE) {
11129 // C++11 [intro.execution]p15:
11130 // When calling a function [...], every value computation and side effect
11131 // associated with any argument expression, or with the postfix expression
11132 // designating the called function, is sequenced before execution of every
11133 // expression or statement in the body of the function [and thus before
11134 // the value computation of its result].
11135 SequencedSubexpression Sequenced(*this);
11136 Base::VisitCallExpr(CE);
11137
11138 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11139 }
11140
Richard Smithc406cb72013-01-17 01:17:56 +000011141 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000011142 // This is a call, so all subexpressions are sequenced before the result.
11143 SequencedSubexpression Sequenced(*this);
11144
Richard Smithc406cb72013-01-17 01:17:56 +000011145 if (!CCE->isListInitialization())
11146 return VisitExpr(CCE);
11147
11148 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011149 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011150 SequenceTree::Seq Parent = Region;
11151 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11152 E = CCE->arg_end();
11153 I != E; ++I) {
11154 Region = Tree.allocate(Parent);
11155 Elts.push_back(Region);
11156 Visit(*I);
11157 }
11158
11159 // Forget that the initializers are sequenced.
11160 Region = Parent;
11161 for (unsigned I = 0; I < Elts.size(); ++I)
11162 Tree.merge(Elts[I]);
11163 }
11164
11165 void VisitInitListExpr(InitListExpr *ILE) {
11166 if (!SemaRef.getLangOpts().CPlusPlus11)
11167 return VisitExpr(ILE);
11168
11169 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011170 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000011171 SequenceTree::Seq Parent = Region;
11172 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11173 Expr *E = ILE->getInit(I);
11174 if (!E) continue;
11175 Region = Tree.allocate(Parent);
11176 Elts.push_back(Region);
11177 Visit(E);
11178 }
11179
11180 // Forget that the initializers are sequenced.
11181 Region = Parent;
11182 for (unsigned I = 0; I < Elts.size(); ++I)
11183 Tree.merge(Elts[I]);
11184 }
11185};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011186
11187} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000011188
11189void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000011190 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000011191 WorkList.push_back(E);
11192 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000011193 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000011194 SequenceChecker(*this, Item, WorkList);
11195 }
Richard Smithc406cb72013-01-17 01:17:56 +000011196}
11197
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011198void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11199 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000011200 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000011201 if (!E->isInstantiationDependent())
11202 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000011203 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000011204 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000011205 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000011206}
11207
John McCall1f425642010-11-11 03:21:53 +000011208void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11209 FieldDecl *BitField,
11210 Expr *Init) {
11211 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11212}
11213
David Majnemer61a5bbf2015-04-07 22:08:51 +000011214static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11215 SourceLocation Loc) {
11216 if (!PType->isVariablyModifiedType())
11217 return;
11218 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11219 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11220 return;
11221 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000011222 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11223 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11224 return;
11225 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000011226 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11227 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11228 return;
11229 }
11230
11231 const ArrayType *AT = S.Context.getAsArrayType(PType);
11232 if (!AT)
11233 return;
11234
11235 if (AT->getSizeModifier() != ArrayType::Star) {
11236 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11237 return;
11238 }
11239
11240 S.Diag(Loc, diag::err_array_star_in_function_definition);
11241}
11242
Mike Stump0c2ec772010-01-21 03:59:47 +000011243/// CheckParmsForFunctionDef - Check that the parameters of the given
11244/// function are appropriate for the definition of a function. This
11245/// takes care of any checks that cannot be performed on the
11246/// declaration itself, e.g., that the types of each of the function
11247/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000011248bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000011249 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011250 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000011251 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011252 // C99 6.7.5.3p4: the parameters in a parameter type list in a
11253 // function declarator that is part of a function definition of
11254 // that function shall not have incomplete type.
11255 //
11256 // This is also C++ [dcl.fct]p6.
11257 if (!Param->isInvalidDecl() &&
11258 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011259 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011260 Param->setInvalidDecl();
11261 HasInvalidParm = true;
11262 }
11263
11264 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11265 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011266 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011267 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011268 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011269 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011270 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011271
11272 // C99 6.7.5.3p12:
11273 // If the function declarator is not part of a definition of that
11274 // function, parameters may have incomplete type and may use the [*]
11275 // notation in their sequences of declarator specifiers to specify
11276 // variable length array types.
11277 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011278 // FIXME: This diagnostic should point the '[*]' if source-location
11279 // information is added for it.
11280 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011281
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011282 // If the parameter is a c++ class type and it has to be destructed in the
11283 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011284 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011285 if (!Param->isInvalidDecl()) {
11286 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11287 if (!ClassDecl->isInvalidDecl() &&
11288 !ClassDecl->hasIrrelevantDestructor() &&
11289 !ClassDecl->isDependentContext() &&
11290 Context.isParamDestroyedInCallee(Param->getType())) {
11291 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11292 MarkFunctionReferenced(Param->getLocation(), Destructor);
11293 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011294 }
11295 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011296 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011297
11298 // Parameters with the pass_object_size attribute only need to be marked
11299 // constant at function definitions. Because we lack information about
11300 // whether we're on a declaration or definition when we're instantiating the
11301 // attribute, we need to check for constness here.
11302 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11303 if (!Param->getType().isConstQualified())
11304 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11305 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011306 }
11307
11308 return HasInvalidParm;
11309}
John McCall2b5c1b22010-08-12 21:44:57 +000011310
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011311/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11312/// or MemberExpr.
11313static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11314 ASTContext &Context) {
11315 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11316 return Context.getDeclAlign(DRE->getDecl());
11317
11318 if (const auto *ME = dyn_cast<MemberExpr>(E))
11319 return Context.getDeclAlign(ME->getMemberDecl());
11320
11321 return TypeAlign;
11322}
11323
John McCall2b5c1b22010-08-12 21:44:57 +000011324/// CheckCastAlign - Implements -Wcast-align, which warns when a
11325/// pointer cast increases the alignment requirements.
11326void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11327 // This is actually a lot of work to potentially be doing on every
11328 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011329 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011330 return;
11331
11332 // Ignore dependent types.
11333 if (T->isDependentType() || Op->getType()->isDependentType())
11334 return;
11335
11336 // Require that the destination be a pointer type.
11337 const PointerType *DestPtr = T->getAs<PointerType>();
11338 if (!DestPtr) return;
11339
11340 // If the destination has alignment 1, we're done.
11341 QualType DestPointee = DestPtr->getPointeeType();
11342 if (DestPointee->isIncompleteType()) return;
11343 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11344 if (DestAlign.isOne()) return;
11345
11346 // Require that the source be a pointer type.
11347 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11348 if (!SrcPtr) return;
11349 QualType SrcPointee = SrcPtr->getPointeeType();
11350
11351 // Whitelist casts from cv void*. We already implicitly
11352 // whitelisted casts to cv void*, since they have alignment 1.
11353 // Also whitelist casts involving incomplete types, which implicitly
11354 // includes 'void'.
11355 if (SrcPointee->isIncompleteType()) return;
11356
11357 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011358
11359 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11360 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11361 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11362 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11363 if (UO->getOpcode() == UO_AddrOf)
11364 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11365 }
11366
John McCall2b5c1b22010-08-12 21:44:57 +000011367 if (SrcAlign >= DestAlign) return;
11368
11369 Diag(TRange.getBegin(), diag::warn_cast_align)
11370 << Op->getType() << T
11371 << static_cast<unsigned>(SrcAlign.getQuantity())
11372 << static_cast<unsigned>(DestAlign.getQuantity())
11373 << TRange << Op->getSourceRange();
11374}
11375
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011376/// Check whether this array fits the idiom of a size-one tail padded
Chandler Carruth28389f02011-08-05 09:10:50 +000011377/// array member of a struct.
11378///
11379/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11380/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011381static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011382 const NamedDecl *ND) {
11383 if (Size != 1 || !ND) return false;
11384
11385 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11386 if (!FD) return false;
11387
11388 // Don't consider sizes resulting from macro expansions or template argument
11389 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011390
11391 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011392 while (TInfo) {
11393 TypeLoc TL = TInfo->getTypeLoc();
11394 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011395 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11396 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011397 TInfo = TDL->getTypeSourceInfo();
11398 continue;
11399 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011400 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11401 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011402 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11403 return false;
11404 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011405 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011406 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011407
11408 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011409 if (!RD) return false;
11410 if (RD->isUnion()) return false;
11411 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11412 if (!CRD->isStandardLayout()) return false;
11413 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011414
Benjamin Kramer8c543672011-08-06 03:04:42 +000011415 // See if this is the last field decl in the record.
11416 const Decl *D = FD;
11417 while ((D = D->getNextDeclInContext()))
11418 if (isa<FieldDecl>(D))
11419 return false;
11420 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011421}
11422
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011423void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011424 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011425 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011426 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011427 if (IndexExpr->isValueDependent())
11428 return;
11429
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011430 const Type *EffectiveType =
11431 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011432 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011433 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011434 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011435 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011436 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011437
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011438 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011439 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011440 return;
Richard Smith13f67182011-12-16 19:31:14 +000011441 if (IndexNegated)
11442 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011443
Craig Topperc3ec1492014-05-26 06:22:03 +000011444 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011445 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011446 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011447 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011448 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011449
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011450 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011451 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011452 if (!size.isStrictlyPositive())
11453 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011454
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011455 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011456 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011457 // Make sure we're comparing apples to apples when comparing index to size
11458 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11459 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011460 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011461 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011462 if (ptrarith_typesize != array_typesize) {
11463 // There's a cast to a different size type involved
11464 uint64_t ratio = array_typesize / ptrarith_typesize;
11465 // TODO: Be smarter about handling cases where array_typesize is not a
11466 // multiple of ptrarith_typesize
11467 if (ptrarith_typesize * ratio == array_typesize)
11468 size *= llvm::APInt(size.getBitWidth(), ratio);
11469 }
11470 }
11471
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011472 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011473 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011474 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011475 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011476
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011477 // For array subscripting the index must be less than size, but for pointer
11478 // arithmetic also allow the index (offset) to be equal to size since
11479 // computing the next address after the end of the array is legal and
11480 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011481 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011482 return;
11483
11484 // Also don't warn for arrays of size 1 which are members of some
11485 // structure. These are often used to approximate flexible arrays in C89
11486 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011487 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011488 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011489
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011490 // Suppress the warning if the subscript expression (as identified by the
11491 // ']' location) and the index expression are both from macro expansions
11492 // within a system header.
11493 if (ASE) {
11494 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11495 ASE->getRBracketLoc());
11496 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11497 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11498 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011499 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011500 return;
11501 }
11502 }
11503
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011504 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011505 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011506 DiagID = diag::warn_array_index_exceeds_bounds;
11507
11508 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11509 PDiag(DiagID) << index.toString(10, true)
11510 << size.toString(10, true)
11511 << (unsigned)size.getLimitedValue(~0U)
11512 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011513 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011514 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011515 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011516 DiagID = diag::warn_ptr_arith_precedes_bounds;
11517 if (index.isNegative()) index = -index;
11518 }
11519
11520 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11521 PDiag(DiagID) << index.toString(10, true)
11522 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011523 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011524
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011525 if (!ND) {
11526 // Try harder to find a NamedDecl to point at in the note.
11527 while (const ArraySubscriptExpr *ASE =
11528 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11529 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11530 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011531 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011532 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011533 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011534 }
11535
Chandler Carruth1af88f12011-02-17 21:10:52 +000011536 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011537 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11538 PDiag(diag::note_array_index_out_of_bounds)
11539 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011540}
11541
Ted Kremenekdf26df72011-03-01 18:41:00 +000011542void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011543 int AllowOnePastEnd = 0;
11544 while (expr) {
11545 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011546 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011547 case Stmt::ArraySubscriptExprClass: {
11548 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011549 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011550 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011551 expr = ASE->getBase();
11552 break;
11553 }
11554 case Stmt::MemberExprClass: {
11555 expr = cast<MemberExpr>(expr)->getBase();
11556 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011557 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011558 case Stmt::OMPArraySectionExprClass: {
11559 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11560 if (ASE->getLowerBound())
11561 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11562 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11563 return;
11564 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011565 case Stmt::UnaryOperatorClass: {
11566 // Only unwrap the * and & unary operators
11567 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11568 expr = UO->getSubExpr();
11569 switch (UO->getOpcode()) {
11570 case UO_AddrOf:
11571 AllowOnePastEnd++;
11572 break;
11573 case UO_Deref:
11574 AllowOnePastEnd--;
11575 break;
11576 default:
11577 return;
11578 }
11579 break;
11580 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011581 case Stmt::ConditionalOperatorClass: {
11582 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11583 if (const Expr *lhs = cond->getLHS())
11584 CheckArrayAccess(lhs);
11585 if (const Expr *rhs = cond->getRHS())
11586 CheckArrayAccess(rhs);
11587 return;
11588 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011589 case Stmt::CXXOperatorCallExprClass: {
11590 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11591 for (const auto *Arg : OCE->arguments())
11592 CheckArrayAccess(Arg);
11593 return;
11594 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011595 default:
11596 return;
11597 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011598 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011599}
John McCall31168b02011-06-15 23:02:42 +000011600
11601//===--- CHECK: Objective-C retain cycles ----------------------------------//
11602
11603namespace {
John McCall31168b02011-06-15 23:02:42 +000011604
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011605struct RetainCycleOwner {
11606 VarDecl *Variable = nullptr;
11607 SourceRange Range;
11608 SourceLocation Loc;
11609 bool Indirect = false;
11610
11611 RetainCycleOwner() = default;
11612
11613 void setLocsFrom(Expr *e) {
11614 Loc = e->getExprLoc();
11615 Range = e->getSourceRange();
11616 }
11617};
11618
11619} // namespace
John McCall31168b02011-06-15 23:02:42 +000011620
11621/// Consider whether capturing the given variable can possibly lead to
11622/// a retain cycle.
11623static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011624 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011625 // lifetime. In MRR, it's captured strongly if the variable is
11626 // __block and has an appropriate type.
11627 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11628 return false;
11629
11630 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011631 if (ref)
11632 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011633 return true;
11634}
11635
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011636static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011637 while (true) {
11638 e = e->IgnoreParens();
11639 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11640 switch (cast->getCastKind()) {
11641 case CK_BitCast:
11642 case CK_LValueBitCast:
11643 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011644 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011645 e = cast->getSubExpr();
11646 continue;
11647
John McCall31168b02011-06-15 23:02:42 +000011648 default:
11649 return false;
11650 }
11651 }
11652
11653 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11654 ObjCIvarDecl *ivar = ref->getDecl();
11655 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11656 return false;
11657
11658 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011659 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011660 return false;
11661
11662 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11663 owner.Indirect = true;
11664 return true;
11665 }
11666
11667 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11668 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11669 if (!var) return false;
11670 return considerVariable(var, ref, owner);
11671 }
11672
John McCall31168b02011-06-15 23:02:42 +000011673 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11674 if (member->isArrow()) return false;
11675
11676 // Don't count this as an indirect ownership.
11677 e = member->getBase();
11678 continue;
11679 }
11680
John McCallfe96e0b2011-11-06 09:01:30 +000011681 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11682 // Only pay attention to pseudo-objects on property references.
11683 ObjCPropertyRefExpr *pre
11684 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11685 ->IgnoreParens());
11686 if (!pre) return false;
11687 if (pre->isImplicitProperty()) return false;
11688 ObjCPropertyDecl *property = pre->getExplicitProperty();
11689 if (!property->isRetaining() &&
11690 !(property->getPropertyIvarDecl() &&
11691 property->getPropertyIvarDecl()->getType()
11692 .getObjCLifetime() == Qualifiers::OCL_Strong))
11693 return false;
11694
11695 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011696 if (pre->isSuperReceiver()) {
11697 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11698 if (!owner.Variable)
11699 return false;
11700 owner.Loc = pre->getLocation();
11701 owner.Range = pre->getSourceRange();
11702 return true;
11703 }
John McCallfe96e0b2011-11-06 09:01:30 +000011704 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11705 ->getSourceExpr());
11706 continue;
11707 }
11708
John McCall31168b02011-06-15 23:02:42 +000011709 // Array ivars?
11710
11711 return false;
11712 }
11713}
11714
11715namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011716
John McCall31168b02011-06-15 23:02:42 +000011717 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011718 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011719 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011720 Expr *Capturer = nullptr;
11721 bool VarWillBeReased = false;
11722
11723 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11724 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11725 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011726
11727 void VisitDeclRefExpr(DeclRefExpr *ref) {
11728 if (ref->getDecl() == Variable && !Capturer)
11729 Capturer = ref;
11730 }
11731
John McCall31168b02011-06-15 23:02:42 +000011732 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11733 if (Capturer) return;
11734 Visit(ref->getBase());
11735 if (Capturer && ref->isFreeIvar())
11736 Capturer = ref;
11737 }
11738
11739 void VisitBlockExpr(BlockExpr *block) {
11740 // Look inside nested blocks
11741 if (block->getBlockDecl()->capturesVariable(Variable))
11742 Visit(block->getBlockDecl()->getBody());
11743 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011744
11745 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11746 if (Capturer) return;
11747 if (OVE->getSourceExpr())
11748 Visit(OVE->getSourceExpr());
11749 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011750
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011751 void VisitBinaryOperator(BinaryOperator *BinOp) {
11752 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11753 return;
11754 Expr *LHS = BinOp->getLHS();
11755 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11756 if (DRE->getDecl() != Variable)
11757 return;
11758 if (Expr *RHS = BinOp->getRHS()) {
11759 RHS = RHS->IgnoreParenCasts();
11760 llvm::APSInt Value;
11761 VarWillBeReased =
11762 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11763 }
11764 }
11765 }
John McCall31168b02011-06-15 23:02:42 +000011766 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011767
11768} // namespace
John McCall31168b02011-06-15 23:02:42 +000011769
11770/// Check whether the given argument is a block which captures a
11771/// variable.
11772static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11773 assert(owner.Variable && owner.Loc.isValid());
11774
11775 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011776
11777 // Look through [^{...} copy] and Block_copy(^{...}).
11778 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11779 Selector Cmd = ME->getSelector();
11780 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11781 e = ME->getInstanceReceiver();
11782 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011783 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011784 e = e->IgnoreParenCasts();
11785 }
11786 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11787 if (CE->getNumArgs() == 1) {
11788 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011789 if (Fn) {
11790 const IdentifierInfo *FnI = Fn->getIdentifier();
11791 if (FnI && FnI->isStr("_Block_copy")) {
11792 e = CE->getArg(0)->IgnoreParenCasts();
11793 }
11794 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011795 }
11796 }
11797
John McCall31168b02011-06-15 23:02:42 +000011798 BlockExpr *block = dyn_cast<BlockExpr>(e);
11799 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011800 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011801
11802 FindCaptureVisitor visitor(S.Context, owner.Variable);
11803 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011804 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011805}
11806
11807static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11808 RetainCycleOwner &owner) {
11809 assert(capturer);
11810 assert(owner.Variable && owner.Loc.isValid());
11811
11812 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11813 << owner.Variable << capturer->getSourceRange();
11814 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11815 << owner.Indirect << owner.Range;
11816}
11817
11818/// Check for a keyword selector that starts with the word 'add' or
11819/// 'set'.
11820static bool isSetterLikeSelector(Selector sel) {
11821 if (sel.isUnarySelector()) return false;
11822
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011823 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011824 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011825 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011826 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011827 else if (str.startswith("add")) {
11828 // Specially whitelist 'addOperationWithBlock:'.
11829 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11830 return false;
11831 str = str.substr(3);
11832 }
John McCall31168b02011-06-15 23:02:42 +000011833 else
11834 return false;
11835
11836 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011837 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011838}
11839
Benjamin Kramer3a743452015-03-09 15:03:32 +000011840static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11841 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011842 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11843 Message->getReceiverInterface(),
11844 NSAPI::ClassId_NSMutableArray);
11845 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011846 return None;
11847 }
11848
11849 Selector Sel = Message->getSelector();
11850
11851 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11852 S.NSAPIObj->getNSArrayMethodKind(Sel);
11853 if (!MKOpt) {
11854 return None;
11855 }
11856
11857 NSAPI::NSArrayMethodKind MK = *MKOpt;
11858
11859 switch (MK) {
11860 case NSAPI::NSMutableArr_addObject:
11861 case NSAPI::NSMutableArr_insertObjectAtIndex:
11862 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11863 return 0;
11864 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11865 return 1;
11866
11867 default:
11868 return None;
11869 }
11870
11871 return None;
11872}
11873
11874static
11875Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11876 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011877 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11878 Message->getReceiverInterface(),
11879 NSAPI::ClassId_NSMutableDictionary);
11880 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011881 return None;
11882 }
11883
11884 Selector Sel = Message->getSelector();
11885
11886 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11887 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11888 if (!MKOpt) {
11889 return None;
11890 }
11891
11892 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11893
11894 switch (MK) {
11895 case NSAPI::NSMutableDict_setObjectForKey:
11896 case NSAPI::NSMutableDict_setValueForKey:
11897 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11898 return 0;
11899
11900 default:
11901 return None;
11902 }
11903
11904 return None;
11905}
11906
11907static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011908 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11909 Message->getReceiverInterface(),
11910 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011911
Alex Denisov5dfac812015-08-06 04:51:14 +000011912 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11913 Message->getReceiverInterface(),
11914 NSAPI::ClassId_NSMutableOrderedSet);
11915 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011916 return None;
11917 }
11918
11919 Selector Sel = Message->getSelector();
11920
11921 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11922 if (!MKOpt) {
11923 return None;
11924 }
11925
11926 NSAPI::NSSetMethodKind MK = *MKOpt;
11927
11928 switch (MK) {
11929 case NSAPI::NSMutableSet_addObject:
11930 case NSAPI::NSOrderedSet_setObjectAtIndex:
11931 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11932 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11933 return 0;
11934 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11935 return 1;
11936 }
11937
11938 return None;
11939}
11940
11941void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11942 if (!Message->isInstanceMessage()) {
11943 return;
11944 }
11945
11946 Optional<int> ArgOpt;
11947
11948 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11949 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11950 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11951 return;
11952 }
11953
11954 int ArgIndex = *ArgOpt;
11955
Alex Denisove1d882c2015-03-04 17:55:52 +000011956 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11957 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11958 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11959 }
11960
Alex Denisov5dfac812015-08-06 04:51:14 +000011961 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011962 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011963 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011964 Diag(Message->getSourceRange().getBegin(),
11965 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011966 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000011967 }
11968 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011969 } else {
11970 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11971
11972 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11973 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11974 }
11975
11976 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11977 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11978 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11979 ValueDecl *Decl = ReceiverRE->getDecl();
11980 Diag(Message->getSourceRange().getBegin(),
11981 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011982 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011983 if (!ArgRE->isObjCSelfExpr()) {
11984 Diag(Decl->getLocation(),
11985 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000011986 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011987 }
11988 }
11989 }
11990 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11991 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11992 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11993 ObjCIvarDecl *Decl = IvarRE->getDecl();
11994 Diag(Message->getSourceRange().getBegin(),
11995 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011996 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011997 Diag(Decl->getLocation(),
11998 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000011999 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000012000 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012001 }
12002 }
12003 }
Alex Denisove1d882c2015-03-04 17:55:52 +000012004}
12005
John McCall31168b02011-06-15 23:02:42 +000012006/// Check a message send to see if it's likely to cause a retain cycle.
12007void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12008 // Only check instance methods whose selector looks like a setter.
12009 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12010 return;
12011
12012 // Try to find a variable that the receiver is strongly owned by.
12013 RetainCycleOwner owner;
12014 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012015 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000012016 return;
12017 } else {
12018 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12019 owner.Variable = getCurMethodDecl()->getSelfDecl();
12020 owner.Loc = msg->getSuperLoc();
12021 owner.Range = msg->getSuperLoc();
12022 }
12023
12024 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000012025 const ObjCMethodDecl *MD = msg->getMethodDecl();
12026 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12027 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12028 // noescape blocks should not be retained by the method.
12029 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12030 continue;
John McCall31168b02011-06-15 23:02:42 +000012031 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000012032 }
12033 }
John McCall31168b02011-06-15 23:02:42 +000012034}
12035
12036/// Check a property assign to see if it's likely to cause a retain cycle.
12037void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12038 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000012039 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000012040 return;
12041
12042 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12043 diagnoseRetainCycle(*this, capturer, owner);
12044}
12045
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012046void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12047 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000012048 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000012049 return;
12050
12051 // Because we don't have an expression for the variable, we have to set the
12052 // location explicitly here.
12053 Owner.Loc = Var->getLocation();
12054 Owner.Range = Var->getSourceRange();
12055
12056 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12057 diagnoseRetainCycle(*this, Capturer, Owner);
12058}
12059
Ted Kremenek9304da92012-12-21 08:04:28 +000012060static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12061 Expr *RHS, bool isProperty) {
12062 // Check if RHS is an Objective-C object literal, which also can get
12063 // immediately zapped in a weak reference. Note that we explicitly
12064 // allow ObjCStringLiterals, since those are designed to never really die.
12065 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012066
Ted Kremenek64873352012-12-21 22:46:35 +000012067 // This enum needs to match with the 'select' in
12068 // warn_objc_arc_literal_assign (off-by-1).
12069 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12070 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12071 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012072
12073 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000012074 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000012075 << (isProperty ? 0 : 1)
12076 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000012077
12078 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000012079}
12080
Ted Kremenekc1f014a2012-12-21 19:45:30 +000012081static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12082 Qualifiers::ObjCLifetime LT,
12083 Expr *RHS, bool isProperty) {
12084 // Strip off any implicit cast added to get to the one ARC-specific.
12085 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12086 if (cast->getCastKind() == CK_ARCConsumeObject) {
12087 S.Diag(Loc, diag::warn_arc_retained_assign)
12088 << (LT == Qualifiers::OCL_ExplicitNone)
12089 << (isProperty ? 0 : 1)
12090 << RHS->getSourceRange();
12091 return true;
12092 }
12093 RHS = cast->getSubExpr();
12094 }
12095
12096 if (LT == Qualifiers::OCL_Weak &&
12097 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12098 return true;
12099
12100 return false;
12101}
12102
Ted Kremenekb36234d2012-12-21 08:04:20 +000012103bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12104 QualType LHS, Expr *RHS) {
12105 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12106
12107 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12108 return false;
12109
12110 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12111 return true;
12112
12113 return false;
12114}
12115
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012116void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12117 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012118 QualType LHSType;
12119 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000012120 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012121 ObjCPropertyRefExpr *PRE
12122 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12123 if (PRE && !PRE->isImplicitProperty()) {
12124 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12125 if (PD)
12126 LHSType = PD->getType();
12127 }
12128
12129 if (LHSType.isNull())
12130 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000012131
12132 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12133
12134 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012135 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000012136 getCurFunction()->markSafeWeakUse(LHS);
12137 }
12138
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012139 if (checkUnsafeAssigns(Loc, LHSType, RHS))
12140 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000012141
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012142 // FIXME. Check for other life times.
12143 if (LT != Qualifiers::OCL_None)
12144 return;
12145
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012146 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012147 if (PRE->isImplicitProperty())
12148 return;
12149 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12150 if (!PD)
12151 return;
12152
Bill Wendling44426052012-12-20 19:22:21 +000012153 unsigned Attributes = PD->getPropertyAttributes();
12154 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012155 // when 'assign' attribute was not explicitly specified
12156 // by user, ignore it and rely on property type itself
12157 // for lifetime info.
12158 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12159 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12160 LHSType->isObjCRetainableType())
12161 return;
12162
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012163 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000012164 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012165 Diag(Loc, diag::warn_arc_retained_property_assign)
12166 << RHS->getSourceRange();
12167 return;
12168 }
12169 RHS = cast->getSubExpr();
12170 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000012171 }
Bill Wendling44426052012-12-20 19:22:21 +000012172 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000012173 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12174 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000012175 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000012176 }
12177}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012178
12179//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12180
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012181static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12182 SourceLocation StmtLoc,
12183 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012184 // Do not warn if the body is a macro that expands to nothing, e.g:
12185 //
12186 // #define CALL(x)
12187 // if (condition)
12188 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012189 if (Body->hasLeadingEmptyMacro())
12190 return false;
12191
12192 // Get line numbers of statement and body.
12193 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000012194 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012195 &StmtLineInvalid);
12196 if (StmtLineInvalid)
12197 return false;
12198
12199 bool BodyLineInvalid;
12200 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12201 &BodyLineInvalid);
12202 if (BodyLineInvalid)
12203 return false;
12204
12205 // Warn if null statement and body are on the same line.
12206 if (StmtLine != BodyLine)
12207 return false;
12208
12209 return true;
12210}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012211
12212void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12213 const Stmt *Body,
12214 unsigned DiagID) {
12215 // Since this is a syntactic check, don't emit diagnostic for template
12216 // instantiations, this just adds noise.
12217 if (CurrentInstantiationScope)
12218 return;
12219
12220 // The body should be a null statement.
12221 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12222 if (!NBody)
12223 return;
12224
12225 // Do the usual checks.
12226 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12227 return;
12228
12229 Diag(NBody->getSemiLoc(), DiagID);
12230 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12231}
12232
12233void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12234 const Stmt *PossibleBody) {
12235 assert(!CurrentInstantiationScope); // Ensured by caller
12236
12237 SourceLocation StmtLoc;
12238 const Stmt *Body;
12239 unsigned DiagID;
12240 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12241 StmtLoc = FS->getRParenLoc();
12242 Body = FS->getBody();
12243 DiagID = diag::warn_empty_for_body;
12244 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
12245 StmtLoc = WS->getCond()->getSourceRange().getEnd();
12246 Body = WS->getBody();
12247 DiagID = diag::warn_empty_while_body;
12248 } else
12249 return; // Neither `for' nor `while'.
12250
12251 // The body should be a null statement.
12252 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12253 if (!NBody)
12254 return;
12255
12256 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012257 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012258 return;
12259
12260 // Do the usual checks.
12261 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12262 return;
12263
12264 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12265 // noise level low, emit diagnostics only if for/while is followed by a
12266 // CompoundStmt, e.g.:
12267 // for (int i = 0; i < n; i++);
12268 // {
12269 // a(i);
12270 // }
12271 // or if for/while is followed by a statement with more indentation
12272 // than for/while itself:
12273 // for (int i = 0; i < n; i++);
12274 // a(i);
12275 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12276 if (!ProbableTypo) {
12277 bool BodyColInvalid;
12278 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12279 PossibleBody->getLocStart(),
12280 &BodyColInvalid);
12281 if (BodyColInvalid)
12282 return;
12283
12284 bool StmtColInvalid;
12285 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12286 S->getLocStart(),
12287 &StmtColInvalid);
12288 if (StmtColInvalid)
12289 return;
12290
12291 if (BodyCol > StmtCol)
12292 ProbableTypo = true;
12293 }
12294
12295 if (ProbableTypo) {
12296 Diag(NBody->getSemiLoc(), DiagID);
12297 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12298 }
12299}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012300
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012301//===--- CHECK: Warn on self move with std::move. -------------------------===//
12302
12303/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12304void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12305 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012306 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12307 return;
12308
Richard Smith51ec0cf2017-02-21 01:17:38 +000012309 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012310 return;
12311
12312 // Strip parens and casts away.
12313 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12314 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12315
12316 // Check for a call expression
12317 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12318 if (!CE || CE->getNumArgs() != 1)
12319 return;
12320
12321 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012322 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012323 return;
12324
12325 // Get argument from std::move
12326 RHSExpr = CE->getArg(0);
12327
12328 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12329 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12330
12331 // Two DeclRefExpr's, check that the decls are the same.
12332 if (LHSDeclRef && RHSDeclRef) {
12333 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12334 return;
12335 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12336 RHSDeclRef->getDecl()->getCanonicalDecl())
12337 return;
12338
12339 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12340 << LHSExpr->getSourceRange()
12341 << RHSExpr->getSourceRange();
12342 return;
12343 }
12344
12345 // Member variables require a different approach to check for self moves.
12346 // MemberExpr's are the same if every nested MemberExpr refers to the same
12347 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12348 // the base Expr's are CXXThisExpr's.
12349 const Expr *LHSBase = LHSExpr;
12350 const Expr *RHSBase = RHSExpr;
12351 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12352 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12353 if (!LHSME || !RHSME)
12354 return;
12355
12356 while (LHSME && RHSME) {
12357 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12358 RHSME->getMemberDecl()->getCanonicalDecl())
12359 return;
12360
12361 LHSBase = LHSME->getBase();
12362 RHSBase = RHSME->getBase();
12363 LHSME = dyn_cast<MemberExpr>(LHSBase);
12364 RHSME = dyn_cast<MemberExpr>(RHSBase);
12365 }
12366
12367 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12368 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12369 if (LHSDeclRef && RHSDeclRef) {
12370 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12371 return;
12372 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12373 RHSDeclRef->getDecl()->getCanonicalDecl())
12374 return;
12375
12376 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12377 << LHSExpr->getSourceRange()
12378 << RHSExpr->getSourceRange();
12379 return;
12380 }
12381
12382 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12383 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12384 << LHSExpr->getSourceRange()
12385 << RHSExpr->getSourceRange();
12386}
12387
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012388//===--- Layout compatibility ----------------------------------------------//
12389
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012390static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012391
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012392/// Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012393static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012394 // C++11 [dcl.enum] p8:
12395 // Two enumeration types are layout-compatible if they have the same
12396 // underlying type.
12397 return ED1->isComplete() && ED2->isComplete() &&
12398 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12399}
12400
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012401/// Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012402static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12403 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012404 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12405 return false;
12406
12407 if (Field1->isBitField() != Field2->isBitField())
12408 return false;
12409
12410 if (Field1->isBitField()) {
12411 // Make sure that the bit-fields are the same length.
12412 unsigned Bits1 = Field1->getBitWidthValue(C);
12413 unsigned Bits2 = Field2->getBitWidthValue(C);
12414
12415 if (Bits1 != Bits2)
12416 return false;
12417 }
12418
12419 return true;
12420}
12421
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012422/// Check if two standard-layout structs are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012423/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012424static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12425 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012426 // If both records are C++ classes, check that base classes match.
12427 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12428 // If one of records is a CXXRecordDecl we are in C++ mode,
12429 // thus the other one is a CXXRecordDecl, too.
12430 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12431 // Check number of base classes.
12432 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12433 return false;
12434
12435 // Check the base classes.
12436 for (CXXRecordDecl::base_class_const_iterator
12437 Base1 = D1CXX->bases_begin(),
12438 BaseEnd1 = D1CXX->bases_end(),
12439 Base2 = D2CXX->bases_begin();
12440 Base1 != BaseEnd1;
12441 ++Base1, ++Base2) {
12442 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12443 return false;
12444 }
12445 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12446 // If only RD2 is a C++ class, it should have zero base classes.
12447 if (D2CXX->getNumBases() > 0)
12448 return false;
12449 }
12450
12451 // Check the fields.
12452 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12453 Field2End = RD2->field_end(),
12454 Field1 = RD1->field_begin(),
12455 Field1End = RD1->field_end();
12456 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12457 if (!isLayoutCompatible(C, *Field1, *Field2))
12458 return false;
12459 }
12460 if (Field1 != Field1End || Field2 != Field2End)
12461 return false;
12462
12463 return true;
12464}
12465
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012466/// Check if two standard-layout unions are layout-compatible.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012467/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012468static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12469 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012470 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012471 for (auto *Field2 : RD2->fields())
12472 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012473
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012474 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012475 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12476 I = UnmatchedFields.begin(),
12477 E = UnmatchedFields.end();
12478
12479 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012480 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012481 bool Result = UnmatchedFields.erase(*I);
12482 (void) Result;
12483 assert(Result);
12484 break;
12485 }
12486 }
12487 if (I == E)
12488 return false;
12489 }
12490
12491 return UnmatchedFields.empty();
12492}
12493
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012494static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12495 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012496 if (RD1->isUnion() != RD2->isUnion())
12497 return false;
12498
12499 if (RD1->isUnion())
12500 return isLayoutCompatibleUnion(C, RD1, RD2);
12501 else
12502 return isLayoutCompatibleStruct(C, RD1, RD2);
12503}
12504
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012505/// Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012506static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012507 if (T1.isNull() || T2.isNull())
12508 return false;
12509
12510 // C++11 [basic.types] p11:
12511 // If two types T1 and T2 are the same type, then T1 and T2 are
12512 // layout-compatible types.
12513 if (C.hasSameType(T1, T2))
12514 return true;
12515
12516 T1 = T1.getCanonicalType().getUnqualifiedType();
12517 T2 = T2.getCanonicalType().getUnqualifiedType();
12518
12519 const Type::TypeClass TC1 = T1->getTypeClass();
12520 const Type::TypeClass TC2 = T2->getTypeClass();
12521
12522 if (TC1 != TC2)
12523 return false;
12524
12525 if (TC1 == Type::Enum) {
12526 return isLayoutCompatible(C,
12527 cast<EnumType>(T1)->getDecl(),
12528 cast<EnumType>(T2)->getDecl());
12529 } else if (TC1 == Type::Record) {
12530 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12531 return false;
12532
12533 return isLayoutCompatible(C,
12534 cast<RecordType>(T1)->getDecl(),
12535 cast<RecordType>(T2)->getDecl());
12536 }
12537
12538 return false;
12539}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012540
12541//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12542
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012543/// Given a type tag expression find the type tag itself.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012544///
12545/// \param TypeExpr Type tag expression, as it appears in user's code.
12546///
12547/// \param VD Declaration of an identifier that appears in a type tag.
12548///
12549/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012550static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12551 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012552 while(true) {
12553 if (!TypeExpr)
12554 return false;
12555
12556 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12557
12558 switch (TypeExpr->getStmtClass()) {
12559 case Stmt::UnaryOperatorClass: {
12560 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12561 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12562 TypeExpr = UO->getSubExpr();
12563 continue;
12564 }
12565 return false;
12566 }
12567
12568 case Stmt::DeclRefExprClass: {
12569 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12570 *VD = DRE->getDecl();
12571 return true;
12572 }
12573
12574 case Stmt::IntegerLiteralClass: {
12575 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12576 llvm::APInt MagicValueAPInt = IL->getValue();
12577 if (MagicValueAPInt.getActiveBits() <= 64) {
12578 *MagicValue = MagicValueAPInt.getZExtValue();
12579 return true;
12580 } else
12581 return false;
12582 }
12583
12584 case Stmt::BinaryConditionalOperatorClass:
12585 case Stmt::ConditionalOperatorClass: {
12586 const AbstractConditionalOperator *ACO =
12587 cast<AbstractConditionalOperator>(TypeExpr);
12588 bool Result;
12589 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12590 if (Result)
12591 TypeExpr = ACO->getTrueExpr();
12592 else
12593 TypeExpr = ACO->getFalseExpr();
12594 continue;
12595 }
12596 return false;
12597 }
12598
12599 case Stmt::BinaryOperatorClass: {
12600 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12601 if (BO->getOpcode() == BO_Comma) {
12602 TypeExpr = BO->getRHS();
12603 continue;
12604 }
12605 return false;
12606 }
12607
12608 default:
12609 return false;
12610 }
12611 }
12612}
12613
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012614/// Retrieve the C type corresponding to type tag TypeExpr.
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012615///
12616/// \param TypeExpr Expression that specifies a type tag.
12617///
12618/// \param MagicValues Registered magic values.
12619///
12620/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12621/// kind.
12622///
12623/// \param TypeInfo Information about the corresponding C type.
12624///
12625/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012626static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012627 const IdentifierInfo *ArgumentKind,
12628 const Expr *TypeExpr, const ASTContext &Ctx,
12629 const llvm::DenseMap<Sema::TypeTagMagicValue,
12630 Sema::TypeTagData> *MagicValues,
12631 bool &FoundWrongKind,
12632 Sema::TypeTagData &TypeInfo) {
12633 FoundWrongKind = false;
12634
12635 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012636 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012637
12638 uint64_t MagicValue;
12639
12640 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12641 return false;
12642
12643 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012644 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012645 if (I->getArgumentKind() != ArgumentKind) {
12646 FoundWrongKind = true;
12647 return false;
12648 }
12649 TypeInfo.Type = I->getMatchingCType();
12650 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12651 TypeInfo.MustBeNull = I->getMustBeNull();
12652 return true;
12653 }
12654 return false;
12655 }
12656
12657 if (!MagicValues)
12658 return false;
12659
12660 llvm::DenseMap<Sema::TypeTagMagicValue,
12661 Sema::TypeTagData>::const_iterator I =
12662 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12663 if (I == MagicValues->end())
12664 return false;
12665
12666 TypeInfo = I->second;
12667 return true;
12668}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012669
12670void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12671 uint64_t MagicValue, QualType Type,
12672 bool LayoutCompatible,
12673 bool MustBeNull) {
12674 if (!TypeTagForDatatypeMagicValues)
12675 TypeTagForDatatypeMagicValues.reset(
12676 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12677
12678 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12679 (*TypeTagForDatatypeMagicValues)[Magic] =
12680 TypeTagData(Type, LayoutCompatible, MustBeNull);
12681}
12682
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012683static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012684 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12685 if (!BT1)
12686 return false;
12687
12688 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12689 if (!BT2)
12690 return false;
12691
12692 BuiltinType::Kind T1Kind = BT1->getKind();
12693 BuiltinType::Kind T2Kind = BT2->getKind();
12694
12695 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12696 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12697 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12698 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12699}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012700
12701void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012702 const ArrayRef<const Expr *> ExprArgs,
12703 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012704 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12705 bool IsPointerAttr = Attr->getIsPointer();
12706
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012707 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012708 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12709 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012710 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012711 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012712 return;
12713 }
Joel E. Denny81508102018-03-13 14:51:22 +000012714 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012715 bool FoundWrongKind;
12716 TypeTagData TypeInfo;
12717 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12718 TypeTagForDatatypeMagicValues.get(),
12719 FoundWrongKind, TypeInfo)) {
12720 if (FoundWrongKind)
12721 Diag(TypeTagExpr->getExprLoc(),
12722 diag::warn_type_tag_for_datatype_wrong_kind)
12723 << TypeTagExpr->getSourceRange();
12724 return;
12725 }
12726
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012727 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012728 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12729 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012730 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012731 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012732 return;
12733 }
Joel E. Denny81508102018-03-13 14:51:22 +000012734 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012735 if (IsPointerAttr) {
12736 // Skip implicit cast of pointer to `void *' (as a function argument).
12737 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012738 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012739 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012740 ArgumentExpr = ICE->getSubExpr();
12741 }
12742 QualType ArgumentType = ArgumentExpr->getType();
12743
12744 // Passing a `void*' pointer shouldn't trigger a warning.
12745 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12746 return;
12747
12748 if (TypeInfo.MustBeNull) {
12749 // Type tag with matching void type requires a null pointer.
12750 if (!ArgumentExpr->isNullPointerConstant(Context,
12751 Expr::NPC_ValueDependentIsNotNull)) {
12752 Diag(ArgumentExpr->getExprLoc(),
12753 diag::warn_type_safety_null_pointer_required)
12754 << ArgumentKind->getName()
12755 << ArgumentExpr->getSourceRange()
12756 << TypeTagExpr->getSourceRange();
12757 }
12758 return;
12759 }
12760
12761 QualType RequiredType = TypeInfo.Type;
12762 if (IsPointerAttr)
12763 RequiredType = Context.getPointerType(RequiredType);
12764
12765 bool mismatch = false;
12766 if (!TypeInfo.LayoutCompatible) {
12767 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12768
12769 // C++11 [basic.fundamental] p1:
12770 // Plain char, signed char, and unsigned char are three distinct types.
12771 //
12772 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12773 // char' depending on the current char signedness mode.
12774 if (mismatch)
12775 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12776 RequiredType->getPointeeType())) ||
12777 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12778 mismatch = false;
12779 } else
12780 if (IsPointerAttr)
12781 mismatch = !isLayoutCompatible(Context,
12782 ArgumentType->getPointeeType(),
12783 RequiredType->getPointeeType());
12784 else
12785 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12786
12787 if (mismatch)
12788 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012789 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012790 << TypeInfo.LayoutCompatible << RequiredType
12791 << ArgumentExpr->getSourceRange()
12792 << TypeTagExpr->getSourceRange();
12793}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012794
12795void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12796 CharUnits Alignment) {
12797 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12798}
12799
12800void Sema::DiagnoseMisalignedMembers() {
12801 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012802 const NamedDecl *ND = m.RD;
12803 if (ND->getName().empty()) {
12804 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12805 ND = TD;
12806 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012807 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012808 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012809 }
12810 MisalignedMembers.clear();
12811}
12812
12813void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012814 E = E->IgnoreParens();
12815 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012816 return;
12817 if (isa<UnaryOperator>(E) &&
12818 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12819 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12820 if (isa<MemberExpr>(Op)) {
12821 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12822 MisalignedMember(Op));
12823 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012824 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012825 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12826 Context.getTypeAlignInChars(
12827 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012828 MisalignedMembers.erase(MA);
12829 }
12830 }
12831}
12832
12833void Sema::RefersToMemberWithReducedAlignment(
12834 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012835 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12836 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012837 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012838 if (!ME)
12839 return;
12840
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012841 // No need to check expressions with an __unaligned-qualified type.
12842 if (E->getType().getQualifiers().hasUnaligned())
12843 return;
12844
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012845 // For a chain of MemberExpr like "a.b.c.d" this list
12846 // will keep FieldDecl's like [d, c, b].
12847 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12848 const MemberExpr *TopME = nullptr;
12849 bool AnyIsPacked = false;
12850 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012851 QualType BaseType = ME->getBase()->getType();
12852 if (ME->isArrow())
12853 BaseType = BaseType->getPointeeType();
12854 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012855 if (RD->isInvalidDecl())
12856 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012857
12858 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012859 auto *FD = dyn_cast<FieldDecl>(MD);
12860 // We do not care about non-data members.
12861 if (!FD || FD->isInvalidDecl())
12862 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012863
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012864 AnyIsPacked =
12865 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12866 ReverseMemberChain.push_back(FD);
12867
12868 TopME = ME;
12869 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12870 } while (ME);
12871 assert(TopME && "We did not compute a topmost MemberExpr!");
12872
12873 // Not the scope of this diagnostic.
12874 if (!AnyIsPacked)
12875 return;
12876
12877 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12878 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12879 // TODO: The innermost base of the member expression may be too complicated.
12880 // For now, just disregard these cases. This is left for future
12881 // improvement.
12882 if (!DRE && !isa<CXXThisExpr>(TopBase))
12883 return;
12884
12885 // Alignment expected by the whole expression.
12886 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12887
12888 // No need to do anything else with this case.
12889 if (ExpectedAlignment.isOne())
12890 return;
12891
12892 // Synthesize offset of the whole access.
12893 CharUnits Offset;
12894 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12895 I++) {
12896 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12897 }
12898
12899 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12900 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12901 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12902
12903 // The base expression of the innermost MemberExpr may give
12904 // stronger guarantees than the class containing the member.
12905 if (DRE && !TopME->isArrow()) {
12906 const ValueDecl *VD = DRE->getDecl();
12907 if (!VD->getType()->isReferenceType())
12908 CompleteObjectAlignment =
12909 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12910 }
12911
12912 // Check if the synthesized offset fulfills the alignment.
12913 if (Offset % ExpectedAlignment != 0 ||
12914 // It may fulfill the offset it but the effective alignment may still be
12915 // lower than the expected expression alignment.
12916 CompleteObjectAlignment < ExpectedAlignment) {
12917 // If this happens, we want to determine a sensible culprit of this.
12918 // Intuitively, watching the chain of member expressions from right to
12919 // left, we start with the required alignment (as required by the field
12920 // type) but some packed attribute in that chain has reduced the alignment.
12921 // It may happen that another packed structure increases it again. But if
12922 // we are here such increase has not been enough. So pointing the first
12923 // FieldDecl that either is packed or else its RecordDecl is,
12924 // seems reasonable.
12925 FieldDecl *FD = nullptr;
12926 CharUnits Alignment;
12927 for (FieldDecl *FDI : ReverseMemberChain) {
12928 if (FDI->hasAttr<PackedAttr>() ||
12929 FDI->getParent()->hasAttr<PackedAttr>()) {
12930 FD = FDI;
12931 Alignment = std::min(
12932 Context.getTypeAlignInChars(FD->getType()),
12933 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12934 break;
12935 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012936 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012937 assert(FD && "We did not find a packed FieldDecl!");
12938 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012939 }
12940}
12941
12942void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12943 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012944
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012945 RefersToMemberWithReducedAlignment(
12946 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12947 _2, _3, _4));
12948}