blob: 9e7f5cae28789951c38d127d100a9a38da056be3 [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
687// \brief Performs semantic analysis for the read/write_pipe call.
688// \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
741// \brief Performs a semantic analysis on the {work_group_/sub_group_
742// /_}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
770// \brief Performs a semantic analysis on {work_group_/sub_group_
771// /_}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
793// \brief Performs a semantic analysis on the call to built-in Pipe
794// 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
Anastasia Stulova7f8d6dc2016-07-04 16:07:18 +0000811// \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
Yaxun Liuf7449a12016-05-20 19:54:38 +0000812// \brief Performs semantic analysis for the to_global/local/private call.
813// \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;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001298 case llvm::Triple::mips:
1299 case llvm::Triple::mipsel:
1300 case llvm::Triple::mips64:
1301 case llvm::Triple::mips64el:
1302 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1303 return ExprError();
1304 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001305 case llvm::Triple::systemz:
1306 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1307 return ExprError();
1308 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001309 case llvm::Triple::x86:
1310 case llvm::Triple::x86_64:
1311 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1312 return ExprError();
1313 break;
Kit Bartone50adcb2015-03-30 19:40:59 +00001314 case llvm::Triple::ppc:
1315 case llvm::Triple::ppc64:
1316 case llvm::Triple::ppc64le:
1317 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1318 return ExprError();
1319 break;
Nate Begeman4904e322010-06-08 02:47:44 +00001320 default:
1321 break;
1322 }
1323 }
1324
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001325 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +00001326}
1327
Nate Begeman91e1fea2010-06-14 05:21:25 +00001328// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +00001329static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +00001330 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +00001331 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +00001332 switch (Type.getEltType()) {
1333 case NeonTypeFlags::Int8:
1334 case NeonTypeFlags::Poly8:
1335 return shift ? 7 : (8 << IsQuad) - 1;
1336 case NeonTypeFlags::Int16:
1337 case NeonTypeFlags::Poly16:
1338 return shift ? 15 : (4 << IsQuad) - 1;
1339 case NeonTypeFlags::Int32:
1340 return shift ? 31 : (2 << IsQuad) - 1;
1341 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +00001342 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +00001343 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001344 case NeonTypeFlags::Poly128:
1345 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +00001346 case NeonTypeFlags::Float16:
1347 assert(!shift && "cannot shift float types!");
1348 return (4 << IsQuad) - 1;
1349 case NeonTypeFlags::Float32:
1350 assert(!shift && "cannot shift float types!");
1351 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001352 case NeonTypeFlags::Float64:
1353 assert(!shift && "cannot shift float types!");
1354 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +00001355 }
David Blaikie8a40f702012-01-17 06:56:22 +00001356 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +00001357}
1358
Bob Wilsone4d77232011-11-08 05:04:11 +00001359/// getNeonEltType - Return the QualType corresponding to the elements of
1360/// the vector type specified by the NeonTypeFlags. This is used to check
1361/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +00001362static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +00001363 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +00001364 switch (Flags.getEltType()) {
1365 case NeonTypeFlags::Int8:
1366 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1367 case NeonTypeFlags::Int16:
1368 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1369 case NeonTypeFlags::Int32:
1370 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1371 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +00001372 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +00001373 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1374 else
1375 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1376 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001377 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +00001378 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001379 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +00001380 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +00001381 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +00001382 if (IsInt64Long)
1383 return Context.UnsignedLongTy;
1384 else
1385 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +00001386 case NeonTypeFlags::Poly128:
1387 break;
Bob Wilsone4d77232011-11-08 05:04:11 +00001388 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +00001389 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001390 case NeonTypeFlags::Float32:
1391 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +00001392 case NeonTypeFlags::Float64:
1393 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +00001394 }
David Blaikie8a40f702012-01-17 06:56:22 +00001395 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +00001396}
1397
Tim Northover12670412014-02-19 10:37:05 +00001398bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +00001399 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +00001400 uint64_t mask = 0;
1401 unsigned TV = 0;
1402 int PtrArgNum = -1;
1403 bool HasConstPtr = false;
1404 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +00001405#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001406#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001407#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001408#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001409 }
1410
1411 // For NEON intrinsics which are overloaded on vector element type, validate
1412 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +00001413 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +00001414 if (mask) {
1415 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1416 return true;
1417
1418 TV = Result.getLimitedValue(64);
1419 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1420 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +00001421 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +00001422 }
1423
1424 if (PtrArgNum >= 0) {
1425 // Check that pointer arguments have the specified type.
1426 Expr *Arg = TheCall->getArg(PtrArgNum);
1427 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1428 Arg = ICE->getSubExpr();
1429 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1430 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +00001431
Tim Northovera2ee4332014-03-29 15:09:45 +00001432 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Joerg Sonnenberger47006c52017-01-09 11:40:41 +00001433 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1434 Arch == llvm::Triple::aarch64_be;
Tim Northovera2ee4332014-03-29 15:09:45 +00001435 bool IsInt64Long =
1436 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1437 QualType EltTy =
1438 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +00001439 if (HasConstPtr)
1440 EltTy = EltTy.withConst();
1441 QualType LHSTy = Context.getPointerType(EltTy);
1442 AssignConvertType ConvTy;
1443 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1444 if (RHS.isInvalid())
1445 return true;
1446 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1447 RHS.get(), AA_Assigning))
1448 return true;
1449 }
1450
1451 // For NEON intrinsics which take an immediate value as part of the
1452 // instruction, range check them here.
1453 unsigned i = 0, l = 0, u = 0;
1454 switch (BuiltinID) {
1455 default:
1456 return false;
Tim Northover12670412014-02-19 10:37:05 +00001457#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001458#include "clang/Basic/arm_neon.inc"
Abderrazek Zaafranice8746d2018-01-19 23:11:18 +00001459#include "clang/Basic/arm_fp16.inc"
Tim Northover12670412014-02-19 10:37:05 +00001460#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +00001461 }
Tim Northover2fe823a2013-08-01 09:23:19 +00001462
Richard Sandiford28940af2014-04-16 08:47:51 +00001463 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +00001464}
1465
Tim Northovera2ee4332014-03-29 15:09:45 +00001466bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1467 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +00001468 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001469 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +00001470 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001471 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +00001472 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001473 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1474 BuiltinID == AArch64::BI__builtin_arm_strex ||
1475 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +00001476 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +00001477 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001478 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1479 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1480 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +00001481
1482 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1483
1484 // Ensure that we have the proper number of arguments.
1485 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1486 return true;
1487
1488 // Inspect the pointer argument of the atomic builtin. This should always be
1489 // a pointer type, whose element is an integral scalar or pointer type.
1490 // Because it is a pointer type, we don't have to worry about any implicit
1491 // casts here.
1492 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1493 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1494 if (PointerArgRes.isInvalid())
1495 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001496 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001497
1498 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1499 if (!pointerType) {
1500 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1501 << PointerArg->getType() << PointerArg->getSourceRange();
1502 return true;
1503 }
1504
1505 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1506 // task is to insert the appropriate casts into the AST. First work out just
1507 // what the appropriate type is.
1508 QualType ValType = pointerType->getPointeeType();
1509 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1510 if (IsLdrex)
1511 AddrType.addConst();
1512
1513 // Issue a warning if the cast is dodgy.
1514 CastKind CastNeeded = CK_NoOp;
1515 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1516 CastNeeded = CK_BitCast;
1517 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1518 << PointerArg->getType()
1519 << Context.getPointerType(AddrType)
1520 << AA_Passing << PointerArg->getSourceRange();
1521 }
1522
1523 // Finally, do the cast and replace the argument with the corrected version.
1524 AddrType = Context.getPointerType(AddrType);
1525 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1526 if (PointerArgRes.isInvalid())
1527 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001528 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001529
1530 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1531
1532 // In general, we allow ints, floats and pointers to be loaded and stored.
1533 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1534 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1535 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1536 << PointerArg->getType() << PointerArg->getSourceRange();
1537 return true;
1538 }
1539
1540 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001541 if (Context.getTypeSize(ValType) > MaxWidth) {
1542 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001543 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1544 << PointerArg->getType() << PointerArg->getSourceRange();
1545 return true;
1546 }
1547
1548 switch (ValType.getObjCLifetime()) {
1549 case Qualifiers::OCL_None:
1550 case Qualifiers::OCL_ExplicitNone:
1551 // okay
1552 break;
1553
1554 case Qualifiers::OCL_Weak:
1555 case Qualifiers::OCL_Strong:
1556 case Qualifiers::OCL_Autoreleasing:
1557 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1558 << ValType << PointerArg->getSourceRange();
1559 return true;
1560 }
1561
Tim Northover6aacd492013-07-16 09:47:53 +00001562 if (IsLdrex) {
1563 TheCall->setType(ValType);
1564 return false;
1565 }
1566
1567 // Initialize the argument to be stored.
1568 ExprResult ValArg = TheCall->getArg(0);
1569 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1570 Context, ValType, /*consume*/ false);
1571 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1572 if (ValArg.isInvalid())
1573 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001574 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001575
1576 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1577 // but the custom checker bypasses all default analysis.
1578 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001579 return false;
1580}
1581
Nate Begeman4904e322010-06-08 02:47:44 +00001582bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover6aacd492013-07-16 09:47:53 +00001583 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001584 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1585 BuiltinID == ARM::BI__builtin_arm_strex ||
1586 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001587 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001588 }
1589
Yi Kong26d104a2014-08-13 19:18:14 +00001590 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1591 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1592 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1593 }
1594
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001595 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1596 BuiltinID == ARM::BI__builtin_arm_wsr64)
1597 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1598
1599 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1600 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1601 BuiltinID == ARM::BI__builtin_arm_wsr ||
1602 BuiltinID == ARM::BI__builtin_arm_wsrp)
1603 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1604
Tim Northover12670412014-02-19 10:37:05 +00001605 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1606 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001607
Yi Kong4efadfb2014-07-03 16:01:25 +00001608 // For intrinsics which take an immediate value as part of the instruction,
1609 // range check them here.
Sjoerd Meijer293da702017-12-07 09:54:39 +00001610 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begemand773fe62010-06-13 04:47:52 +00001611 switch (BuiltinID) {
1612 default: return false;
Sjoerd Meijer293da702017-12-07 09:54:39 +00001613 case ARM::BI__builtin_arm_ssat:
1614 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1615 case ARM::BI__builtin_arm_usat:
1616 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1617 case ARM::BI__builtin_arm_ssat16:
1618 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1619 case ARM::BI__builtin_arm_usat16:
1620 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
Nate Begemanf568b072010-08-03 21:32:34 +00001621 case ARM::BI__builtin_arm_vcvtr_f:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001622 case ARM::BI__builtin_arm_vcvtr_d:
1623 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
Weiming Zhao87bb4922013-11-12 21:42:50 +00001624 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001625 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001626 case ARM::BI__builtin_arm_isb:
Sjoerd Meijer293da702017-12-07 09:54:39 +00001627 case ARM::BI__builtin_arm_dbg:
1628 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
Richard Sandiford28940af2014-04-16 08:47:51 +00001629 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001630}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001631
Tim Northover573cbee2014-05-24 12:52:07 +00001632bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001633 CallExpr *TheCall) {
Tim Northover573cbee2014-05-24 12:52:07 +00001634 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001635 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1636 BuiltinID == AArch64::BI__builtin_arm_strex ||
1637 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001638 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1639 }
1640
Yi Konga5548432014-08-13 19:18:20 +00001641 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1642 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1643 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1644 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1645 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1646 }
1647
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001648 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1649 BuiltinID == AArch64::BI__builtin_arm_wsr64)
Tim Northover54e50002016-04-13 17:08:55 +00001650 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001651
1652 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1653 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1654 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1655 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1656 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1657
Tim Northovera2ee4332014-03-29 15:09:45 +00001658 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1659 return true;
1660
Yi Kong19a29ac2014-07-17 10:52:06 +00001661 // For intrinsics which take an immediate value as part of the instruction,
1662 // range check them here.
1663 unsigned i = 0, l = 0, u = 0;
1664 switch (BuiltinID) {
1665 default: return false;
1666 case AArch64::BI__builtin_arm_dmb:
1667 case AArch64::BI__builtin_arm_dsb:
1668 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1669 }
1670
Yi Kong19a29ac2014-07-17 10:52:06 +00001671 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001672}
1673
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001674// CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1675// intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1676// ordering for DSP is unspecified. MSA is ordered by the data format used
1677// by the underlying instruction i.e., df/m, df/n and then by size.
1678//
1679// FIXME: The size tests here should instead be tablegen'd along with the
1680// definitions from include/clang/Basic/BuiltinsMips.def.
1681// FIXME: GCC is strict on signedness for some of these intrinsics, we should
1682// be too.
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001683bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001684 unsigned i = 0, l = 0, u = 0, m = 0;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001685 switch (BuiltinID) {
1686 default: return false;
1687 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1688 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001689 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1690 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1691 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1692 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1693 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001694 // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1695 // df/m field.
1696 // These intrinsics take an unsigned 3 bit immediate.
1697 case Mips::BI__builtin_msa_bclri_b:
1698 case Mips::BI__builtin_msa_bnegi_b:
1699 case Mips::BI__builtin_msa_bseti_b:
1700 case Mips::BI__builtin_msa_sat_s_b:
1701 case Mips::BI__builtin_msa_sat_u_b:
1702 case Mips::BI__builtin_msa_slli_b:
1703 case Mips::BI__builtin_msa_srai_b:
1704 case Mips::BI__builtin_msa_srari_b:
1705 case Mips::BI__builtin_msa_srli_b:
1706 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1707 case Mips::BI__builtin_msa_binsli_b:
1708 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1709 // These intrinsics take an unsigned 4 bit immediate.
1710 case Mips::BI__builtin_msa_bclri_h:
1711 case Mips::BI__builtin_msa_bnegi_h:
1712 case Mips::BI__builtin_msa_bseti_h:
1713 case Mips::BI__builtin_msa_sat_s_h:
1714 case Mips::BI__builtin_msa_sat_u_h:
1715 case Mips::BI__builtin_msa_slli_h:
1716 case Mips::BI__builtin_msa_srai_h:
1717 case Mips::BI__builtin_msa_srari_h:
1718 case Mips::BI__builtin_msa_srli_h:
1719 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1720 case Mips::BI__builtin_msa_binsli_h:
1721 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001722 // These intrinsics take an unsigned 5 bit immediate.
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001723 // The first block of intrinsics actually have an unsigned 5 bit field,
1724 // not a df/n field.
1725 case Mips::BI__builtin_msa_clei_u_b:
1726 case Mips::BI__builtin_msa_clei_u_h:
1727 case Mips::BI__builtin_msa_clei_u_w:
1728 case Mips::BI__builtin_msa_clei_u_d:
1729 case Mips::BI__builtin_msa_clti_u_b:
1730 case Mips::BI__builtin_msa_clti_u_h:
1731 case Mips::BI__builtin_msa_clti_u_w:
1732 case Mips::BI__builtin_msa_clti_u_d:
1733 case Mips::BI__builtin_msa_maxi_u_b:
1734 case Mips::BI__builtin_msa_maxi_u_h:
1735 case Mips::BI__builtin_msa_maxi_u_w:
1736 case Mips::BI__builtin_msa_maxi_u_d:
1737 case Mips::BI__builtin_msa_mini_u_b:
1738 case Mips::BI__builtin_msa_mini_u_h:
1739 case Mips::BI__builtin_msa_mini_u_w:
1740 case Mips::BI__builtin_msa_mini_u_d:
1741 case Mips::BI__builtin_msa_addvi_b:
1742 case Mips::BI__builtin_msa_addvi_h:
1743 case Mips::BI__builtin_msa_addvi_w:
1744 case Mips::BI__builtin_msa_addvi_d:
1745 case Mips::BI__builtin_msa_bclri_w:
1746 case Mips::BI__builtin_msa_bnegi_w:
1747 case Mips::BI__builtin_msa_bseti_w:
1748 case Mips::BI__builtin_msa_sat_s_w:
1749 case Mips::BI__builtin_msa_sat_u_w:
1750 case Mips::BI__builtin_msa_slli_w:
1751 case Mips::BI__builtin_msa_srai_w:
1752 case Mips::BI__builtin_msa_srari_w:
1753 case Mips::BI__builtin_msa_srli_w:
1754 case Mips::BI__builtin_msa_srlri_w:
1755 case Mips::BI__builtin_msa_subvi_b:
1756 case Mips::BI__builtin_msa_subvi_h:
1757 case Mips::BI__builtin_msa_subvi_w:
1758 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1759 case Mips::BI__builtin_msa_binsli_w:
1760 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1761 // These intrinsics take an unsigned 6 bit immediate.
1762 case Mips::BI__builtin_msa_bclri_d:
1763 case Mips::BI__builtin_msa_bnegi_d:
1764 case Mips::BI__builtin_msa_bseti_d:
1765 case Mips::BI__builtin_msa_sat_s_d:
1766 case Mips::BI__builtin_msa_sat_u_d:
1767 case Mips::BI__builtin_msa_slli_d:
1768 case Mips::BI__builtin_msa_srai_d:
1769 case Mips::BI__builtin_msa_srari_d:
1770 case Mips::BI__builtin_msa_srli_d:
1771 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1772 case Mips::BI__builtin_msa_binsli_d:
1773 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1774 // These intrinsics take a signed 5 bit immediate.
1775 case Mips::BI__builtin_msa_ceqi_b:
1776 case Mips::BI__builtin_msa_ceqi_h:
1777 case Mips::BI__builtin_msa_ceqi_w:
1778 case Mips::BI__builtin_msa_ceqi_d:
1779 case Mips::BI__builtin_msa_clti_s_b:
1780 case Mips::BI__builtin_msa_clti_s_h:
1781 case Mips::BI__builtin_msa_clti_s_w:
1782 case Mips::BI__builtin_msa_clti_s_d:
1783 case Mips::BI__builtin_msa_clei_s_b:
1784 case Mips::BI__builtin_msa_clei_s_h:
1785 case Mips::BI__builtin_msa_clei_s_w:
1786 case Mips::BI__builtin_msa_clei_s_d:
1787 case Mips::BI__builtin_msa_maxi_s_b:
1788 case Mips::BI__builtin_msa_maxi_s_h:
1789 case Mips::BI__builtin_msa_maxi_s_w:
1790 case Mips::BI__builtin_msa_maxi_s_d:
1791 case Mips::BI__builtin_msa_mini_s_b:
1792 case Mips::BI__builtin_msa_mini_s_h:
1793 case Mips::BI__builtin_msa_mini_s_w:
1794 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1795 // These intrinsics take an unsigned 8 bit immediate.
1796 case Mips::BI__builtin_msa_andi_b:
1797 case Mips::BI__builtin_msa_nori_b:
1798 case Mips::BI__builtin_msa_ori_b:
1799 case Mips::BI__builtin_msa_shf_b:
1800 case Mips::BI__builtin_msa_shf_h:
1801 case Mips::BI__builtin_msa_shf_w:
1802 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1803 case Mips::BI__builtin_msa_bseli_b:
1804 case Mips::BI__builtin_msa_bmnzi_b:
1805 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1806 // df/n format
1807 // These intrinsics take an unsigned 4 bit immediate.
1808 case Mips::BI__builtin_msa_copy_s_b:
1809 case Mips::BI__builtin_msa_copy_u_b:
1810 case Mips::BI__builtin_msa_insve_b:
1811 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001812 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1813 // These intrinsics take an unsigned 3 bit immediate.
1814 case Mips::BI__builtin_msa_copy_s_h:
1815 case Mips::BI__builtin_msa_copy_u_h:
1816 case Mips::BI__builtin_msa_insve_h:
1817 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001818 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1819 // These intrinsics take an unsigned 2 bit immediate.
1820 case Mips::BI__builtin_msa_copy_s_w:
1821 case Mips::BI__builtin_msa_copy_u_w:
1822 case Mips::BI__builtin_msa_insve_w:
1823 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001824 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1825 // These intrinsics take an unsigned 1 bit immediate.
1826 case Mips::BI__builtin_msa_copy_s_d:
1827 case Mips::BI__builtin_msa_copy_u_d:
1828 case Mips::BI__builtin_msa_insve_d:
1829 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001830 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1831 // Memory offsets and immediate loads.
1832 // These intrinsics take a signed 10 bit immediate.
Petar Jovanovic9b8b9e82017-03-31 16:16:43 +00001833 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001834 case Mips::BI__builtin_msa_ldi_h:
1835 case Mips::BI__builtin_msa_ldi_w:
1836 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1837 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1838 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1839 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1840 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1841 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1842 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1843 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1844 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001845 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001846
Simon Dardis1f90f2d2016-10-19 17:50:52 +00001847 if (!m)
1848 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1849
1850 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1851 SemaBuiltinConstantArgMultiple(TheCall, i, m);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001852}
1853
Kit Bartone50adcb2015-03-30 19:40:59 +00001854bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1855 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001856 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1857 BuiltinID == PPC::BI__builtin_divdeu ||
1858 BuiltinID == PPC::BI__builtin_bpermd;
1859 bool IsTarget64Bit = Context.getTargetInfo()
1860 .getTypeWidth(Context
1861 .getTargetInfo()
1862 .getIntPtrType()) == 64;
1863 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1864 BuiltinID == PPC::BI__builtin_divweu ||
1865 BuiltinID == PPC::BI__builtin_divde ||
1866 BuiltinID == PPC::BI__builtin_divdeu;
1867
1868 if (Is64BitBltin && !IsTarget64Bit)
1869 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1870 << TheCall->getSourceRange();
1871
1872 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1873 (BuiltinID == PPC::BI__builtin_bpermd &&
1874 !Context.getTargetInfo().hasFeature("bpermd")))
1875 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1876 << TheCall->getSourceRange();
1877
Kit Bartone50adcb2015-03-30 19:40:59 +00001878 switch (BuiltinID) {
1879 default: return false;
1880 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1881 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1882 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1883 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1884 case PPC::BI__builtin_tbegin:
1885 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1886 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1887 case PPC::BI__builtin_tabortwc:
1888 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1889 case PPC::BI__builtin_tabortwci:
1890 case PPC::BI__builtin_tabortdci:
1891 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1892 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
Tony Jiangbbc48e92017-05-24 15:13:32 +00001893 case PPC::BI__builtin_vsx_xxpermdi:
Tony Jiang9aa2c032017-05-24 15:54:13 +00001894 case PPC::BI__builtin_vsx_xxsldwi:
Tony Jiangbbc48e92017-05-24 15:13:32 +00001895 return SemaBuiltinVSX(TheCall);
Kit Bartone50adcb2015-03-30 19:40:59 +00001896 }
1897 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1898}
1899
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001900bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1901 CallExpr *TheCall) {
1902 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1903 Expr *Arg = TheCall->getArg(0);
1904 llvm::APSInt AbortCode(32);
1905 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1906 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1907 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1908 << Arg->getSourceRange();
1909 }
1910
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001911 // For intrinsics which take an immediate value as part of the instruction,
1912 // range check them here.
1913 unsigned i = 0, l = 0, u = 0;
1914 switch (BuiltinID) {
1915 default: return false;
1916 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1917 case SystemZ::BI__builtin_s390_verimb:
1918 case SystemZ::BI__builtin_s390_verimh:
1919 case SystemZ::BI__builtin_s390_verimf:
1920 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1921 case SystemZ::BI__builtin_s390_vfaeb:
1922 case SystemZ::BI__builtin_s390_vfaeh:
1923 case SystemZ::BI__builtin_s390_vfaef:
1924 case SystemZ::BI__builtin_s390_vfaebs:
1925 case SystemZ::BI__builtin_s390_vfaehs:
1926 case SystemZ::BI__builtin_s390_vfaefs:
1927 case SystemZ::BI__builtin_s390_vfaezb:
1928 case SystemZ::BI__builtin_s390_vfaezh:
1929 case SystemZ::BI__builtin_s390_vfaezf:
1930 case SystemZ::BI__builtin_s390_vfaezbs:
1931 case SystemZ::BI__builtin_s390_vfaezhs:
1932 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001933 case SystemZ::BI__builtin_s390_vfisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001934 case SystemZ::BI__builtin_s390_vfidb:
1935 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1936 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001937 case SystemZ::BI__builtin_s390_vftcisb:
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001938 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1939 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1940 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1941 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1942 case SystemZ::BI__builtin_s390_vstrcb:
1943 case SystemZ::BI__builtin_s390_vstrch:
1944 case SystemZ::BI__builtin_s390_vstrcf:
1945 case SystemZ::BI__builtin_s390_vstrczb:
1946 case SystemZ::BI__builtin_s390_vstrczh:
1947 case SystemZ::BI__builtin_s390_vstrczf:
1948 case SystemZ::BI__builtin_s390_vstrcbs:
1949 case SystemZ::BI__builtin_s390_vstrchs:
1950 case SystemZ::BI__builtin_s390_vstrcfs:
1951 case SystemZ::BI__builtin_s390_vstrczbs:
1952 case SystemZ::BI__builtin_s390_vstrczhs:
1953 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
Ulrich Weigandcac24ab2017-07-17 17:45:57 +00001954 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1955 case SystemZ::BI__builtin_s390_vfminsb:
1956 case SystemZ::BI__builtin_s390_vfmaxsb:
1957 case SystemZ::BI__builtin_s390_vfmindb:
1958 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001959 }
1960 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001961}
1962
Craig Topper5ba2c502015-11-07 08:08:31 +00001963/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1964/// This checks that the target supports __builtin_cpu_supports and
1965/// that the string argument is constant and valid.
1966static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1967 Expr *Arg = TheCall->getArg(0);
1968
1969 // Check if the argument is a string literal.
1970 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1971 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1972 << Arg->getSourceRange();
1973
1974 // Check the contents of the string.
1975 StringRef Feature =
1976 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1977 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1978 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1979 << Arg->getSourceRange();
1980 return false;
1981}
1982
Craig Topper699ae0c2017-08-10 20:28:30 +00001983/// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1984/// This checks that the target supports __builtin_cpu_is and
1985/// that the string argument is constant and valid.
1986static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1987 Expr *Arg = TheCall->getArg(0);
1988
1989 // Check if the argument is a string literal.
1990 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1991 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1992 << Arg->getSourceRange();
1993
1994 // Check the contents of the string.
1995 StringRef Feature =
1996 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1997 if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1998 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1999 << Arg->getSourceRange();
2000 return false;
2001}
2002
Craig Toppera7e253e2016-09-23 04:48:31 +00002003// Check if the rounding mode is legal.
2004bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
2005 // Indicates if this instruction has rounding control or just SAE.
2006 bool HasRC = false;
2007
2008 unsigned ArgNum = 0;
2009 switch (BuiltinID) {
2010 default:
2011 return false;
2012 case X86::BI__builtin_ia32_vcvttsd2si32:
2013 case X86::BI__builtin_ia32_vcvttsd2si64:
2014 case X86::BI__builtin_ia32_vcvttsd2usi32:
2015 case X86::BI__builtin_ia32_vcvttsd2usi64:
2016 case X86::BI__builtin_ia32_vcvttss2si32:
2017 case X86::BI__builtin_ia32_vcvttss2si64:
2018 case X86::BI__builtin_ia32_vcvttss2usi32:
2019 case X86::BI__builtin_ia32_vcvttss2usi64:
2020 ArgNum = 1;
2021 break;
2022 case X86::BI__builtin_ia32_cvtps2pd512_mask:
2023 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
2024 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
2025 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
2026 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
2027 case X86::BI__builtin_ia32_cvttps2dq512_mask:
2028 case X86::BI__builtin_ia32_cvttps2qq512_mask:
2029 case X86::BI__builtin_ia32_cvttps2udq512_mask:
2030 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
2031 case X86::BI__builtin_ia32_exp2pd_mask:
2032 case X86::BI__builtin_ia32_exp2ps_mask:
2033 case X86::BI__builtin_ia32_getexppd512_mask:
2034 case X86::BI__builtin_ia32_getexpps512_mask:
2035 case X86::BI__builtin_ia32_rcp28pd_mask:
2036 case X86::BI__builtin_ia32_rcp28ps_mask:
2037 case X86::BI__builtin_ia32_rsqrt28pd_mask:
2038 case X86::BI__builtin_ia32_rsqrt28ps_mask:
2039 case X86::BI__builtin_ia32_vcomisd:
2040 case X86::BI__builtin_ia32_vcomiss:
2041 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
2042 ArgNum = 3;
2043 break;
2044 case X86::BI__builtin_ia32_cmppd512_mask:
2045 case X86::BI__builtin_ia32_cmpps512_mask:
2046 case X86::BI__builtin_ia32_cmpsd_mask:
2047 case X86::BI__builtin_ia32_cmpss_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002048 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002049 case X86::BI__builtin_ia32_getexpsd128_round_mask:
2050 case X86::BI__builtin_ia32_getexpss128_round_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002051 case X86::BI__builtin_ia32_maxpd512_mask:
2052 case X86::BI__builtin_ia32_maxps512_mask:
2053 case X86::BI__builtin_ia32_maxsd_round_mask:
2054 case X86::BI__builtin_ia32_maxss_round_mask:
2055 case X86::BI__builtin_ia32_minpd512_mask:
2056 case X86::BI__builtin_ia32_minps512_mask:
2057 case X86::BI__builtin_ia32_minsd_round_mask:
2058 case X86::BI__builtin_ia32_minss_round_mask:
Craig Toppera7e253e2016-09-23 04:48:31 +00002059 case X86::BI__builtin_ia32_rcp28sd_round_mask:
2060 case X86::BI__builtin_ia32_rcp28ss_round_mask:
2061 case X86::BI__builtin_ia32_reducepd512_mask:
2062 case X86::BI__builtin_ia32_reduceps512_mask:
2063 case X86::BI__builtin_ia32_rndscalepd_mask:
2064 case X86::BI__builtin_ia32_rndscaleps_mask:
2065 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2066 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2067 ArgNum = 4;
2068 break;
2069 case X86::BI__builtin_ia32_fixupimmpd512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002070 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002071 case X86::BI__builtin_ia32_fixupimmps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002072 case X86::BI__builtin_ia32_fixupimmps512_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002073 case X86::BI__builtin_ia32_fixupimmsd_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002074 case X86::BI__builtin_ia32_fixupimmsd_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002075 case X86::BI__builtin_ia32_fixupimmss_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002076 case X86::BI__builtin_ia32_fixupimmss_maskz:
Craig Toppera7e253e2016-09-23 04:48:31 +00002077 case X86::BI__builtin_ia32_rangepd512_mask:
2078 case X86::BI__builtin_ia32_rangeps512_mask:
2079 case X86::BI__builtin_ia32_rangesd128_round_mask:
2080 case X86::BI__builtin_ia32_rangess128_round_mask:
2081 case X86::BI__builtin_ia32_reducesd_mask:
2082 case X86::BI__builtin_ia32_reducess_mask:
2083 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2084 case X86::BI__builtin_ia32_rndscaless_round_mask:
2085 ArgNum = 5;
2086 break;
Craig Topper7609f1c2016-10-01 21:03:50 +00002087 case X86::BI__builtin_ia32_vcvtsd2si64:
2088 case X86::BI__builtin_ia32_vcvtsd2si32:
2089 case X86::BI__builtin_ia32_vcvtsd2usi32:
2090 case X86::BI__builtin_ia32_vcvtsd2usi64:
2091 case X86::BI__builtin_ia32_vcvtss2si32:
2092 case X86::BI__builtin_ia32_vcvtss2si64:
2093 case X86::BI__builtin_ia32_vcvtss2usi32:
2094 case X86::BI__builtin_ia32_vcvtss2usi64:
2095 ArgNum = 1;
2096 HasRC = true;
2097 break;
Craig Topper8e066312016-11-07 07:01:09 +00002098 case X86::BI__builtin_ia32_cvtsi2sd64:
2099 case X86::BI__builtin_ia32_cvtsi2ss32:
2100 case X86::BI__builtin_ia32_cvtsi2ss64:
Craig Topper7609f1c2016-10-01 21:03:50 +00002101 case X86::BI__builtin_ia32_cvtusi2sd64:
2102 case X86::BI__builtin_ia32_cvtusi2ss32:
2103 case X86::BI__builtin_ia32_cvtusi2ss64:
2104 ArgNum = 2;
2105 HasRC = true;
2106 break;
2107 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2108 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2109 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2110 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2111 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2112 case X86::BI__builtin_ia32_cvtps2qq512_mask:
2113 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2114 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2115 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2116 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2117 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002118 case X86::BI__builtin_ia32_sqrtpd512_mask:
2119 case X86::BI__builtin_ia32_sqrtps512_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002120 ArgNum = 3;
2121 HasRC = true;
2122 break;
2123 case X86::BI__builtin_ia32_addpd512_mask:
2124 case X86::BI__builtin_ia32_addps512_mask:
2125 case X86::BI__builtin_ia32_divpd512_mask:
2126 case X86::BI__builtin_ia32_divps512_mask:
2127 case X86::BI__builtin_ia32_mulpd512_mask:
2128 case X86::BI__builtin_ia32_mulps512_mask:
2129 case X86::BI__builtin_ia32_subpd512_mask:
2130 case X86::BI__builtin_ia32_subps512_mask:
2131 case X86::BI__builtin_ia32_addss_round_mask:
2132 case X86::BI__builtin_ia32_addsd_round_mask:
2133 case X86::BI__builtin_ia32_divss_round_mask:
2134 case X86::BI__builtin_ia32_divsd_round_mask:
2135 case X86::BI__builtin_ia32_mulss_round_mask:
2136 case X86::BI__builtin_ia32_mulsd_round_mask:
2137 case X86::BI__builtin_ia32_subss_round_mask:
2138 case X86::BI__builtin_ia32_subsd_round_mask:
2139 case X86::BI__builtin_ia32_scalefpd512_mask:
2140 case X86::BI__builtin_ia32_scalefps512_mask:
2141 case X86::BI__builtin_ia32_scalefsd_round_mask:
2142 case X86::BI__builtin_ia32_scalefss_round_mask:
2143 case X86::BI__builtin_ia32_getmantpd512_mask:
2144 case X86::BI__builtin_ia32_getmantps512_mask:
Craig Topper8e066312016-11-07 07:01:09 +00002145 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2146 case X86::BI__builtin_ia32_sqrtsd_round_mask:
2147 case X86::BI__builtin_ia32_sqrtss_round_mask:
Craig Topper7609f1c2016-10-01 21:03:50 +00002148 case X86::BI__builtin_ia32_vfmaddpd512_mask:
2149 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2150 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2151 case X86::BI__builtin_ia32_vfmaddps512_mask:
2152 case X86::BI__builtin_ia32_vfmaddps512_mask3:
2153 case X86::BI__builtin_ia32_vfmaddps512_maskz:
2154 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2155 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2156 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2157 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2158 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2159 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2160 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2161 case X86::BI__builtin_ia32_vfmsubps512_mask3:
2162 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2163 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2164 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2165 case X86::BI__builtin_ia32_vfnmaddps512_mask:
2166 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2167 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2168 case X86::BI__builtin_ia32_vfnmsubps512_mask:
2169 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2170 case X86::BI__builtin_ia32_vfmaddsd3_mask:
2171 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2172 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2173 case X86::BI__builtin_ia32_vfmaddss3_mask:
2174 case X86::BI__builtin_ia32_vfmaddss3_maskz:
2175 case X86::BI__builtin_ia32_vfmaddss3_mask3:
2176 ArgNum = 4;
2177 HasRC = true;
2178 break;
2179 case X86::BI__builtin_ia32_getmantsd_round_mask:
2180 case X86::BI__builtin_ia32_getmantss_round_mask:
2181 ArgNum = 5;
2182 HasRC = true;
2183 break;
Craig Toppera7e253e2016-09-23 04:48:31 +00002184 }
2185
2186 llvm::APSInt Result;
2187
2188 // We can't check the value of a dependent argument.
2189 Expr *Arg = TheCall->getArg(ArgNum);
2190 if (Arg->isTypeDependent() || Arg->isValueDependent())
2191 return false;
2192
2193 // Check constant-ness first.
2194 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2195 return true;
2196
2197 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2198 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2199 // combined with ROUND_NO_EXC.
2200 if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2201 Result == 8/*ROUND_NO_EXC*/ ||
2202 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2203 return false;
2204
2205 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2206 << Arg->getSourceRange();
2207}
2208
Craig Topperdf5beb22017-03-13 17:16:50 +00002209// Check if the gather/scatter scale is legal.
2210bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2211 CallExpr *TheCall) {
2212 unsigned ArgNum = 0;
2213 switch (BuiltinID) {
2214 default:
2215 return false;
2216 case X86::BI__builtin_ia32_gatherpfdpd:
2217 case X86::BI__builtin_ia32_gatherpfdps:
2218 case X86::BI__builtin_ia32_gatherpfqpd:
2219 case X86::BI__builtin_ia32_gatherpfqps:
2220 case X86::BI__builtin_ia32_scatterpfdpd:
2221 case X86::BI__builtin_ia32_scatterpfdps:
2222 case X86::BI__builtin_ia32_scatterpfqpd:
2223 case X86::BI__builtin_ia32_scatterpfqps:
2224 ArgNum = 3;
2225 break;
2226 case X86::BI__builtin_ia32_gatherd_pd:
2227 case X86::BI__builtin_ia32_gatherd_pd256:
2228 case X86::BI__builtin_ia32_gatherq_pd:
2229 case X86::BI__builtin_ia32_gatherq_pd256:
2230 case X86::BI__builtin_ia32_gatherd_ps:
2231 case X86::BI__builtin_ia32_gatherd_ps256:
2232 case X86::BI__builtin_ia32_gatherq_ps:
2233 case X86::BI__builtin_ia32_gatherq_ps256:
2234 case X86::BI__builtin_ia32_gatherd_q:
2235 case X86::BI__builtin_ia32_gatherd_q256:
2236 case X86::BI__builtin_ia32_gatherq_q:
2237 case X86::BI__builtin_ia32_gatherq_q256:
2238 case X86::BI__builtin_ia32_gatherd_d:
2239 case X86::BI__builtin_ia32_gatherd_d256:
2240 case X86::BI__builtin_ia32_gatherq_d:
2241 case X86::BI__builtin_ia32_gatherq_d256:
2242 case X86::BI__builtin_ia32_gather3div2df:
2243 case X86::BI__builtin_ia32_gather3div2di:
2244 case X86::BI__builtin_ia32_gather3div4df:
2245 case X86::BI__builtin_ia32_gather3div4di:
2246 case X86::BI__builtin_ia32_gather3div4sf:
2247 case X86::BI__builtin_ia32_gather3div4si:
2248 case X86::BI__builtin_ia32_gather3div8sf:
2249 case X86::BI__builtin_ia32_gather3div8si:
2250 case X86::BI__builtin_ia32_gather3siv2df:
2251 case X86::BI__builtin_ia32_gather3siv2di:
2252 case X86::BI__builtin_ia32_gather3siv4df:
2253 case X86::BI__builtin_ia32_gather3siv4di:
2254 case X86::BI__builtin_ia32_gather3siv4sf:
2255 case X86::BI__builtin_ia32_gather3siv4si:
2256 case X86::BI__builtin_ia32_gather3siv8sf:
2257 case X86::BI__builtin_ia32_gather3siv8si:
2258 case X86::BI__builtin_ia32_gathersiv8df:
2259 case X86::BI__builtin_ia32_gathersiv16sf:
2260 case X86::BI__builtin_ia32_gatherdiv8df:
2261 case X86::BI__builtin_ia32_gatherdiv16sf:
2262 case X86::BI__builtin_ia32_gathersiv8di:
2263 case X86::BI__builtin_ia32_gathersiv16si:
2264 case X86::BI__builtin_ia32_gatherdiv8di:
2265 case X86::BI__builtin_ia32_gatherdiv16si:
2266 case X86::BI__builtin_ia32_scatterdiv2df:
2267 case X86::BI__builtin_ia32_scatterdiv2di:
2268 case X86::BI__builtin_ia32_scatterdiv4df:
2269 case X86::BI__builtin_ia32_scatterdiv4di:
2270 case X86::BI__builtin_ia32_scatterdiv4sf:
2271 case X86::BI__builtin_ia32_scatterdiv4si:
2272 case X86::BI__builtin_ia32_scatterdiv8sf:
2273 case X86::BI__builtin_ia32_scatterdiv8si:
2274 case X86::BI__builtin_ia32_scattersiv2df:
2275 case X86::BI__builtin_ia32_scattersiv2di:
2276 case X86::BI__builtin_ia32_scattersiv4df:
2277 case X86::BI__builtin_ia32_scattersiv4di:
2278 case X86::BI__builtin_ia32_scattersiv4sf:
2279 case X86::BI__builtin_ia32_scattersiv4si:
2280 case X86::BI__builtin_ia32_scattersiv8sf:
2281 case X86::BI__builtin_ia32_scattersiv8si:
2282 case X86::BI__builtin_ia32_scattersiv8df:
2283 case X86::BI__builtin_ia32_scattersiv16sf:
2284 case X86::BI__builtin_ia32_scatterdiv8df:
2285 case X86::BI__builtin_ia32_scatterdiv16sf:
2286 case X86::BI__builtin_ia32_scattersiv8di:
2287 case X86::BI__builtin_ia32_scattersiv16si:
2288 case X86::BI__builtin_ia32_scatterdiv8di:
2289 case X86::BI__builtin_ia32_scatterdiv16si:
2290 ArgNum = 4;
2291 break;
2292 }
2293
2294 llvm::APSInt Result;
2295
2296 // We can't check the value of a dependent argument.
2297 Expr *Arg = TheCall->getArg(ArgNum);
2298 if (Arg->isTypeDependent() || Arg->isValueDependent())
2299 return false;
2300
2301 // Check constant-ness first.
2302 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2303 return true;
2304
2305 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2306 return false;
2307
2308 return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2309 << Arg->getSourceRange();
2310}
2311
Craig Topper51738f82018-04-26 20:14:46 +00002312static bool isX86_32Builtin(unsigned BuiltinID) {
2313 // These builtins only work on x86-32 targets.
2314 switch (BuiltinID) {
2315 case X86::BI__builtin_ia32_readeflags_u32:
2316 case X86::BI__builtin_ia32_writeeflags_u32:
2317 return true;
2318 }
2319
2320 return false;
2321}
2322
Craig Topperf0ddc892016-09-23 04:48:27 +00002323bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2324 if (BuiltinID == X86::BI__builtin_cpu_supports)
2325 return SemaBuiltinCpuSupports(*this, TheCall);
2326
Craig Topper699ae0c2017-08-10 20:28:30 +00002327 if (BuiltinID == X86::BI__builtin_cpu_is)
2328 return SemaBuiltinCpuIs(*this, TheCall);
2329
Craig Topper51738f82018-04-26 20:14:46 +00002330 // Check for 32-bit only builtins on a 64-bit target.
2331 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2332 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
2333 return Diag(TheCall->getCallee()->getLocStart(),
2334 diag::err_32_bit_builtin_64_bit_tgt);
2335
Craig Toppera7e253e2016-09-23 04:48:31 +00002336 // If the intrinsic has rounding or SAE make sure its valid.
2337 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2338 return true;
2339
Craig Topperdf5beb22017-03-13 17:16:50 +00002340 // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2341 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2342 return true;
2343
Craig Topperf0ddc892016-09-23 04:48:27 +00002344 // For intrinsics which take an immediate value as part of the instruction,
2345 // range check them here.
2346 int i = 0, l = 0, u = 0;
2347 switch (BuiltinID) {
2348 default:
2349 return false;
Richard Trieucc3949d2016-02-18 22:34:54 +00002350 case X86::BI_mm_prefetch:
Craig Topper170de4b2017-12-21 23:50:22 +00002351 i = 1; l = 0; u = 7;
Craig Topper39c87102016-05-18 03:18:12 +00002352 break;
Richard Trieucc3949d2016-02-18 22:34:54 +00002353 case X86::BI__builtin_ia32_sha1rnds4:
Craig Topper39c87102016-05-18 03:18:12 +00002354 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2355 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2356 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2357 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002358 i = 2; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002359 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00002360 case X86::BI__builtin_ia32_vpermil2pd:
2361 case X86::BI__builtin_ia32_vpermil2pd256:
2362 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00002363 case X86::BI__builtin_ia32_vpermil2ps256:
Craig Topper39c87102016-05-18 03:18:12 +00002364 i = 3; l = 0; u = 3;
Richard Trieucc3949d2016-02-18 22:34:54 +00002365 break;
Craig Topper95b0d732015-01-25 23:30:05 +00002366 case X86::BI__builtin_ia32_cmpb128_mask:
2367 case X86::BI__builtin_ia32_cmpw128_mask:
2368 case X86::BI__builtin_ia32_cmpd128_mask:
2369 case X86::BI__builtin_ia32_cmpq128_mask:
2370 case X86::BI__builtin_ia32_cmpb256_mask:
2371 case X86::BI__builtin_ia32_cmpw256_mask:
2372 case X86::BI__builtin_ia32_cmpd256_mask:
2373 case X86::BI__builtin_ia32_cmpq256_mask:
2374 case X86::BI__builtin_ia32_cmpb512_mask:
2375 case X86::BI__builtin_ia32_cmpw512_mask:
2376 case X86::BI__builtin_ia32_cmpd512_mask:
2377 case X86::BI__builtin_ia32_cmpq512_mask:
2378 case X86::BI__builtin_ia32_ucmpb128_mask:
2379 case X86::BI__builtin_ia32_ucmpw128_mask:
2380 case X86::BI__builtin_ia32_ucmpd128_mask:
2381 case X86::BI__builtin_ia32_ucmpq128_mask:
2382 case X86::BI__builtin_ia32_ucmpb256_mask:
2383 case X86::BI__builtin_ia32_ucmpw256_mask:
2384 case X86::BI__builtin_ia32_ucmpd256_mask:
2385 case X86::BI__builtin_ia32_ucmpq256_mask:
2386 case X86::BI__builtin_ia32_ucmpb512_mask:
2387 case X86::BI__builtin_ia32_ucmpw512_mask:
2388 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00002389 case X86::BI__builtin_ia32_ucmpq512_mask:
Craig Topper8dd7d0d2015-02-13 06:04:48 +00002390 case X86::BI__builtin_ia32_vpcomub:
2391 case X86::BI__builtin_ia32_vpcomuw:
2392 case X86::BI__builtin_ia32_vpcomud:
2393 case X86::BI__builtin_ia32_vpcomuq:
2394 case X86::BI__builtin_ia32_vpcomb:
2395 case X86::BI__builtin_ia32_vpcomw:
2396 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00002397 case X86::BI__builtin_ia32_vpcomq:
Craig Topper39c87102016-05-18 03:18:12 +00002398 i = 2; l = 0; u = 7;
2399 break;
2400 case X86::BI__builtin_ia32_roundps:
2401 case X86::BI__builtin_ia32_roundpd:
2402 case X86::BI__builtin_ia32_roundps256:
2403 case X86::BI__builtin_ia32_roundpd256:
Craig Topper39c87102016-05-18 03:18:12 +00002404 i = 1; l = 0; u = 15;
2405 break;
2406 case X86::BI__builtin_ia32_roundss:
2407 case X86::BI__builtin_ia32_roundsd:
2408 case X86::BI__builtin_ia32_rangepd128_mask:
2409 case X86::BI__builtin_ia32_rangepd256_mask:
2410 case X86::BI__builtin_ia32_rangepd512_mask:
2411 case X86::BI__builtin_ia32_rangeps128_mask:
2412 case X86::BI__builtin_ia32_rangeps256_mask:
2413 case X86::BI__builtin_ia32_rangeps512_mask:
2414 case X86::BI__builtin_ia32_getmantsd_round_mask:
2415 case X86::BI__builtin_ia32_getmantss_round_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002416 i = 2; l = 0; u = 15;
2417 break;
2418 case X86::BI__builtin_ia32_cmpps:
2419 case X86::BI__builtin_ia32_cmpss:
2420 case X86::BI__builtin_ia32_cmppd:
2421 case X86::BI__builtin_ia32_cmpsd:
2422 case X86::BI__builtin_ia32_cmpps256:
2423 case X86::BI__builtin_ia32_cmppd256:
2424 case X86::BI__builtin_ia32_cmpps128_mask:
2425 case X86::BI__builtin_ia32_cmppd128_mask:
2426 case X86::BI__builtin_ia32_cmpps256_mask:
2427 case X86::BI__builtin_ia32_cmppd256_mask:
2428 case X86::BI__builtin_ia32_cmpps512_mask:
2429 case X86::BI__builtin_ia32_cmppd512_mask:
2430 case X86::BI__builtin_ia32_cmpsd_mask:
2431 case X86::BI__builtin_ia32_cmpss_mask:
2432 i = 2; l = 0; u = 31;
2433 break;
Craig Topper39c87102016-05-18 03:18:12 +00002434 case X86::BI__builtin_ia32_vcvtps2ph:
Craig Topper23a30222017-11-08 04:54:26 +00002435 case X86::BI__builtin_ia32_vcvtps2ph_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002436 case X86::BI__builtin_ia32_vcvtps2ph256:
Craig Topper23a30222017-11-08 04:54:26 +00002437 case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2438 case X86::BI__builtin_ia32_vcvtps2ph512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002439 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2440 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2441 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2442 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2443 case X86::BI__builtin_ia32_rndscaleps_mask:
2444 case X86::BI__builtin_ia32_rndscalepd_mask:
2445 case X86::BI__builtin_ia32_reducepd128_mask:
2446 case X86::BI__builtin_ia32_reducepd256_mask:
2447 case X86::BI__builtin_ia32_reducepd512_mask:
2448 case X86::BI__builtin_ia32_reduceps128_mask:
2449 case X86::BI__builtin_ia32_reduceps256_mask:
2450 case X86::BI__builtin_ia32_reduceps512_mask:
2451 case X86::BI__builtin_ia32_prold512_mask:
2452 case X86::BI__builtin_ia32_prolq512_mask:
2453 case X86::BI__builtin_ia32_prold128_mask:
2454 case X86::BI__builtin_ia32_prold256_mask:
2455 case X86::BI__builtin_ia32_prolq128_mask:
2456 case X86::BI__builtin_ia32_prolq256_mask:
2457 case X86::BI__builtin_ia32_prord128_mask:
2458 case X86::BI__builtin_ia32_prord256_mask:
2459 case X86::BI__builtin_ia32_prorq128_mask:
2460 case X86::BI__builtin_ia32_prorq256_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002461 case X86::BI__builtin_ia32_fpclasspd128_mask:
2462 case X86::BI__builtin_ia32_fpclasspd256_mask:
2463 case X86::BI__builtin_ia32_fpclassps128_mask:
2464 case X86::BI__builtin_ia32_fpclassps256_mask:
2465 case X86::BI__builtin_ia32_fpclassps512_mask:
2466 case X86::BI__builtin_ia32_fpclasspd512_mask:
2467 case X86::BI__builtin_ia32_fpclasssd_mask:
2468 case X86::BI__builtin_ia32_fpclassss_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002469 i = 1; l = 0; u = 255;
2470 break;
Craig Topper39c87102016-05-18 03:18:12 +00002471 case X86::BI__builtin_ia32_palignr128:
2472 case X86::BI__builtin_ia32_palignr256:
Craig Topper39c87102016-05-18 03:18:12 +00002473 case X86::BI__builtin_ia32_palignr512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002474 case X86::BI__builtin_ia32_vcomisd:
2475 case X86::BI__builtin_ia32_vcomiss:
2476 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2477 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2478 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2479 case X86::BI__builtin_ia32_shuf_i64x2_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002480 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2481 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2482 case X86::BI__builtin_ia32_dbpsadbw512_mask:
Craig Topper91926432018-01-11 01:38:02 +00002483 case X86::BI__builtin_ia32_vpshldd128_mask:
2484 case X86::BI__builtin_ia32_vpshldd256_mask:
2485 case X86::BI__builtin_ia32_vpshldd512_mask:
2486 case X86::BI__builtin_ia32_vpshldq128_mask:
2487 case X86::BI__builtin_ia32_vpshldq256_mask:
2488 case X86::BI__builtin_ia32_vpshldq512_mask:
2489 case X86::BI__builtin_ia32_vpshldw128_mask:
2490 case X86::BI__builtin_ia32_vpshldw256_mask:
2491 case X86::BI__builtin_ia32_vpshldw512_mask:
2492 case X86::BI__builtin_ia32_vpshrdd128_mask:
2493 case X86::BI__builtin_ia32_vpshrdd256_mask:
2494 case X86::BI__builtin_ia32_vpshrdd512_mask:
2495 case X86::BI__builtin_ia32_vpshrdq128_mask:
2496 case X86::BI__builtin_ia32_vpshrdq256_mask:
2497 case X86::BI__builtin_ia32_vpshrdq512_mask:
2498 case X86::BI__builtin_ia32_vpshrdw128_mask:
2499 case X86::BI__builtin_ia32_vpshrdw256_mask:
2500 case X86::BI__builtin_ia32_vpshrdw512_mask:
Craig Topper39c87102016-05-18 03:18:12 +00002501 i = 2; l = 0; u = 255;
2502 break;
2503 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2504 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2505 case X86::BI__builtin_ia32_fixupimmps512_mask:
2506 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2507 case X86::BI__builtin_ia32_fixupimmsd_mask:
2508 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2509 case X86::BI__builtin_ia32_fixupimmss_mask:
2510 case X86::BI__builtin_ia32_fixupimmss_maskz:
2511 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2512 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2513 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2514 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2515 case X86::BI__builtin_ia32_fixupimmps128_mask:
2516 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2517 case X86::BI__builtin_ia32_fixupimmps256_mask:
2518 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2519 case X86::BI__builtin_ia32_pternlogd512_mask:
2520 case X86::BI__builtin_ia32_pternlogd512_maskz:
2521 case X86::BI__builtin_ia32_pternlogq512_mask:
2522 case X86::BI__builtin_ia32_pternlogq512_maskz:
2523 case X86::BI__builtin_ia32_pternlogd128_mask:
2524 case X86::BI__builtin_ia32_pternlogd128_maskz:
2525 case X86::BI__builtin_ia32_pternlogd256_mask:
2526 case X86::BI__builtin_ia32_pternlogd256_maskz:
2527 case X86::BI__builtin_ia32_pternlogq128_mask:
2528 case X86::BI__builtin_ia32_pternlogq128_maskz:
2529 case X86::BI__builtin_ia32_pternlogq256_mask:
2530 case X86::BI__builtin_ia32_pternlogq256_maskz:
2531 i = 3; l = 0; u = 255;
2532 break;
Craig Topper9625db02017-03-12 22:19:10 +00002533 case X86::BI__builtin_ia32_gatherpfdpd:
2534 case X86::BI__builtin_ia32_gatherpfdps:
2535 case X86::BI__builtin_ia32_gatherpfqpd:
2536 case X86::BI__builtin_ia32_gatherpfqps:
2537 case X86::BI__builtin_ia32_scatterpfdpd:
2538 case X86::BI__builtin_ia32_scatterpfdps:
2539 case X86::BI__builtin_ia32_scatterpfqpd:
2540 case X86::BI__builtin_ia32_scatterpfqps:
Craig Topperf771f79b2017-03-31 17:22:30 +00002541 i = 4; l = 2; u = 3;
Craig Topper9625db02017-03-12 22:19:10 +00002542 break;
Craig Topper39c87102016-05-18 03:18:12 +00002543 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2544 case X86::BI__builtin_ia32_rndscaless_round_mask:
2545 i = 4; l = 0; u = 255;
Richard Trieucc3949d2016-02-18 22:34:54 +00002546 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002547 }
Craig Topperdd84ec52014-12-27 07:00:08 +00002548 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002549}
2550
Richard Smith55ce3522012-06-25 20:30:08 +00002551/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2552/// parameter with the FormatAttr's correct format_idx and firstDataArg.
2553/// Returns true when the format fits the function and the FormatStringInfo has
2554/// been populated.
2555bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2556 FormatStringInfo *FSI) {
2557 FSI->HasVAListArg = Format->getFirstArg() == 0;
2558 FSI->FormatIdx = Format->getFormatIdx() - 1;
2559 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002560
Richard Smith55ce3522012-06-25 20:30:08 +00002561 // The way the format attribute works in GCC, the implicit this argument
2562 // of member functions is counted. However, it doesn't appear in our own
2563 // lists, so decrement format_idx in that case.
2564 if (IsCXXMember) {
2565 if(FSI->FormatIdx == 0)
2566 return false;
2567 --FSI->FormatIdx;
2568 if (FSI->FirstDataArg != 0)
2569 --FSI->FirstDataArg;
2570 }
2571 return true;
2572}
Mike Stump11289f42009-09-09 15:08:12 +00002573
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002574/// Checks if a the given expression evaluates to null.
2575///
2576/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00002577static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002578 // If the expression has non-null type, it doesn't evaluate to null.
2579 if (auto nullability
2580 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2581 if (*nullability == NullabilityKind::NonNull)
2582 return false;
2583 }
2584
Ted Kremeneka146db32014-01-17 06:24:47 +00002585 // As a special case, transparent unions initialized with zero are
2586 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002587 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00002588 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2589 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002590 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00002591 if (const InitListExpr *ILE =
2592 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002593 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00002594 }
2595
2596 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00002597 return (!Expr->isValueDependent() &&
2598 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2599 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00002600}
2601
2602static void CheckNonNullArgument(Sema &S,
2603 const Expr *ArgExpr,
2604 SourceLocation CallSiteLoc) {
2605 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00002606 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2607 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00002608}
2609
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002610bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2611 FormatStringInfo FSI;
2612 if ((GetFormatStringType(Format) == FST_NSString) &&
2613 getFormatStringInfo(Format, false, &FSI)) {
2614 Idx = FSI.FormatIdx;
2615 return true;
2616 }
2617 return false;
2618}
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002619
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002620/// \brief Diagnose use of %s directive in an NSString which is being passed
2621/// as formatting string to formatting method.
2622static void
2623DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2624 const NamedDecl *FDecl,
2625 Expr **Args,
2626 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002627 unsigned Idx = 0;
2628 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002629 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2630 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002631 Idx = 2;
2632 Format = true;
2633 }
2634 else
2635 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2636 if (S.GetFormatNSStringIdx(I, Idx)) {
2637 Format = true;
2638 break;
2639 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002640 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002641 if (!Format || NumArgs <= Idx)
2642 return;
2643 const Expr *FormatExpr = Args[Idx];
2644 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2645 FormatExpr = CSCE->getSubExpr();
2646 const StringLiteral *FormatString;
2647 if (const ObjCStringLiteral *OSL =
2648 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2649 FormatString = OSL->getString();
2650 else
2651 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2652 if (!FormatString)
2653 return;
2654 if (S.FormatStringHasSArg(FormatString)) {
2655 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2656 << "%s" << 1 << 1;
2657 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2658 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002659 }
2660}
2661
Douglas Gregorb4866e82015-06-19 18:13:19 +00002662/// Determine whether the given type has a non-null nullability annotation.
2663static bool isNonNullType(ASTContext &ctx, QualType type) {
2664 if (auto nullability = type->getNullability(ctx))
2665 return *nullability == NullabilityKind::NonNull;
2666
2667 return false;
2668}
2669
Ted Kremenek2bc73332014-01-17 06:24:43 +00002670static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00002671 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002672 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00002673 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00002674 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002675 assert((FDecl || Proto) && "Need a function declaration or prototype");
2676
Ted Kremenek9aedc152014-01-17 06:24:56 +00002677 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00002678 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00002679 if (FDecl) {
2680 // Handle the nonnull attribute on the function/method declaration itself.
2681 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2682 if (!NonNull->args_size()) {
2683 // Easy case: all pointer arguments are nonnull.
2684 for (const auto *Arg : Args)
2685 if (S.isValidPointerAttrType(Arg->getType()))
2686 CheckNonNullArgument(S, Arg, CallSiteLoc);
2687 return;
2688 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002689
Joel E. Denny81508102018-03-13 14:51:22 +00002690 for (const ParamIdx &Idx : NonNull->args()) {
2691 unsigned IdxAST = Idx.getASTIndex();
2692 if (IdxAST >= Args.size())
Douglas Gregorb4866e82015-06-19 18:13:19 +00002693 continue;
2694 if (NonNullArgs.empty())
2695 NonNullArgs.resize(Args.size());
Joel E. Denny81508102018-03-13 14:51:22 +00002696 NonNullArgs.set(IdxAST);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002697 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002698 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002699 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002700
Douglas Gregorb4866e82015-06-19 18:13:19 +00002701 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2702 // Handle the nonnull attribute on the parameters of the
2703 // function/method.
2704 ArrayRef<ParmVarDecl*> parms;
2705 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2706 parms = FD->parameters();
2707 else
2708 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2709
2710 unsigned ParamIndex = 0;
2711 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2712 I != E; ++I, ++ParamIndex) {
2713 const ParmVarDecl *PVD = *I;
2714 if (PVD->hasAttr<NonNullAttr>() ||
2715 isNonNullType(S.Context, PVD->getType())) {
2716 if (NonNullArgs.empty())
2717 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00002718
Douglas Gregorb4866e82015-06-19 18:13:19 +00002719 NonNullArgs.set(ParamIndex);
2720 }
2721 }
2722 } else {
2723 // If we have a non-function, non-method declaration but no
2724 // function prototype, try to dig out the function prototype.
2725 if (!Proto) {
2726 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2727 QualType type = VD->getType().getNonReferenceType();
2728 if (auto pointerType = type->getAs<PointerType>())
2729 type = pointerType->getPointeeType();
2730 else if (auto blockType = type->getAs<BlockPointerType>())
2731 type = blockType->getPointeeType();
2732 // FIXME: data member pointers?
2733
2734 // Dig out the function prototype, if there is one.
2735 Proto = type->getAs<FunctionProtoType>();
2736 }
2737 }
2738
2739 // Fill in non-null argument information from the nullability
2740 // information on the parameter types (if we have them).
2741 if (Proto) {
2742 unsigned Index = 0;
2743 for (auto paramType : Proto->getParamTypes()) {
2744 if (isNonNullType(S.Context, paramType)) {
2745 if (NonNullArgs.empty())
2746 NonNullArgs.resize(Args.size());
2747
2748 NonNullArgs.set(Index);
2749 }
2750
2751 ++Index;
2752 }
2753 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00002754 }
Richard Smith588bd9b2014-08-27 04:59:42 +00002755
Douglas Gregorb4866e82015-06-19 18:13:19 +00002756 // Check for non-null arguments.
2757 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2758 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00002759 if (NonNullArgs[ArgIndex])
2760 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002761 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00002762}
2763
Richard Smith55ce3522012-06-25 20:30:08 +00002764/// Handles the checks for format strings, non-POD arguments to vararg
George Burgess IVce6284b2017-01-28 02:19:40 +00002765/// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2766/// attributes.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002767void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
George Burgess IVce6284b2017-01-28 02:19:40 +00002768 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2769 bool IsMemberFunction, SourceLocation Loc,
2770 SourceRange Range, VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00002771 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00002772 if (CurContext->isDependentContext())
2773 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00002774
Ted Kremenekb8176da2010-09-09 04:33:05 +00002775 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00002776 llvm::SmallBitVector CheckedVarArgs;
2777 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002778 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002779 // Only create vector if there are format attributes.
2780 CheckedVarArgs.resize(Args.size());
2781
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002782 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00002783 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00002784 }
Richard Smithd7293d72013-08-05 18:49:43 +00002785 }
Richard Smith55ce3522012-06-25 20:30:08 +00002786
2787 // Refuse POD arguments that weren't caught by the format string
2788 // checks above.
Richard Smith836de6b2016-12-19 23:59:34 +00002789 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2790 if (CallType != VariadicDoesNotApply &&
2791 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00002792 unsigned NumParams = Proto ? Proto->getNumParams()
2793 : FDecl && isa<FunctionDecl>(FDecl)
2794 ? cast<FunctionDecl>(FDecl)->getNumParams()
2795 : FDecl && isa<ObjCMethodDecl>(FDecl)
2796 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2797 : 0;
2798
Alp Toker9cacbab2014-01-20 20:26:09 +00002799 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002800 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00002801 if (const Expr *Arg = Args[ArgIdx]) {
2802 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2803 checkVariadicArgument(Arg, CallType);
2804 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00002805 }
Richard Smithd7293d72013-08-05 18:49:43 +00002806 }
Mike Stump11289f42009-09-09 15:08:12 +00002807
Douglas Gregorb4866e82015-06-19 18:13:19 +00002808 if (FDecl || Proto) {
2809 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002810
Richard Trieu41bc0992013-06-22 00:20:41 +00002811 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00002812 if (FDecl) {
2813 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +00002814 CheckArgumentWithTypeTag(I, Args, Loc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00002815 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00002816 }
George Burgess IVce6284b2017-01-28 02:19:40 +00002817
2818 if (FD)
2819 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
Richard Smith55ce3522012-06-25 20:30:08 +00002820}
2821
2822/// CheckConstructorCall - Check a constructor call for correctness and safety
2823/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002824void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2825 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002826 const FunctionProtoType *Proto,
2827 SourceLocation Loc) {
2828 VariadicCallType CallType =
2829 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
George Burgess IVce6284b2017-01-28 02:19:40 +00002830 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2831 Loc, SourceRange(), CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00002832}
2833
2834/// CheckFunctionCall - Check a direct function call for various correctness
2835/// and safety properties not strictly enforced by the C type system.
2836bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2837 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002838 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2839 isa<CXXMethodDecl>(FDecl);
2840 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2841 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00002842 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2843 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00002844 Expr** Args = TheCall->getArgs();
2845 unsigned NumArgs = TheCall->getNumArgs();
George Burgess IVce6284b2017-01-28 02:19:40 +00002846
2847 Expr *ImplicitThis = nullptr;
Eli Friedmanadf42182012-10-11 00:34:15 +00002848 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00002849 // If this is a call to a member operator, hide the first argument
2850 // from checkCall.
2851 // FIXME: Our choice of AST representation here is less than ideal.
George Burgess IVce6284b2017-01-28 02:19:40 +00002852 ImplicitThis = Args[0];
Eli Friedman726d11c2012-10-11 00:30:58 +00002853 ++Args;
2854 --NumArgs;
George Burgess IVce6284b2017-01-28 02:19:40 +00002855 } else if (IsMemberFunction)
2856 ImplicitThis =
2857 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2858
2859 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00002860 IsMemberFunction, TheCall->getRParenLoc(),
2861 TheCall->getCallee()->getSourceRange(), CallType);
2862
2863 IdentifierInfo *FnInfo = FDecl->getIdentifier();
2864 // None of the checks below are needed for functions that don't have
2865 // simple names (e.g., C++ conversion functions).
2866 if (!FnInfo)
2867 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002868
Richard Trieua7f30b12016-12-06 01:42:28 +00002869 CheckAbsoluteValueFunction(TheCall, FDecl);
2870 CheckMaxUnsignedZero(TheCall, FDecl);
Richard Trieu67c00712016-12-05 23:41:46 +00002871
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002872 if (getLangOpts().ObjC1)
2873 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00002874
Anna Zaks22122702012-01-17 00:37:07 +00002875 unsigned CMId = FDecl->getMemoryFunctionKind();
2876 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00002877 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00002878
Anna Zaks201d4892012-01-13 21:52:01 +00002879 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00002880 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00002881 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00002882 else if (CMId == Builtin::BIstrncat)
2883 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00002884 else
Anna Zaks22122702012-01-17 00:37:07 +00002885 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002886
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002887 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00002888}
2889
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002890bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00002891 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00002892 VariadicCallType CallType =
2893 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002894
George Burgess IVce6284b2017-01-28 02:19:40 +00002895 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2896 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002897 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002898
2899 return false;
2900}
2901
Richard Trieu664c4c62013-06-20 21:03:13 +00002902bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2903 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00002904 QualType Ty;
2905 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002906 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002907 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00002908 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00002909 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002910 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002911
Douglas Gregorb4866e82015-06-19 18:13:19 +00002912 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2913 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002914 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002915
Richard Trieu664c4c62013-06-20 21:03:13 +00002916 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00002917 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00002918 CallType = VariadicDoesNotApply;
2919 } else if (Ty->isBlockPointerType()) {
2920 CallType = VariadicBlock;
2921 } else { // Ty->isFunctionPointerType()
2922 CallType = VariadicFunction;
2923 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002924
George Burgess IVce6284b2017-01-28 02:19:40 +00002925 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
Douglas Gregorb4866e82015-06-19 18:13:19 +00002926 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2927 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00002928 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00002929
Anders Carlssonbc4c1072009-08-16 01:56:34 +00002930 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00002931}
2932
Richard Trieu41bc0992013-06-22 00:20:41 +00002933/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2934/// such as function pointers returned from functions.
2935bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002936 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00002937 TheCall->getCallee());
George Burgess IVce6284b2017-01-28 02:19:40 +00002938 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00002939 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00002940 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00002941 TheCall->getCallee()->getSourceRange(), CallType);
2942
2943 return false;
2944}
2945
Tim Northovere94a34c2014-03-11 10:49:14 +00002946static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
JF Bastiendda2cb12016-04-18 18:01:49 +00002947 if (!llvm::isValidAtomicOrderingCABI(Ordering))
Tim Northovere94a34c2014-03-11 10:49:14 +00002948 return false;
2949
JF Bastiendda2cb12016-04-18 18:01:49 +00002950 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
Tim Northovere94a34c2014-03-11 10:49:14 +00002951 switch (Op) {
2952 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00002953 case AtomicExpr::AO__opencl_atomic_init:
Tim Northovere94a34c2014-03-11 10:49:14 +00002954 llvm_unreachable("There is no ordering argument for an init");
2955
2956 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00002957 case AtomicExpr::AO__opencl_atomic_load:
Tim Northovere94a34c2014-03-11 10:49:14 +00002958 case AtomicExpr::AO__atomic_load_n:
2959 case AtomicExpr::AO__atomic_load:
JF Bastiendda2cb12016-04-18 18:01:49 +00002960 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2961 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002962
2963 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00002964 case AtomicExpr::AO__opencl_atomic_store:
Tim Northovere94a34c2014-03-11 10:49:14 +00002965 case AtomicExpr::AO__atomic_store:
2966 case AtomicExpr::AO__atomic_store_n:
JF Bastiendda2cb12016-04-18 18:01:49 +00002967 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2968 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2969 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
Tim Northovere94a34c2014-03-11 10:49:14 +00002970
2971 default:
2972 return true;
2973 }
2974}
2975
Richard Smithfeea8832012-04-12 05:08:17 +00002976ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2977 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002978 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2979 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002980
Yaxun Liu39195062017-08-04 18:16:31 +00002981 // All the non-OpenCL operations take one of the following forms.
2982 // The OpenCL operations take the __c11 forms with one extra argument for
2983 // synchronization scope.
Richard Smithfeea8832012-04-12 05:08:17 +00002984 enum {
2985 // C __c11_atomic_init(A *, C)
2986 Init,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002987
Richard Smithfeea8832012-04-12 05:08:17 +00002988 // C __c11_atomic_load(A *, int)
2989 Load,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002990
Richard Smithfeea8832012-04-12 05:08:17 +00002991 // void __atomic_load(A *, CP, int)
Eric Fiselier8d662442016-03-30 23:39:56 +00002992 LoadCopy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002993
Eric Fiselier8d662442016-03-30 23:39:56 +00002994 // void __atomic_store(A *, CP, int)
Richard Smithfeea8832012-04-12 05:08:17 +00002995 Copy,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002996
Richard Smithfeea8832012-04-12 05:08:17 +00002997 // C __c11_atomic_add(A *, M, int)
2998 Arithmetic,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00002999
Richard Smithfeea8832012-04-12 05:08:17 +00003000 // C __atomic_exchange_n(A *, CP, int)
3001 Xchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003002
Richard Smithfeea8832012-04-12 05:08:17 +00003003 // void __atomic_exchange(A *, C *, CP, int)
3004 GNUXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003005
Richard Smithfeea8832012-04-12 05:08:17 +00003006 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
3007 C11CmpXchg,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003008
Richard Smithfeea8832012-04-12 05:08:17 +00003009 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
3010 GNUCmpXchg
3011 } Form = Init;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003012
Yaxun Liu39195062017-08-04 18:16:31 +00003013 const unsigned NumForm = GNUCmpXchg + 1;
Eric Fiselier8d662442016-03-30 23:39:56 +00003014 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
3015 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
Richard Smithfeea8832012-04-12 05:08:17 +00003016 // where:
3017 // C is an appropriate type,
3018 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
3019 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
3020 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
3021 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003022
Yaxun Liu39195062017-08-04 18:16:31 +00003023 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
3024 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
3025 "need to update code for modified forms");
Gabor Horvath98bd0982015-03-16 09:59:54 +00003026 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
3027 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
3028 AtomicExpr::AO__atomic_load,
3029 "need to update code for modified C11 atomics");
Yaxun Liu39195062017-08-04 18:16:31 +00003030 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
3031 Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
3032 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
3033 Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
3034 IsOpenCL;
Richard Smithfeea8832012-04-12 05:08:17 +00003035 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
3036 Op == AtomicExpr::AO__atomic_store_n ||
3037 Op == AtomicExpr::AO__atomic_exchange_n ||
3038 Op == AtomicExpr::AO__atomic_compare_exchange_n;
3039 bool IsAddSub = false;
3040
3041 switch (Op) {
3042 case AtomicExpr::AO__c11_atomic_init:
Yaxun Liu39195062017-08-04 18:16:31 +00003043 case AtomicExpr::AO__opencl_atomic_init:
Richard Smithfeea8832012-04-12 05:08:17 +00003044 Form = Init;
3045 break;
3046
3047 case AtomicExpr::AO__c11_atomic_load:
Yaxun Liu39195062017-08-04 18:16:31 +00003048 case AtomicExpr::AO__opencl_atomic_load:
Richard Smithfeea8832012-04-12 05:08:17 +00003049 case AtomicExpr::AO__atomic_load_n:
3050 Form = Load;
3051 break;
3052
Richard Smithfeea8832012-04-12 05:08:17 +00003053 case AtomicExpr::AO__atomic_load:
Eric Fiselier8d662442016-03-30 23:39:56 +00003054 Form = LoadCopy;
3055 break;
3056
3057 case AtomicExpr::AO__c11_atomic_store:
Yaxun Liu39195062017-08-04 18:16:31 +00003058 case AtomicExpr::AO__opencl_atomic_store:
Richard Smithfeea8832012-04-12 05:08:17 +00003059 case AtomicExpr::AO__atomic_store:
3060 case AtomicExpr::AO__atomic_store_n:
3061 Form = Copy;
3062 break;
3063
3064 case AtomicExpr::AO__c11_atomic_fetch_add:
3065 case AtomicExpr::AO__c11_atomic_fetch_sub:
Yaxun Liu39195062017-08-04 18:16:31 +00003066 case AtomicExpr::AO__opencl_atomic_fetch_add:
3067 case AtomicExpr::AO__opencl_atomic_fetch_sub:
3068 case AtomicExpr::AO__opencl_atomic_fetch_min:
3069 case AtomicExpr::AO__opencl_atomic_fetch_max:
Richard Smithfeea8832012-04-12 05:08:17 +00003070 case AtomicExpr::AO__atomic_fetch_add:
3071 case AtomicExpr::AO__atomic_fetch_sub:
3072 case AtomicExpr::AO__atomic_add_fetch:
3073 case AtomicExpr::AO__atomic_sub_fetch:
3074 IsAddSub = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003075 LLVM_FALLTHROUGH;
Richard Smithfeea8832012-04-12 05:08:17 +00003076 case AtomicExpr::AO__c11_atomic_fetch_and:
3077 case AtomicExpr::AO__c11_atomic_fetch_or:
3078 case AtomicExpr::AO__c11_atomic_fetch_xor:
Yaxun Liu39195062017-08-04 18:16:31 +00003079 case AtomicExpr::AO__opencl_atomic_fetch_and:
3080 case AtomicExpr::AO__opencl_atomic_fetch_or:
3081 case AtomicExpr::AO__opencl_atomic_fetch_xor:
Richard Smithfeea8832012-04-12 05:08:17 +00003082 case AtomicExpr::AO__atomic_fetch_and:
3083 case AtomicExpr::AO__atomic_fetch_or:
3084 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003085 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003086 case AtomicExpr::AO__atomic_and_fetch:
3087 case AtomicExpr::AO__atomic_or_fetch:
3088 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003089 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003090 Form = Arithmetic;
3091 break;
3092
3093 case AtomicExpr::AO__c11_atomic_exchange:
Yaxun Liu39195062017-08-04 18:16:31 +00003094 case AtomicExpr::AO__opencl_atomic_exchange:
Richard Smithfeea8832012-04-12 05:08:17 +00003095 case AtomicExpr::AO__atomic_exchange_n:
3096 Form = Xchg;
3097 break;
3098
3099 case AtomicExpr::AO__atomic_exchange:
3100 Form = GNUXchg;
3101 break;
3102
3103 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3104 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
Yaxun Liu39195062017-08-04 18:16:31 +00003105 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3106 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
Richard Smithfeea8832012-04-12 05:08:17 +00003107 Form = C11CmpXchg;
3108 break;
3109
3110 case AtomicExpr::AO__atomic_compare_exchange:
3111 case AtomicExpr::AO__atomic_compare_exchange_n:
3112 Form = GNUCmpXchg;
3113 break;
3114 }
3115
Yaxun Liu39195062017-08-04 18:16:31 +00003116 unsigned AdjustedNumArgs = NumArgs[Form];
3117 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3118 ++AdjustedNumArgs;
Richard Smithfeea8832012-04-12 05:08:17 +00003119 // Check we have the right number of arguments.
Yaxun Liu39195062017-08-04 18:16:31 +00003120 if (TheCall->getNumArgs() < AdjustedNumArgs) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003121 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003122 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003123 << TheCall->getCallee()->getSourceRange();
3124 return ExprError();
Yaxun Liu39195062017-08-04 18:16:31 +00003125 } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3126 Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003127 diag::err_typecheck_call_too_many_args)
Yaxun Liu39195062017-08-04 18:16:31 +00003128 << 0 << AdjustedNumArgs << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003129 << TheCall->getCallee()->getSourceRange();
3130 return ExprError();
3131 }
3132
Richard Smithfeea8832012-04-12 05:08:17 +00003133 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003134 Expr *Ptr = TheCall->getArg(0);
George Burgess IV92b43a42016-07-21 03:28:13 +00003135 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3136 if (ConvertedPtr.isInvalid())
3137 return ExprError();
3138
3139 Ptr = ConvertedPtr.get();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003140 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3141 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00003142 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003143 << Ptr->getType() << Ptr->getSourceRange();
3144 return ExprError();
3145 }
3146
Richard Smithfeea8832012-04-12 05:08:17 +00003147 // For a __c11 builtin, this should be a pointer to an _Atomic type.
3148 QualType AtomTy = pointerType->getPointeeType(); // 'A'
3149 QualType ValType = AtomTy; // 'C'
3150 if (IsC11) {
3151 if (!AtomTy->isAtomicType()) {
3152 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3153 << Ptr->getType() << Ptr->getSourceRange();
3154 return ExprError();
3155 }
Yaxun Liu39195062017-08-04 18:16:31 +00003156 if (AtomTy.isConstQualified() ||
3157 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
Richard Smithe00921a2012-09-15 06:09:58 +00003158 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
Yaxun Liu39195062017-08-04 18:16:31 +00003159 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3160 << Ptr->getSourceRange();
Richard Smithe00921a2012-09-15 06:09:58 +00003161 return ExprError();
3162 }
Richard Smithfeea8832012-04-12 05:08:17 +00003163 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiselier8d662442016-03-30 23:39:56 +00003164 } else if (Form != Load && Form != LoadCopy) {
Eric Fiseliera3a7c562015-10-04 00:11:02 +00003165 if (ValType.isConstQualified()) {
3166 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3167 << Ptr->getType() << Ptr->getSourceRange();
3168 return ExprError();
3169 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003170 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003171
Richard Smithfeea8832012-04-12 05:08:17 +00003172 // For an arithmetic operation, the implied arithmetic must be well-formed.
3173 if (Form == Arithmetic) {
3174 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3175 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3176 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3177 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3178 return ExprError();
3179 }
3180 if (!IsAddSub && !ValType->isIntegerType()) {
3181 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3182 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3183 return ExprError();
3184 }
David Majnemere85cff82015-01-28 05:48:06 +00003185 if (IsC11 && ValType->isPointerType() &&
3186 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3187 diag::err_incomplete_type)) {
3188 return ExprError();
3189 }
Richard Smithfeea8832012-04-12 05:08:17 +00003190 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3191 // For __atomic_*_n operations, the value type must be a scalar integral or
3192 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003193 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00003194 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3195 return ExprError();
3196 }
3197
Eli Friedmanaa769812013-09-11 03:49:34 +00003198 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3199 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00003200 // For GNU atomics, require a trivially-copyable type. This is not part of
3201 // the GNU atomics specification, but we enforce it for sanity.
3202 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003203 << Ptr->getType() << Ptr->getSourceRange();
3204 return ExprError();
3205 }
3206
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003207 switch (ValType.getObjCLifetime()) {
3208 case Qualifiers::OCL_None:
3209 case Qualifiers::OCL_ExplicitNone:
3210 // okay
3211 break;
3212
3213 case Qualifiers::OCL_Weak:
3214 case Qualifiers::OCL_Strong:
3215 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00003216 // FIXME: Can this happen? By this point, ValType should be known
3217 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003218 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3219 << ValType << Ptr->getSourceRange();
3220 return ExprError();
3221 }
3222
David Majnemerc6eb6502015-06-03 00:26:35 +00003223 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
3224 // volatile-ness of the pointee-type inject itself into the result or the
Eric Fiselier8d662442016-03-30 23:39:56 +00003225 // other operands. Similarly atomic_load can take a pointer to a const 'A'.
David Majnemerc6eb6502015-06-03 00:26:35 +00003226 ValType.removeLocalVolatile();
Eric Fiselier8d662442016-03-30 23:39:56 +00003227 ValType.removeLocalConst();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003228 QualType ResultType = ValType;
Yaxun Liu39195062017-08-04 18:16:31 +00003229 if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3230 Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003231 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00003232 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003233 ResultType = Context.BoolTy;
3234
Richard Smithfeea8832012-04-12 05:08:17 +00003235 // The type of a parameter passed 'by value'. In the GNU atomics, such
3236 // arguments are actually passed as pointers.
3237 QualType ByValType = ValType; // 'CP'
3238 if (!IsC11 && !IsN)
3239 ByValType = Ptr->getType();
3240
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003241 // The first argument --- the pointer --- has a fixed type; we
3242 // deduce the types of the rest of the arguments accordingly. Walk
3243 // the remaining arguments, converting them to the deduced value type.
Yaxun Liu39195062017-08-04 18:16:31 +00003244 for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003245 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00003246 if (i < NumVals[Form] + 1) {
3247 switch (i) {
3248 case 1:
3249 // The second argument is the non-atomic operand. For arithmetic, this
3250 // is always passed by value, and for a compare_exchange it is always
3251 // passed by address. For the rest, GNU uses by-address and C11 uses
3252 // by-value.
3253 assert(Form != Load);
3254 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3255 Ty = ValType;
3256 else if (Form == Copy || Form == Xchg)
3257 Ty = ByValType;
3258 else if (Form == Arithmetic)
3259 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003260 else {
3261 Expr *ValArg = TheCall->getArg(i);
Alex Lorenz67522152016-11-23 16:57:03 +00003262 // Treat this argument as _Nonnull as we want to show a warning if
3263 // NULL is passed into it.
3264 CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
Alexander Richardson6d989432017-10-15 18:48:14 +00003265 LangAS AS = LangAS::Default;
Anastasia Stulova76fd1052015-12-22 15:14:54 +00003266 // Keep address space of non-atomic pointer type.
3267 if (const PointerType *PtrTy =
3268 ValArg->getType()->getAs<PointerType>()) {
3269 AS = PtrTy->getPointeeType().getAddressSpace();
3270 }
3271 Ty = Context.getPointerType(
3272 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3273 }
Richard Smithfeea8832012-04-12 05:08:17 +00003274 break;
3275 case 2:
3276 // The third argument to compare_exchange / GNU exchange is a
3277 // (pointer to a) desired value.
3278 Ty = ByValType;
3279 break;
3280 case 3:
3281 // The fourth argument to GNU compare_exchange is a 'weak' flag.
3282 Ty = Context.BoolTy;
3283 break;
3284 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003285 } else {
Yaxun Liu39195062017-08-04 18:16:31 +00003286 // The order(s) and scope are always converted to int.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003287 Ty = Context.IntTy;
3288 }
Richard Smithfeea8832012-04-12 05:08:17 +00003289
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003290 InitializedEntity Entity =
3291 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00003292 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003293 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3294 if (Arg.isInvalid())
3295 return true;
3296 TheCall->setArg(i, Arg.get());
3297 }
3298
Richard Smithfeea8832012-04-12 05:08:17 +00003299 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003300 SmallVector<Expr*, 5> SubExprs;
3301 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00003302 switch (Form) {
3303 case Init:
3304 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00003305 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003306 break;
3307 case Load:
3308 SubExprs.push_back(TheCall->getArg(1)); // Order
3309 break;
Eric Fiselier8d662442016-03-30 23:39:56 +00003310 case LoadCopy:
Richard Smithfeea8832012-04-12 05:08:17 +00003311 case Copy:
3312 case Arithmetic:
3313 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003314 SubExprs.push_back(TheCall->getArg(2)); // Order
3315 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00003316 break;
3317 case GNUXchg:
3318 // Note, AtomicExpr::getVal2() has a special case for this atomic.
3319 SubExprs.push_back(TheCall->getArg(3)); // Order
3320 SubExprs.push_back(TheCall->getArg(1)); // Val1
3321 SubExprs.push_back(TheCall->getArg(2)); // Val2
3322 break;
3323 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003324 SubExprs.push_back(TheCall->getArg(3)); // Order
3325 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003326 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00003327 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00003328 break;
3329 case GNUCmpXchg:
3330 SubExprs.push_back(TheCall->getArg(4)); // Order
3331 SubExprs.push_back(TheCall->getArg(1)); // Val1
3332 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3333 SubExprs.push_back(TheCall->getArg(2)); // Val2
3334 SubExprs.push_back(TheCall->getArg(3)); // Weak
3335 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003336 }
Tim Northovere94a34c2014-03-11 10:49:14 +00003337
3338 if (SubExprs.size() >= 2 && Form != Init) {
3339 llvm::APSInt Result(32);
3340 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3341 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00003342 Diag(SubExprs[1]->getLocStart(),
3343 diag::warn_atomic_op_has_invalid_memory_order)
3344 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00003345 }
3346
Yaxun Liu30d652a2017-08-15 16:02:49 +00003347 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3348 auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3349 llvm::APSInt Result(32);
3350 if (Scope->isIntegerConstantExpr(Result, Context) &&
3351 !ScopeModel->isValid(Result.getZExtValue())) {
3352 Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3353 << Scope->getSourceRange();
3354 }
3355 SubExprs.push_back(Scope);
3356 }
3357
Fariborz Jahanian615de762013-05-28 17:37:39 +00003358 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3359 SubExprs, ResultType, Op,
3360 TheCall->getRParenLoc());
3361
3362 if ((Op == AtomicExpr::AO__c11_atomic_load ||
Yaxun Liu39195062017-08-04 18:16:31 +00003363 Op == AtomicExpr::AO__c11_atomic_store ||
3364 Op == AtomicExpr::AO__opencl_atomic_load ||
3365 Op == AtomicExpr::AO__opencl_atomic_store ) &&
Fariborz Jahanian615de762013-05-28 17:37:39 +00003366 Context.AtomicUsesUnsupportedLibcall(AE))
Yaxun Liu39195062017-08-04 18:16:31 +00003367 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3368 << ((Op == AtomicExpr::AO__c11_atomic_load ||
3369 Op == AtomicExpr::AO__opencl_atomic_load)
3370 ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00003371
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003372 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003373}
3374
John McCall29ad95b2011-08-27 01:09:30 +00003375/// checkBuiltinArgument - Given a call to a builtin function, perform
3376/// normal type-checking on the given argument, updating the call in
3377/// place. This is useful when a builtin function requires custom
3378/// type-checking for some of its arguments but not necessarily all of
3379/// them.
3380///
3381/// Returns true on error.
3382static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3383 FunctionDecl *Fn = E->getDirectCallee();
3384 assert(Fn && "builtin call without direct callee!");
3385
3386 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3387 InitializedEntity Entity =
3388 InitializedEntity::InitializeParameter(S.Context, Param);
3389
3390 ExprResult Arg = E->getArg(0);
3391 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3392 if (Arg.isInvalid())
3393 return true;
3394
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003395 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00003396 return false;
3397}
3398
Chris Lattnerdc046542009-05-08 06:58:22 +00003399/// SemaBuiltinAtomicOverloaded - We have a call to a function like
3400/// __sync_fetch_and_add, which is an overloaded function based on the pointer
3401/// type of its first argument. The main ActOnCallExpr routines have already
3402/// promoted the types of arguments because all of these calls are prototyped as
3403/// void(...).
3404///
3405/// This function goes through and does final semantic checking for these
3406/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00003407ExprResult
3408Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003409 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00003410 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3411 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3412
3413 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003414 if (TheCall->getNumArgs() < 1) {
3415 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3416 << 0 << 1 << TheCall->getNumArgs()
3417 << TheCall->getCallee()->getSourceRange();
3418 return ExprError();
3419 }
Mike Stump11289f42009-09-09 15:08:12 +00003420
Chris Lattnerdc046542009-05-08 06:58:22 +00003421 // Inspect the first argument of the atomic builtin. This should always be
3422 // a pointer type, whose element is an integral scalar or pointer type.
3423 // Because it is a pointer type, we don't have to worry about any implicit
3424 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003425 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00003426 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00003427 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3428 if (FirstArgResult.isInvalid())
3429 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003430 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00003431 TheCall->setArg(0, FirstArg);
3432
John McCall31168b02011-06-15 23:02:42 +00003433 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3434 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003435 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3436 << FirstArg->getType() << FirstArg->getSourceRange();
3437 return ExprError();
3438 }
Mike Stump11289f42009-09-09 15:08:12 +00003439
John McCall31168b02011-06-15 23:02:42 +00003440 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00003441 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003442 !ValType->isBlockPointerType()) {
3443 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3444 << FirstArg->getType() << FirstArg->getSourceRange();
3445 return ExprError();
3446 }
Chris Lattnerdc046542009-05-08 06:58:22 +00003447
John McCall31168b02011-06-15 23:02:42 +00003448 switch (ValType.getObjCLifetime()) {
3449 case Qualifiers::OCL_None:
3450 case Qualifiers::OCL_ExplicitNone:
3451 // okay
3452 break;
3453
3454 case Qualifiers::OCL_Weak:
3455 case Qualifiers::OCL_Strong:
3456 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00003457 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00003458 << ValType << FirstArg->getSourceRange();
3459 return ExprError();
3460 }
3461
John McCallb50451a2011-10-05 07:41:44 +00003462 // Strip any qualifiers off ValType.
3463 ValType = ValType.getUnqualifiedType();
3464
Chandler Carruth3973af72010-07-18 20:54:12 +00003465 // The majority of builtins return a value, but a few have special return
3466 // types, so allow them to override appropriately below.
3467 QualType ResultType = ValType;
3468
Chris Lattnerdc046542009-05-08 06:58:22 +00003469 // We need to figure out which concrete builtin this maps onto. For example,
3470 // __sync_fetch_and_add with a 2 byte object turns into
3471 // __sync_fetch_and_add_2.
3472#define BUILTIN_ROW(x) \
3473 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3474 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00003475
Chris Lattnerdc046542009-05-08 06:58:22 +00003476 static const unsigned BuiltinIndices[][5] = {
3477 BUILTIN_ROW(__sync_fetch_and_add),
3478 BUILTIN_ROW(__sync_fetch_and_sub),
3479 BUILTIN_ROW(__sync_fetch_and_or),
3480 BUILTIN_ROW(__sync_fetch_and_and),
3481 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00003482 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00003483
Chris Lattnerdc046542009-05-08 06:58:22 +00003484 BUILTIN_ROW(__sync_add_and_fetch),
3485 BUILTIN_ROW(__sync_sub_and_fetch),
3486 BUILTIN_ROW(__sync_and_and_fetch),
3487 BUILTIN_ROW(__sync_or_and_fetch),
3488 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00003489 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00003490
Chris Lattnerdc046542009-05-08 06:58:22 +00003491 BUILTIN_ROW(__sync_val_compare_and_swap),
3492 BUILTIN_ROW(__sync_bool_compare_and_swap),
3493 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00003494 BUILTIN_ROW(__sync_lock_release),
3495 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00003496 };
Mike Stump11289f42009-09-09 15:08:12 +00003497#undef BUILTIN_ROW
3498
Chris Lattnerdc046542009-05-08 06:58:22 +00003499 // Determine the index of the size.
3500 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00003501 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00003502 case 1: SizeIndex = 0; break;
3503 case 2: SizeIndex = 1; break;
3504 case 4: SizeIndex = 2; break;
3505 case 8: SizeIndex = 3; break;
3506 case 16: SizeIndex = 4; break;
3507 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003508 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3509 << FirstArg->getType() << FirstArg->getSourceRange();
3510 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00003511 }
Mike Stump11289f42009-09-09 15:08:12 +00003512
Chris Lattnerdc046542009-05-08 06:58:22 +00003513 // Each of these builtins has one pointer argument, followed by some number of
3514 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3515 // that we ignore. Find out which row of BuiltinIndices to read from as well
3516 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00003517 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00003518 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00003519 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00003520 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00003521 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00003522 case Builtin::BI__sync_fetch_and_add:
3523 case Builtin::BI__sync_fetch_and_add_1:
3524 case Builtin::BI__sync_fetch_and_add_2:
3525 case Builtin::BI__sync_fetch_and_add_4:
3526 case Builtin::BI__sync_fetch_and_add_8:
3527 case Builtin::BI__sync_fetch_and_add_16:
3528 BuiltinIndex = 0;
3529 break;
3530
3531 case Builtin::BI__sync_fetch_and_sub:
3532 case Builtin::BI__sync_fetch_and_sub_1:
3533 case Builtin::BI__sync_fetch_and_sub_2:
3534 case Builtin::BI__sync_fetch_and_sub_4:
3535 case Builtin::BI__sync_fetch_and_sub_8:
3536 case Builtin::BI__sync_fetch_and_sub_16:
3537 BuiltinIndex = 1;
3538 break;
3539
3540 case Builtin::BI__sync_fetch_and_or:
3541 case Builtin::BI__sync_fetch_and_or_1:
3542 case Builtin::BI__sync_fetch_and_or_2:
3543 case Builtin::BI__sync_fetch_and_or_4:
3544 case Builtin::BI__sync_fetch_and_or_8:
3545 case Builtin::BI__sync_fetch_and_or_16:
3546 BuiltinIndex = 2;
3547 break;
3548
3549 case Builtin::BI__sync_fetch_and_and:
3550 case Builtin::BI__sync_fetch_and_and_1:
3551 case Builtin::BI__sync_fetch_and_and_2:
3552 case Builtin::BI__sync_fetch_and_and_4:
3553 case Builtin::BI__sync_fetch_and_and_8:
3554 case Builtin::BI__sync_fetch_and_and_16:
3555 BuiltinIndex = 3;
3556 break;
Mike Stump11289f42009-09-09 15:08:12 +00003557
Douglas Gregor73722482011-11-28 16:30:08 +00003558 case Builtin::BI__sync_fetch_and_xor:
3559 case Builtin::BI__sync_fetch_and_xor_1:
3560 case Builtin::BI__sync_fetch_and_xor_2:
3561 case Builtin::BI__sync_fetch_and_xor_4:
3562 case Builtin::BI__sync_fetch_and_xor_8:
3563 case Builtin::BI__sync_fetch_and_xor_16:
3564 BuiltinIndex = 4;
3565 break;
3566
Hal Finkeld2208b52014-10-02 20:53:50 +00003567 case Builtin::BI__sync_fetch_and_nand:
3568 case Builtin::BI__sync_fetch_and_nand_1:
3569 case Builtin::BI__sync_fetch_and_nand_2:
3570 case Builtin::BI__sync_fetch_and_nand_4:
3571 case Builtin::BI__sync_fetch_and_nand_8:
3572 case Builtin::BI__sync_fetch_and_nand_16:
3573 BuiltinIndex = 5;
3574 WarnAboutSemanticsChange = true;
3575 break;
3576
Douglas Gregor73722482011-11-28 16:30:08 +00003577 case Builtin::BI__sync_add_and_fetch:
3578 case Builtin::BI__sync_add_and_fetch_1:
3579 case Builtin::BI__sync_add_and_fetch_2:
3580 case Builtin::BI__sync_add_and_fetch_4:
3581 case Builtin::BI__sync_add_and_fetch_8:
3582 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003583 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00003584 break;
3585
3586 case Builtin::BI__sync_sub_and_fetch:
3587 case Builtin::BI__sync_sub_and_fetch_1:
3588 case Builtin::BI__sync_sub_and_fetch_2:
3589 case Builtin::BI__sync_sub_and_fetch_4:
3590 case Builtin::BI__sync_sub_and_fetch_8:
3591 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003592 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00003593 break;
3594
3595 case Builtin::BI__sync_and_and_fetch:
3596 case Builtin::BI__sync_and_and_fetch_1:
3597 case Builtin::BI__sync_and_and_fetch_2:
3598 case Builtin::BI__sync_and_and_fetch_4:
3599 case Builtin::BI__sync_and_and_fetch_8:
3600 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003601 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00003602 break;
3603
3604 case Builtin::BI__sync_or_and_fetch:
3605 case Builtin::BI__sync_or_and_fetch_1:
3606 case Builtin::BI__sync_or_and_fetch_2:
3607 case Builtin::BI__sync_or_and_fetch_4:
3608 case Builtin::BI__sync_or_and_fetch_8:
3609 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003610 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00003611 break;
3612
3613 case Builtin::BI__sync_xor_and_fetch:
3614 case Builtin::BI__sync_xor_and_fetch_1:
3615 case Builtin::BI__sync_xor_and_fetch_2:
3616 case Builtin::BI__sync_xor_and_fetch_4:
3617 case Builtin::BI__sync_xor_and_fetch_8:
3618 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003619 BuiltinIndex = 10;
3620 break;
3621
3622 case Builtin::BI__sync_nand_and_fetch:
3623 case Builtin::BI__sync_nand_and_fetch_1:
3624 case Builtin::BI__sync_nand_and_fetch_2:
3625 case Builtin::BI__sync_nand_and_fetch_4:
3626 case Builtin::BI__sync_nand_and_fetch_8:
3627 case Builtin::BI__sync_nand_and_fetch_16:
3628 BuiltinIndex = 11;
3629 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00003630 break;
Mike Stump11289f42009-09-09 15:08:12 +00003631
Chris Lattnerdc046542009-05-08 06:58:22 +00003632 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003633 case Builtin::BI__sync_val_compare_and_swap_1:
3634 case Builtin::BI__sync_val_compare_and_swap_2:
3635 case Builtin::BI__sync_val_compare_and_swap_4:
3636 case Builtin::BI__sync_val_compare_and_swap_8:
3637 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003638 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00003639 NumFixed = 2;
3640 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003641
Chris Lattnerdc046542009-05-08 06:58:22 +00003642 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00003643 case Builtin::BI__sync_bool_compare_and_swap_1:
3644 case Builtin::BI__sync_bool_compare_and_swap_2:
3645 case Builtin::BI__sync_bool_compare_and_swap_4:
3646 case Builtin::BI__sync_bool_compare_and_swap_8:
3647 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003648 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00003649 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00003650 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003651 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003652
3653 case Builtin::BI__sync_lock_test_and_set:
3654 case Builtin::BI__sync_lock_test_and_set_1:
3655 case Builtin::BI__sync_lock_test_and_set_2:
3656 case Builtin::BI__sync_lock_test_and_set_4:
3657 case Builtin::BI__sync_lock_test_and_set_8:
3658 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003659 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00003660 break;
3661
Chris Lattnerdc046542009-05-08 06:58:22 +00003662 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00003663 case Builtin::BI__sync_lock_release_1:
3664 case Builtin::BI__sync_lock_release_2:
3665 case Builtin::BI__sync_lock_release_4:
3666 case Builtin::BI__sync_lock_release_8:
3667 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003668 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00003669 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00003670 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00003671 break;
Douglas Gregor73722482011-11-28 16:30:08 +00003672
3673 case Builtin::BI__sync_swap:
3674 case Builtin::BI__sync_swap_1:
3675 case Builtin::BI__sync_swap_2:
3676 case Builtin::BI__sync_swap_4:
3677 case Builtin::BI__sync_swap_8:
3678 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00003679 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00003680 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00003681 }
Mike Stump11289f42009-09-09 15:08:12 +00003682
Chris Lattnerdc046542009-05-08 06:58:22 +00003683 // Now that we know how many fixed arguments we expect, first check that we
3684 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003685 if (TheCall->getNumArgs() < 1+NumFixed) {
3686 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3687 << 0 << 1+NumFixed << TheCall->getNumArgs()
3688 << TheCall->getCallee()->getSourceRange();
3689 return ExprError();
3690 }
Mike Stump11289f42009-09-09 15:08:12 +00003691
Hal Finkeld2208b52014-10-02 20:53:50 +00003692 if (WarnAboutSemanticsChange) {
3693 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3694 << TheCall->getCallee()->getSourceRange();
3695 }
3696
Chris Lattner5b9241b2009-05-08 15:36:58 +00003697 // Get the decl for the concrete builtin from this, we can tell what the
3698 // concrete integer type we should convert to is.
3699 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Mehdi Amini7186a432016-10-11 19:04:24 +00003700 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003701 FunctionDecl *NewBuiltinDecl;
3702 if (NewBuiltinID == BuiltinID)
3703 NewBuiltinDecl = FDecl;
3704 else {
3705 // Perform builtin lookup to avoid redeclaring it.
3706 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3707 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3708 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3709 assert(Res.getFoundDecl());
3710 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00003711 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00003712 return ExprError();
3713 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003714
John McCallcf142162010-08-07 06:22:56 +00003715 // The first argument --- the pointer --- has a fixed type; we
3716 // deduce the types of the rest of the arguments accordingly. Walk
3717 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00003718 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00003719 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00003720
Chris Lattnerdc046542009-05-08 06:58:22 +00003721 // GCC does an implicit conversion to the pointer or integer ValType. This
3722 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00003723 // Initialize the argument.
3724 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3725 ValType, /*consume*/ false);
3726 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00003727 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003728 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003729
Chris Lattnerdc046542009-05-08 06:58:22 +00003730 // Okay, we have something that *can* be converted to the right type. Check
3731 // to see if there is a potentially weird extension going on here. This can
3732 // happen when you do an atomic operation on something like an char* and
3733 // pass in 42. The 42 gets converted to char. This is even more strange
3734 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00003735 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003736 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00003737 }
Mike Stump11289f42009-09-09 15:08:12 +00003738
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003739 ASTContext& Context = this->getASTContext();
3740
3741 // Create a new DeclRefExpr to refer to the new decl.
3742 DeclRefExpr* NewDRE = DeclRefExpr::Create(
3743 Context,
3744 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00003745 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003746 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00003747 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003748 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00003749 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00003750 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00003751
Chris Lattnerdc046542009-05-08 06:58:22 +00003752 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00003753 // FIXME: This loses syntactic information.
3754 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3755 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3756 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003757 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00003758
Chandler Carruthbc8cab12010-07-18 07:23:17 +00003759 // Change the result type of the call to match the original value type. This
3760 // is arbitrary, but the codegen for these builtins ins design to handle it
3761 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00003762 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00003763
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003764 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00003765}
3766
Michael Zolotukhin84df1232015-09-08 23:52:33 +00003767/// SemaBuiltinNontemporalOverloaded - We have a call to
3768/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3769/// overloaded function based on the pointer type of its last argument.
3770///
3771/// This function goes through and does final semantic checking for these
3772/// builtins.
3773ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3774 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3775 DeclRefExpr *DRE =
3776 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3777 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3778 unsigned BuiltinID = FDecl->getBuiltinID();
3779 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3780 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3781 "Unexpected nontemporal load/store builtin!");
3782 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3783 unsigned numArgs = isStore ? 2 : 1;
3784
3785 // Ensure that we have the proper number of arguments.
3786 if (checkArgCount(*this, TheCall, numArgs))
3787 return ExprError();
3788
3789 // Inspect the last argument of the nontemporal builtin. This should always
3790 // be a pointer type, from which we imply the type of the memory access.
3791 // Because it is a pointer type, we don't have to worry about any implicit
3792 // casts here.
3793 Expr *PointerArg = TheCall->getArg(numArgs - 1);
3794 ExprResult PointerArgResult =
3795 DefaultFunctionArrayLvalueConversion(PointerArg);
3796
3797 if (PointerArgResult.isInvalid())
3798 return ExprError();
3799 PointerArg = PointerArgResult.get();
3800 TheCall->setArg(numArgs - 1, PointerArg);
3801
3802 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3803 if (!pointerType) {
3804 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3805 << PointerArg->getType() << PointerArg->getSourceRange();
3806 return ExprError();
3807 }
3808
3809 QualType ValType = pointerType->getPointeeType();
3810
3811 // Strip any qualifiers off ValType.
3812 ValType = ValType.getUnqualifiedType();
3813 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3814 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3815 !ValType->isVectorType()) {
3816 Diag(DRE->getLocStart(),
3817 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3818 << PointerArg->getType() << PointerArg->getSourceRange();
3819 return ExprError();
3820 }
3821
3822 if (!isStore) {
3823 TheCall->setType(ValType);
3824 return TheCallResult;
3825 }
3826
3827 ExprResult ValArg = TheCall->getArg(0);
3828 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3829 Context, ValType, /*consume*/ false);
3830 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3831 if (ValArg.isInvalid())
3832 return ExprError();
3833
3834 TheCall->setArg(0, ValArg.get());
3835 TheCall->setType(Context.VoidTy);
3836 return TheCallResult;
3837}
3838
Chris Lattner6436fb62009-02-18 06:01:06 +00003839/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00003840/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00003841/// Note: It might also make sense to do the UTF-16 conversion here (would
3842/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00003843bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00003844 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00003845 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3846
Douglas Gregorfb65e592011-07-27 05:40:30 +00003847 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003848 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3849 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00003850 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00003851 }
Mike Stump11289f42009-09-09 15:08:12 +00003852
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003853 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003854 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003855 unsigned NumBytes = String.size();
Justin Lebar90910552016-09-30 00:38:45 +00003856 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3857 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3858 llvm::UTF16 *ToPtr = &ToBuf[0];
3859
3860 llvm::ConversionResult Result =
3861 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3862 ToPtr + NumBytes, llvm::strictConversion);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003863 // Check for conversion failure.
Justin Lebar90910552016-09-30 00:38:45 +00003864 if (Result != llvm::conversionOK)
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00003865 Diag(Arg->getLocStart(),
3866 diag::warn_cfstring_truncated) << Arg->getSourceRange();
3867 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00003868 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003869}
3870
Mehdi Amini06d367c2016-10-24 20:39:34 +00003871/// CheckObjCString - Checks that the format string argument to the os_log()
3872/// and os_trace() functions is correct, and converts it to const char *.
3873ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3874 Arg = Arg->IgnoreParenCasts();
3875 auto *Literal = dyn_cast<StringLiteral>(Arg);
3876 if (!Literal) {
3877 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3878 Literal = ObjcLiteral->getString();
3879 }
3880 }
3881
3882 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3883 return ExprError(
3884 Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3885 << Arg->getSourceRange());
3886 }
3887
3888 ExprResult Result(Literal);
3889 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3890 InitializedEntity Entity =
3891 InitializedEntity::InitializeParameter(Context, ResultTy, false);
3892 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3893 return Result;
3894}
3895
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003896/// Check that the user is calling the appropriate va_start builtin for the
3897/// target and calling convention.
3898static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3899 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3900 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
Martin Storsjo022e7822017-07-17 20:49:45 +00003901 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003902 bool IsWindows = TT.isOSWindows();
Martin Storsjo022e7822017-07-17 20:49:45 +00003903 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3904 if (IsX64 || IsAArch64) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00003905 CallingConv CC = CC_C;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003906 if (const FunctionDecl *FD = S.getCurFunctionDecl())
3907 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3908 if (IsMSVAStart) {
3909 // Don't allow this in System V ABI functions.
Martin Storsjo022e7822017-07-17 20:49:45 +00003910 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003911 return S.Diag(Fn->getLocStart(),
3912 diag::err_ms_va_start_used_in_sysv_function);
3913 } else {
Martin Storsjo022e7822017-07-17 20:49:45 +00003914 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003915 // On x64 Windows, don't allow this in System V ABI functions.
3916 // (Yes, that means there's no corresponding way to support variadic
3917 // System V ABI functions on Windows.)
3918 if ((IsWindows && CC == CC_X86_64SysV) ||
Martin Storsjo022e7822017-07-17 20:49:45 +00003919 (!IsWindows && CC == CC_Win64))
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003920 return S.Diag(Fn->getLocStart(),
3921 diag::err_va_start_used_in_wrong_abi_function)
3922 << !IsWindows;
3923 }
3924 return false;
3925 }
3926
3927 if (IsMSVAStart)
Martin Storsjo022e7822017-07-17 20:49:45 +00003928 return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003929 return false;
3930}
3931
3932static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3933 ParmVarDecl **LastParam = nullptr) {
3934 // Determine whether the current function, block, or obj-c method is variadic
3935 // and get its parameter list.
3936 bool IsVariadic = false;
3937 ArrayRef<ParmVarDecl *> Params;
Reid Klecknerf1deb832017-05-04 19:51:05 +00003938 DeclContext *Caller = S.CurContext;
3939 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3940 IsVariadic = Block->isVariadic();
3941 Params = Block->parameters();
3942 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003943 IsVariadic = FD->isVariadic();
3944 Params = FD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003945 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003946 IsVariadic = MD->isVariadic();
3947 // FIXME: This isn't correct for methods (results in bogus warning).
3948 Params = MD->parameters();
Reid Klecknerf1deb832017-05-04 19:51:05 +00003949 } else if (isa<CapturedDecl>(Caller)) {
3950 // We don't support va_start in a CapturedDecl.
3951 S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3952 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003953 } else {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003954 // This must be some other declcontext that parses exprs.
3955 S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3956 return true;
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003957 }
3958
3959 if (!IsVariadic) {
Reid Klecknerf1deb832017-05-04 19:51:05 +00003960 S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003961 return true;
3962 }
3963
3964 if (LastParam)
3965 *LastParam = Params.empty() ? nullptr : Params.back();
3966
3967 return false;
3968}
3969
Charles Davisc7d5c942015-09-17 20:55:33 +00003970/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3971/// for validity. Emit an error and return true on failure; return false
3972/// on success.
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003973bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00003974 Expr *Fn = TheCall->getCallee();
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003975
3976 if (checkVAStartABI(*this, BuiltinID, Fn))
3977 return true;
3978
Chris Lattner08464942007-12-28 05:29:59 +00003979 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00003980 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003981 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003982 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3983 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00003984 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00003985 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00003986 return true;
3987 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003988
3989 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00003990 return Diag(TheCall->getLocEnd(),
3991 diag::err_typecheck_call_too_few_args_at_least)
3992 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00003993 }
3994
John McCall29ad95b2011-08-27 01:09:30 +00003995 // Type-check the first argument normally.
3996 if (checkBuiltinArgument(*this, TheCall, 0))
3997 return true;
3998
Reid Kleckner2b0fa122017-05-02 20:10:03 +00003999 // Check that the current function is variadic, and get its last parameter.
4000 ParmVarDecl *LastParam;
4001 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
Chris Lattner43be2e62007-12-19 23:59:04 +00004002 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004003
Chris Lattner43be2e62007-12-19 23:59:04 +00004004 // Verify that the second argument to the builtin is the last argument of the
4005 // current function or method.
4006 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00004007 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004008
Nico Weber9eea7642013-05-24 23:31:57 +00004009 // These are valid if SecondArgIsLastNamedArgument is false after the next
4010 // block.
4011 QualType Type;
4012 SourceLocation ParamLoc;
Aaron Ballman1de59c52016-04-24 13:30:21 +00004013 bool IsCRegister = false;
Nico Weber9eea7642013-05-24 23:31:57 +00004014
Anders Carlsson6a8350b2008-02-11 04:20:54 +00004015 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
4016 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004017 SecondArgIsLastNamedArgument = PV == LastParam;
Nico Weber9eea7642013-05-24 23:31:57 +00004018
4019 Type = PV->getType();
4020 ParamLoc = PV->getLocation();
Aaron Ballman1de59c52016-04-24 13:30:21 +00004021 IsCRegister =
4022 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
Chris Lattner43be2e62007-12-19 23:59:04 +00004023 }
4024 }
Mike Stump11289f42009-09-09 15:08:12 +00004025
Chris Lattner43be2e62007-12-19 23:59:04 +00004026 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00004027 Diag(TheCall->getArg(1)->getLocStart(),
Aaron Ballman05164812016-04-18 18:10:53 +00004028 diag::warn_second_arg_of_va_start_not_last_named_param);
Aaron Ballman1de59c52016-04-24 13:30:21 +00004029 else if (IsCRegister || Type->isReferenceType() ||
Aaron Ballmana4f597f2016-09-15 18:07:51 +00004030 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
4031 // Promotable integers are UB, but enumerations need a bit of
4032 // extra checking to see what their promotable type actually is.
4033 if (!Type->isPromotableIntegerType())
4034 return false;
4035 if (!Type->isEnumeralType())
4036 return true;
4037 const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
4038 return !(ED &&
4039 Context.typesAreCompatible(ED->getPromotionType(), Type));
4040 }()) {
Aaron Ballman1de59c52016-04-24 13:30:21 +00004041 unsigned Reason = 0;
4042 if (Type->isReferenceType()) Reason = 1;
4043 else if (IsCRegister) Reason = 2;
4044 Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
Nico Weber9eea7642013-05-24 23:31:57 +00004045 Diag(ParamLoc, diag::note_parameter_type) << Type;
4046 }
4047
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00004048 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00004049 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00004050}
Chris Lattner43be2e62007-12-19 23:59:04 +00004051
Saleem Abdulrasool3450aa72017-09-26 20:12:04 +00004052bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004053 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
4054 // const char *named_addr);
4055
4056 Expr *Func = Call->getCallee();
4057
4058 if (Call->getNumArgs() < 3)
4059 return Diag(Call->getLocEnd(),
4060 diag::err_typecheck_call_too_few_args_at_least)
4061 << 0 /*function call*/ << 3 << Call->getNumArgs();
4062
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004063 // Type-check the first argument normally.
4064 if (checkBuiltinArgument(*this, Call, 0))
4065 return true;
4066
Reid Kleckner2b0fa122017-05-02 20:10:03 +00004067 // Check that the current function is variadic.
4068 if (checkVAStartIsInVariadicFunction(*this, Func))
4069 return true;
4070
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004071 // __va_start on Windows does not validate the parameter qualifiers
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004072
Saleem Abdulrasool448e8ad2017-09-26 17:44:10 +00004073 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4074 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4075
4076 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4077 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4078
4079 const QualType &ConstCharPtrTy =
4080 Context.getPointerType(Context.CharTy.withConst());
4081 if (!Arg1Ty->isPointerType() ||
4082 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4083 Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4084 << Arg1->getType() << ConstCharPtrTy
4085 << 1 /* different class */
4086 << 0 /* qualifier difference */
4087 << 3 /* parameter mismatch */
4088 << 2 << Arg1->getType() << ConstCharPtrTy;
4089
4090 const QualType SizeTy = Context.getSizeType();
4091 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4092 Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4093 << Arg2->getType() << SizeTy
4094 << 1 /* different class */
4095 << 0 /* qualifier difference */
4096 << 3 /* parameter mismatch */
4097 << 3 << Arg2->getType() << SizeTy;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00004098
4099 return false;
4100}
4101
Chris Lattner2da14fb2007-12-20 00:26:33 +00004102/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4103/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00004104bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4105 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00004106 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004107 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00004108 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00004109 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004110 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004111 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00004112 << SourceRange(TheCall->getArg(2)->getLocStart(),
4113 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004114
John Wiegley01296292011-04-08 18:41:53 +00004115 ExprResult OrigArg0 = TheCall->getArg(0);
4116 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004117
Chris Lattner2da14fb2007-12-20 00:26:33 +00004118 // Do standard promotions between the two arguments, returning their common
4119 // type.
Chris Lattner08464942007-12-28 05:29:59 +00004120 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00004121 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4122 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00004123
4124 // Make sure any conversions are pushed back into the call; this is
4125 // type safe since unordered compare builtins are declared as "_Bool
4126 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00004127 TheCall->setArg(0, OrigArg0.get());
4128 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00004129
John Wiegley01296292011-04-08 18:41:53 +00004130 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00004131 return false;
4132
Chris Lattner2da14fb2007-12-20 00:26:33 +00004133 // If the common type isn't a real floating type, then the arguments were
4134 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00004135 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00004136 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004137 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00004138 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4139 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00004140
Chris Lattner2da14fb2007-12-20 00:26:33 +00004141 return false;
4142}
4143
Benjamin Kramer634fc102010-02-15 22:42:31 +00004144/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4145/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00004146/// to check everything. We expect the last argument to be a floating point
4147/// value.
4148bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4149 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00004150 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00004151 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00004152 if (TheCall->getNumArgs() > NumArgs)
4153 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004154 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004155 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00004156 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004157 (*(TheCall->arg_end()-1))->getLocEnd());
4158
Benjamin Kramer64aae502010-02-16 10:07:31 +00004159 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00004160
Eli Friedman7e4faac2009-08-31 20:06:00 +00004161 if (OrigArg->isTypeDependent())
4162 return false;
4163
Chris Lattner68784ef2010-05-06 05:50:07 +00004164 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00004165 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00004166 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00004167 diag::err_typecheck_call_invalid_unary_fp)
4168 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004169
Neil Hickey88c0fac2016-12-13 16:22:50 +00004170 // If this is an implicit conversion from float -> float or double, remove it.
Chris Lattner68784ef2010-05-06 05:50:07 +00004171 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
Neil Hickey7b5ddab2016-12-14 13:18:48 +00004172 // Only remove standard FloatCasts, leaving other casts inplace
4173 if (Cast->getCastKind() == CK_FloatingCast) {
4174 Expr *CastArg = Cast->getSubExpr();
4175 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4176 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4177 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4178 "promotion from float to either float or double is the only expected cast here");
4179 Cast->setSubExpr(nullptr);
4180 TheCall->setArg(NumArgs-1, CastArg);
4181 }
Chris Lattner68784ef2010-05-06 05:50:07 +00004182 }
4183 }
4184
Eli Friedman7e4faac2009-08-31 20:06:00 +00004185 return false;
4186}
4187
Tony Jiangbbc48e92017-05-24 15:13:32 +00004188// Customized Sema Checking for VSX builtins that have the following signature:
4189// vector [...] builtinName(vector [...], vector [...], const int);
4190// Which takes the same type of vectors (any legal vector type) for the first
4191// two arguments and takes compile time constant for the third argument.
4192// Example builtins are :
4193// vector double vec_xxpermdi(vector double, vector double, int);
4194// vector short vec_xxsldwi(vector short, vector short, int);
4195bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4196 unsigned ExpectedNumArgs = 3;
4197 if (TheCall->getNumArgs() < ExpectedNumArgs)
4198 return Diag(TheCall->getLocEnd(),
4199 diag::err_typecheck_call_too_few_args_at_least)
4200 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4201 << TheCall->getSourceRange();
4202
4203 if (TheCall->getNumArgs() > ExpectedNumArgs)
4204 return Diag(TheCall->getLocEnd(),
4205 diag::err_typecheck_call_too_many_args_at_most)
4206 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4207 << TheCall->getSourceRange();
4208
4209 // Check the third argument is a compile time constant
4210 llvm::APSInt Value;
4211 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4212 return Diag(TheCall->getLocStart(),
4213 diag::err_vsx_builtin_nonconstant_argument)
4214 << 3 /* argument index */ << TheCall->getDirectCallee()
4215 << SourceRange(TheCall->getArg(2)->getLocStart(),
4216 TheCall->getArg(2)->getLocEnd());
4217
4218 QualType Arg1Ty = TheCall->getArg(0)->getType();
4219 QualType Arg2Ty = TheCall->getArg(1)->getType();
4220
4221 // Check the type of argument 1 and argument 2 are vectors.
4222 SourceLocation BuiltinLoc = TheCall->getLocStart();
4223 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4224 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4225 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4226 << TheCall->getDirectCallee()
4227 << SourceRange(TheCall->getArg(0)->getLocStart(),
4228 TheCall->getArg(1)->getLocEnd());
4229 }
4230
4231 // Check the first two arguments are the same type.
4232 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4233 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4234 << TheCall->getDirectCallee()
4235 << SourceRange(TheCall->getArg(0)->getLocStart(),
4236 TheCall->getArg(1)->getLocEnd());
4237 }
4238
4239 // When default clang type checking is turned off and the customized type
4240 // checking is used, the returning type of the function must be explicitly
4241 // set. Otherwise it is _Bool by default.
4242 TheCall->setType(Arg1Ty);
4243
4244 return false;
4245}
4246
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004247/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4248// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00004249ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00004250 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004251 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00004252 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00004253 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4254 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004255
Nate Begemana0110022010-06-08 00:16:34 +00004256 // Determine which of the following types of shufflevector we're checking:
4257 // 1) unary, vector mask: (lhs, mask)
Craig Topperb3174a82016-05-18 04:11:25 +00004258 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
Nate Begemana0110022010-06-08 00:16:34 +00004259 QualType resType = TheCall->getArg(0)->getType();
4260 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00004261
Douglas Gregorc25f7662009-05-19 22:10:17 +00004262 if (!TheCall->getArg(0)->isTypeDependent() &&
4263 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00004264 QualType LHSType = TheCall->getArg(0)->getType();
4265 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00004266
Craig Topperbaca3892013-07-29 06:47:04 +00004267 if (!LHSType->isVectorType() || !RHSType->isVectorType())
4268 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004269 diag::err_vec_builtin_non_vector)
4270 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004271 << SourceRange(TheCall->getArg(0)->getLocStart(),
4272 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004273
Nate Begemana0110022010-06-08 00:16:34 +00004274 numElements = LHSType->getAs<VectorType>()->getNumElements();
4275 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00004276
Nate Begemana0110022010-06-08 00:16:34 +00004277 // Check to see if we have a call with 2 vector arguments, the unary shuffle
4278 // with mask. If so, verify that RHS is an integer vector type with the
4279 // same number of elts as lhs.
4280 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00004281 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00004282 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00004283 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004284 diag::err_vec_builtin_incompatible_vector)
4285 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004286 << SourceRange(TheCall->getArg(1)->getLocStart(),
4287 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00004288 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00004289 return ExprError(Diag(TheCall->getLocStart(),
Tony Jiangedc78492017-05-24 14:45:57 +00004290 diag::err_vec_builtin_incompatible_vector)
4291 << TheCall->getDirectCallee()
Craig Topperbaca3892013-07-29 06:47:04 +00004292 << SourceRange(TheCall->getArg(0)->getLocStart(),
4293 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00004294 } else if (numElements != numResElements) {
4295 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00004296 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00004297 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00004298 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004299 }
4300
4301 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00004302 if (TheCall->getArg(i)->isTypeDependent() ||
4303 TheCall->getArg(i)->isValueDependent())
4304 continue;
4305
Nate Begemana0110022010-06-08 00:16:34 +00004306 llvm::APSInt Result(32);
4307 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4308 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004309 diag::err_shufflevector_nonconstant_argument)
4310 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004311
Craig Topper50ad5b72013-08-03 17:40:38 +00004312 // Allow -1 which will be translated to undef in the IR.
4313 if (Result.isSigned() && Result.isAllOnesValue())
4314 continue;
4315
Chris Lattner7ab824e2008-08-10 02:05:13 +00004316 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004317 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00004318 diag::err_shufflevector_argument_too_large)
4319 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004320 }
4321
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004322 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004323
Chris Lattner7ab824e2008-08-10 02:05:13 +00004324 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004325 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00004326 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004327 }
4328
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004329 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4330 TheCall->getCallee()->getLocStart(),
4331 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00004332}
Chris Lattner43be2e62007-12-19 23:59:04 +00004333
Hal Finkelc4d7c822013-09-18 03:29:45 +00004334/// SemaConvertVectorExpr - Handle __builtin_convertvector
4335ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4336 SourceLocation BuiltinLoc,
4337 SourceLocation RParenLoc) {
4338 ExprValueKind VK = VK_RValue;
4339 ExprObjectKind OK = OK_Ordinary;
4340 QualType DstTy = TInfo->getType();
4341 QualType SrcTy = E->getType();
4342
4343 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4344 return ExprError(Diag(BuiltinLoc,
4345 diag::err_convertvector_non_vector)
4346 << E->getSourceRange());
4347 if (!DstTy->isVectorType() && !DstTy->isDependentType())
4348 return ExprError(Diag(BuiltinLoc,
4349 diag::err_convertvector_non_vector_type));
4350
4351 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4352 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4353 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4354 if (SrcElts != DstElts)
4355 return ExprError(Diag(BuiltinLoc,
4356 diag::err_convertvector_incompatible_vector)
4357 << E->getSourceRange());
4358 }
4359
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004360 return new (Context)
4361 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00004362}
4363
Daniel Dunbarb7257262008-07-21 22:59:13 +00004364/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4365// This is declared to take (const void*, ...) and can take two
4366// optional constant int args.
4367bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00004368 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004369
Chris Lattner3b054132008-11-19 05:08:23 +00004370 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00004371 return Diag(TheCall->getLocEnd(),
4372 diag::err_typecheck_call_too_many_args_at_most)
4373 << 0 /*function call*/ << 3 << NumArgs
4374 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00004375
4376 // Argument 0 is checked for us and the remaining arguments must be
4377 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00004378 for (unsigned i = 1; i != NumArgs; ++i)
4379 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004380 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004381
Warren Hunt20e4a5d2014-02-21 23:08:53 +00004382 return false;
4383}
4384
Hal Finkelf0417332014-07-17 14:25:55 +00004385/// SemaBuiltinAssume - Handle __assume (MS Extension).
4386// __assume does not evaluate its arguments, and should warn if its argument
4387// has side effects.
4388bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4389 Expr *Arg = TheCall->getArg(0);
4390 if (Arg->isInstantiationDependent()) return false;
4391
4392 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00004393 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00004394 << Arg->getSourceRange()
4395 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4396
4397 return false;
4398}
4399
David Majnemer86b1bfa2016-10-31 18:07:57 +00004400/// Handle __builtin_alloca_with_align. This is declared
David Majnemer51169932016-10-31 05:37:48 +00004401/// as (size_t, size_t) where the second size_t must be a power of 2 greater
4402/// than 8.
4403bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4404 // The alignment must be a constant integer.
4405 Expr *Arg = TheCall->getArg(1);
4406
4407 // We can't check the value of a dependent argument.
4408 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
David Majnemer86b1bfa2016-10-31 18:07:57 +00004409 if (const auto *UE =
4410 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4411 if (UE->getKind() == UETT_AlignOf)
4412 Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4413 << Arg->getSourceRange();
4414
David Majnemer51169932016-10-31 05:37:48 +00004415 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4416
4417 if (!Result.isPowerOf2())
4418 return Diag(TheCall->getLocStart(),
4419 diag::err_alignment_not_power_of_two)
4420 << Arg->getSourceRange();
4421
4422 if (Result < Context.getCharWidth())
4423 return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4424 << (unsigned)Context.getCharWidth()
4425 << Arg->getSourceRange();
4426
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004427 if (Result > std::numeric_limits<int32_t>::max())
David Majnemer51169932016-10-31 05:37:48 +00004428 return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004429 << std::numeric_limits<int32_t>::max()
David Majnemer51169932016-10-31 05:37:48 +00004430 << Arg->getSourceRange();
4431 }
4432
4433 return false;
4434}
4435
4436/// Handle __builtin_assume_aligned. This is declared
Hal Finkelbcc06082014-09-07 22:58:14 +00004437/// as (const void*, size_t, ...) and can take one optional constant int arg.
4438bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4439 unsigned NumArgs = TheCall->getNumArgs();
4440
4441 if (NumArgs > 3)
4442 return Diag(TheCall->getLocEnd(),
4443 diag::err_typecheck_call_too_many_args_at_most)
4444 << 0 /*function call*/ << 3 << NumArgs
4445 << TheCall->getSourceRange();
4446
4447 // The alignment must be a constant integer.
4448 Expr *Arg = TheCall->getArg(1);
4449
4450 // We can't check the value of a dependent argument.
4451 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4452 llvm::APSInt Result;
4453 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4454 return true;
4455
4456 if (!Result.isPowerOf2())
4457 return Diag(TheCall->getLocStart(),
4458 diag::err_alignment_not_power_of_two)
4459 << Arg->getSourceRange();
4460 }
4461
4462 if (NumArgs > 2) {
4463 ExprResult Arg(TheCall->getArg(2));
4464 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4465 Context.getSizeType(), false);
4466 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4467 if (Arg.isInvalid()) return true;
4468 TheCall->setArg(2, Arg.get());
4469 }
Hal Finkelf0417332014-07-17 14:25:55 +00004470
4471 return false;
4472}
4473
Mehdi Amini06d367c2016-10-24 20:39:34 +00004474bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4475 unsigned BuiltinID =
4476 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4477 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4478
4479 unsigned NumArgs = TheCall->getNumArgs();
4480 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4481 if (NumArgs < NumRequiredArgs) {
4482 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4483 << 0 /* function call */ << NumRequiredArgs << NumArgs
4484 << TheCall->getSourceRange();
4485 }
4486 if (NumArgs >= NumRequiredArgs + 0x100) {
4487 return Diag(TheCall->getLocEnd(),
4488 diag::err_typecheck_call_too_many_args_at_most)
4489 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4490 << TheCall->getSourceRange();
4491 }
4492 unsigned i = 0;
4493
4494 // For formatting call, check buffer arg.
4495 if (!IsSizeCall) {
4496 ExprResult Arg(TheCall->getArg(i));
4497 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4498 Context, Context.VoidPtrTy, false);
4499 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4500 if (Arg.isInvalid())
4501 return true;
4502 TheCall->setArg(i, Arg.get());
4503 i++;
4504 }
4505
4506 // Check string literal arg.
4507 unsigned FormatIdx = i;
4508 {
4509 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4510 if (Arg.isInvalid())
4511 return true;
4512 TheCall->setArg(i, Arg.get());
4513 i++;
4514 }
4515
4516 // Make sure variadic args are scalar.
4517 unsigned FirstDataArg = i;
4518 while (i < NumArgs) {
4519 ExprResult Arg = DefaultVariadicArgumentPromotion(
4520 TheCall->getArg(i), VariadicFunction, nullptr);
4521 if (Arg.isInvalid())
4522 return true;
4523 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4524 if (ArgSize.getQuantity() >= 0x100) {
4525 return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4526 << i << (int)ArgSize.getQuantity() << 0xff
4527 << TheCall->getSourceRange();
4528 }
4529 TheCall->setArg(i, Arg.get());
4530 i++;
4531 }
4532
4533 // Check formatting specifiers. NOTE: We're only doing this for the non-size
4534 // call to avoid duplicate diagnostics.
4535 if (!IsSizeCall) {
4536 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4537 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4538 bool Success = CheckFormatArguments(
4539 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4540 VariadicFunction, TheCall->getLocStart(), SourceRange(),
4541 CheckedVarArgs);
4542 if (!Success)
4543 return true;
4544 }
4545
4546 if (IsSizeCall) {
4547 TheCall->setType(Context.getSizeType());
4548 } else {
4549 TheCall->setType(Context.VoidPtrTy);
4550 }
4551 return false;
4552}
4553
Eric Christopher8d0c6212010-04-17 02:26:23 +00004554/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4555/// TheCall is a constant expression.
4556bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4557 llvm::APSInt &Result) {
4558 Expr *Arg = TheCall->getArg(ArgNum);
4559 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4560 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4561
4562 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4563
4564 if (!Arg->isIntegerConstantExpr(Result, Context))
4565 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00004566 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00004567
Chris Lattnerd545ad12009-09-23 06:06:36 +00004568 return false;
4569}
4570
Richard Sandiford28940af2014-04-16 08:47:51 +00004571/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4572/// TheCall is a constant expression in the range [Low, High].
4573bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4574 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00004575 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004576
4577 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00004578 Expr *Arg = TheCall->getArg(ArgNum);
4579 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00004580 return false;
4581
Eric Christopher8d0c6212010-04-17 02:26:23 +00004582 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00004583 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00004584 return true;
4585
Richard Sandiford28940af2014-04-16 08:47:51 +00004586 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00004587 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00004588 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00004589
4590 return false;
4591}
4592
Simon Dardis1f90f2d2016-10-19 17:50:52 +00004593/// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4594/// TheCall is a constant expression is a multiple of Num..
4595bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4596 unsigned Num) {
4597 llvm::APSInt Result;
4598
4599 // We can't check the value of a dependent argument.
4600 Expr *Arg = TheCall->getArg(ArgNum);
4601 if (Arg->isTypeDependent() || Arg->isValueDependent())
4602 return false;
4603
4604 // Check constant-ness first.
4605 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4606 return true;
4607
4608 if (Result.getSExtValue() % Num != 0)
4609 return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4610 << Num << Arg->getSourceRange();
4611
4612 return false;
4613}
4614
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004615/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4616/// TheCall is an ARM/AArch64 special register string literal.
4617bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4618 int ArgNum, unsigned ExpectedFieldNum,
4619 bool AllowName) {
4620 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4621 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4622 BuiltinID == ARM::BI__builtin_arm_rsr ||
4623 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4624 BuiltinID == ARM::BI__builtin_arm_wsr ||
4625 BuiltinID == ARM::BI__builtin_arm_wsrp;
4626 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4627 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4628 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4629 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4630 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4631 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4632 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4633
4634 // We can't check the value of a dependent argument.
4635 Expr *Arg = TheCall->getArg(ArgNum);
4636 if (Arg->isTypeDependent() || Arg->isValueDependent())
4637 return false;
4638
4639 // Check if the argument is a string literal.
4640 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4641 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4642 << Arg->getSourceRange();
4643
4644 // Check the type of special register given.
4645 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4646 SmallVector<StringRef, 6> Fields;
4647 Reg.split(Fields, ":");
4648
4649 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4650 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4651 << Arg->getSourceRange();
4652
4653 // If the string is the name of a register then we cannot check that it is
4654 // valid here but if the string is of one the forms described in ACLE then we
4655 // can check that the supplied fields are integers and within the valid
4656 // ranges.
4657 if (Fields.size() > 1) {
4658 bool FiveFields = Fields.size() == 5;
4659
4660 bool ValidString = true;
4661 if (IsARMBuiltin) {
4662 ValidString &= Fields[0].startswith_lower("cp") ||
4663 Fields[0].startswith_lower("p");
4664 if (ValidString)
4665 Fields[0] =
4666 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4667
4668 ValidString &= Fields[2].startswith_lower("c");
4669 if (ValidString)
4670 Fields[2] = Fields[2].drop_front(1);
4671
4672 if (FiveFields) {
4673 ValidString &= Fields[3].startswith_lower("c");
4674 if (ValidString)
4675 Fields[3] = Fields[3].drop_front(1);
4676 }
4677 }
4678
4679 SmallVector<int, 5> Ranges;
4680 if (FiveFields)
Oleg Ranevskyy85d93a82016-11-18 21:00:08 +00004681 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004682 else
4683 Ranges.append({15, 7, 15});
4684
4685 for (unsigned i=0; i<Fields.size(); ++i) {
4686 int IntField;
4687 ValidString &= !Fields[i].getAsInteger(10, IntField);
4688 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4689 }
4690
4691 if (!ValidString)
4692 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4693 << Arg->getSourceRange();
Luke Cheeseman59b2d832015-06-15 17:51:01 +00004694 } else if (IsAArch64Builtin && Fields.size() == 1) {
4695 // If the register name is one of those that appear in the condition below
4696 // and the special register builtin being used is one of the write builtins,
4697 // then we require that the argument provided for writing to the register
4698 // is an integer constant expression. This is because it will be lowered to
4699 // an MSR (immediate) instruction, so we need to know the immediate at
4700 // compile time.
4701 if (TheCall->getNumArgs() != 2)
4702 return false;
4703
4704 std::string RegLower = Reg.lower();
4705 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4706 RegLower != "pan" && RegLower != "uao")
4707 return false;
4708
4709 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4710 }
4711
4712 return false;
4713}
4714
Eli Friedmanc97d0142009-05-03 06:04:26 +00004715/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004716/// This checks that the target supports __builtin_longjmp and
4717/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004718bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004719 if (!Context.getTargetInfo().hasSjLjLowering())
4720 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4721 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4722
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004723 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00004724 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00004725
Eric Christopher8d0c6212010-04-17 02:26:23 +00004726 // TODO: This is less than ideal. Overload this to take a value.
4727 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4728 return true;
4729
4730 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00004731 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4732 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4733
4734 return false;
4735}
4736
Joerg Sonnenberger27173282015-03-11 23:46:32 +00004737/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4738/// This checks that the target supports __builtin_setjmp.
4739bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4740 if (!Context.getTargetInfo().hasSjLjLowering())
4741 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4742 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4743 return false;
4744}
4745
Richard Smithd7293d72013-08-05 18:49:43 +00004746namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004747
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004748class UncoveredArgHandler {
4749 enum { Unknown = -1, AllCovered = -2 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004750
4751 signed FirstUncoveredArg = Unknown;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004752 SmallVector<const Expr *, 4> DiagnosticExprs;
4753
4754public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004755 UncoveredArgHandler() = default;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004756
4757 bool hasUncoveredArg() const {
4758 return (FirstUncoveredArg >= 0);
4759 }
4760
4761 unsigned getUncoveredArg() const {
4762 assert(hasUncoveredArg() && "no uncovered argument");
4763 return FirstUncoveredArg;
4764 }
4765
4766 void setAllCovered() {
4767 // A string has been found with all arguments covered, so clear out
4768 // the diagnostics.
4769 DiagnosticExprs.clear();
4770 FirstUncoveredArg = AllCovered;
4771 }
4772
4773 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4774 assert(NewFirstUncoveredArg >= 0 && "Outside range");
4775
4776 // Don't update if a previous string covers all arguments.
4777 if (FirstUncoveredArg == AllCovered)
4778 return;
4779
4780 // UncoveredArgHandler tracks the highest uncovered argument index
4781 // and with it all the strings that match this index.
4782 if (NewFirstUncoveredArg == FirstUncoveredArg)
4783 DiagnosticExprs.push_back(StrExpr);
4784 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4785 DiagnosticExprs.clear();
4786 DiagnosticExprs.push_back(StrExpr);
4787 FirstUncoveredArg = NewFirstUncoveredArg;
4788 }
4789 }
4790
4791 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4792};
4793
Richard Smithd7293d72013-08-05 18:49:43 +00004794enum StringLiteralCheckType {
4795 SLCT_NotALiteral,
4796 SLCT_UncheckedLiteral,
4797 SLCT_CheckedLiteral
4798};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004799
4800} // namespace
Richard Smithd7293d72013-08-05 18:49:43 +00004801
Stephen Hines648c3692016-09-16 01:07:04 +00004802static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4803 BinaryOperatorKind BinOpKind,
4804 bool AddendIsRight) {
4805 unsigned BitWidth = Offset.getBitWidth();
4806 unsigned AddendBitWidth = Addend.getBitWidth();
4807 // There might be negative interim results.
4808 if (Addend.isUnsigned()) {
4809 Addend = Addend.zext(++AddendBitWidth);
4810 Addend.setIsSigned(true);
4811 }
4812 // Adjust the bit width of the APSInts.
4813 if (AddendBitWidth > BitWidth) {
4814 Offset = Offset.sext(AddendBitWidth);
4815 BitWidth = AddendBitWidth;
4816 } else if (BitWidth > AddendBitWidth) {
4817 Addend = Addend.sext(BitWidth);
4818 }
4819
4820 bool Ov = false;
4821 llvm::APSInt ResOffset = Offset;
4822 if (BinOpKind == BO_Add)
4823 ResOffset = Offset.sadd_ov(Addend, Ov);
4824 else {
4825 assert(AddendIsRight && BinOpKind == BO_Sub &&
4826 "operator must be add or sub with addend on the right");
4827 ResOffset = Offset.ssub_ov(Addend, Ov);
4828 }
4829
4830 // We add an offset to a pointer here so we should support an offset as big as
4831 // possible.
4832 if (Ov) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004833 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4834 "index (intermediate) result too big");
Stephen Hinesfec73ad2016-09-16 07:21:24 +00004835 Offset = Offset.sext(2 * BitWidth);
Stephen Hines648c3692016-09-16 01:07:04 +00004836 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4837 return;
4838 }
4839
4840 Offset = ResOffset;
4841}
4842
4843namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004844
Stephen Hines648c3692016-09-16 01:07:04 +00004845// This is a wrapper class around StringLiteral to support offsetted string
4846// literals as format strings. It takes the offset into account when returning
4847// the string and its length or the source locations to display notes correctly.
4848class FormatStringLiteral {
4849 const StringLiteral *FExpr;
4850 int64_t Offset;
4851
4852 public:
4853 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4854 : FExpr(fexpr), Offset(Offset) {}
4855
4856 StringRef getString() const {
4857 return FExpr->getString().drop_front(Offset);
4858 }
4859
4860 unsigned getByteLength() const {
4861 return FExpr->getByteLength() - getCharByteWidth() * Offset;
4862 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004863
Stephen Hines648c3692016-09-16 01:07:04 +00004864 unsigned getLength() const { return FExpr->getLength() - Offset; }
4865 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4866
4867 StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4868
4869 QualType getType() const { return FExpr->getType(); }
4870
4871 bool isAscii() const { return FExpr->isAscii(); }
4872 bool isWide() const { return FExpr->isWide(); }
4873 bool isUTF8() const { return FExpr->isUTF8(); }
4874 bool isUTF16() const { return FExpr->isUTF16(); }
4875 bool isUTF32() const { return FExpr->isUTF32(); }
4876 bool isPascal() const { return FExpr->isPascal(); }
4877
4878 SourceLocation getLocationOfByte(
4879 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4880 const TargetInfo &Target, unsigned *StartToken = nullptr,
4881 unsigned *StartTokenByteOffset = nullptr) const {
4882 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4883 StartToken, StartTokenByteOffset);
4884 }
4885
4886 SourceLocation getLocStart() const LLVM_READONLY {
4887 return FExpr->getLocStart().getLocWithOffset(Offset);
4888 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004889
Stephen Hines648c3692016-09-16 01:07:04 +00004890 SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4891};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004892
4893} // namespace
Stephen Hines648c3692016-09-16 01:07:04 +00004894
4895static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004896 const Expr *OrigFormatExpr,
4897 ArrayRef<const Expr *> Args,
4898 bool HasVAListArg, unsigned format_idx,
4899 unsigned firstDataArg,
4900 Sema::FormatStringType Type,
4901 bool inFunctionCall,
4902 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004903 llvm::SmallBitVector &CheckedVarArgs,
4904 UncoveredArgHandler &UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00004905
Richard Smith55ce3522012-06-25 20:30:08 +00004906// Determine if an expression is a string literal or constant string.
4907// If this function returns false on the arguments to a function expecting a
4908// format string, we will usually need to emit a warning.
4909// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00004910static StringLiteralCheckType
4911checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4912 bool HasVAListArg, unsigned format_idx,
4913 unsigned firstDataArg, Sema::FormatStringType Type,
4914 Sema::VariadicCallType CallType, bool InFunctionCall,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004915 llvm::SmallBitVector &CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004916 UncoveredArgHandler &UncoveredArg,
4917 llvm::APSInt Offset) {
Ted Kremenek808829352010-09-09 03:51:39 +00004918 tryAgain:
Stephen Hines648c3692016-09-16 01:07:04 +00004919 assert(Offset.isSigned() && "invalid offset");
4920
Douglas Gregorc25f7662009-05-19 22:10:17 +00004921 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00004922 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004923
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004924 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00004925
Richard Smithd7293d72013-08-05 18:49:43 +00004926 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00004927 // Technically -Wformat-nonliteral does not warn about this case.
4928 // The behavior of printf and friends in this case is implementation
4929 // dependent. Ideally if the format string cannot be null then
4930 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00004931 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00004932
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004933 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00004934 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004935 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00004936 // The expression is a literal if both sub-expressions were, and it was
4937 // completely checked only if both sub-expressions were checked.
4938 const AbstractConditionalOperator *C =
4939 cast<AbstractConditionalOperator>(E);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004940
4941 // Determine whether it is necessary to check both sub-expressions, for
4942 // example, because the condition expression is a constant that can be
4943 // evaluated at compile time.
4944 bool CheckLeft = true, CheckRight = true;
4945
4946 bool Cond;
4947 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4948 if (Cond)
4949 CheckRight = false;
4950 else
4951 CheckLeft = false;
4952 }
4953
Stephen Hines648c3692016-09-16 01:07:04 +00004954 // We need to maintain the offsets for the right and the left hand side
4955 // separately to check if every possible indexed expression is a valid
4956 // string literal. They might have different offsets for different string
4957 // literals in the end.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004958 StringLiteralCheckType Left;
4959 if (!CheckLeft)
4960 Left = SLCT_UncheckedLiteral;
4961 else {
4962 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4963 HasVAListArg, format_idx, firstDataArg,
4964 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00004965 CheckedVarArgs, UncoveredArg, Offset);
4966 if (Left == SLCT_NotALiteral || !CheckRight) {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004967 return Left;
Stephen Hines648c3692016-09-16 01:07:04 +00004968 }
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004969 }
4970
Richard Smith55ce3522012-06-25 20:30:08 +00004971 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00004972 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00004973 HasVAListArg, format_idx, firstDataArg,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004974 Type, CallType, InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00004975 UncoveredArg, Offset);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00004976
4977 return (CheckLeft && Left < Right) ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004978 }
4979
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00004980 case Stmt::ImplicitCastExprClass:
Ted Kremenek808829352010-09-09 03:51:39 +00004981 E = cast<ImplicitCastExpr>(E)->getSubExpr();
4982 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00004983
John McCallc07a0c72011-02-17 10:25:35 +00004984 case Stmt::OpaqueValueExprClass:
4985 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4986 E = src;
4987 goto tryAgain;
4988 }
Richard Smith55ce3522012-06-25 20:30:08 +00004989 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00004990
Ted Kremeneka8890832011-02-24 23:03:04 +00004991 case Stmt::PredefinedExprClass:
4992 // While __func__, etc., are technically not string literals, they
4993 // cannot contain format specifiers and thus are not a security
4994 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00004995 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00004996
Ted Kremenekdfd72c22009-03-20 21:35:28 +00004997 case Stmt::DeclRefExprClass: {
4998 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004999
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005000 // As an exception, do not flag errors for variables binding to
5001 // const string literals.
5002 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
5003 bool isConstant = false;
5004 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005005
Richard Smithd7293d72013-08-05 18:49:43 +00005006 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
5007 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00005008 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00005009 isConstant = T.isConstant(S.Context) &&
5010 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00005011 } else if (T->isObjCObjectPointerType()) {
5012 // In ObjC, there is usually no "const ObjectPointer" type,
5013 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00005014 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005015 }
Mike Stump11289f42009-09-09 15:08:12 +00005016
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005017 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005018 if (const Expr *Init = VD->getAnyInitializer()) {
5019 // Look through initializers like const char c[] = { "foo" }
5020 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
5021 if (InitList->isStringLiteralInit())
5022 Init = InitList->getInit(0)->IgnoreParenImpCasts();
5023 }
Richard Smithd7293d72013-08-05 18:49:43 +00005024 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005025 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005026 firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005027 /*InFunctionCall*/ false, CheckedVarArgs,
5028 UncoveredArg, Offset);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00005029 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005030 }
Mike Stump11289f42009-09-09 15:08:12 +00005031
Anders Carlssonb012ca92009-06-28 19:55:58 +00005032 // For vprintf* functions (i.e., HasVAListArg==true), we add a
5033 // special check to see if the format string is a function parameter
5034 // of the function calling the printf function. If the function
5035 // has an attribute indicating it is a printf-like function, then we
5036 // should suppress warnings concerning non-literals being used in a call
5037 // to a vprintf function. For example:
5038 //
5039 // void
5040 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
5041 // va_list ap;
5042 // va_start(ap, fmt);
5043 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
5044 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00005045 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005046 if (HasVAListArg) {
5047 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
5048 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
5049 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00005050 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005051 // adjust for implicit parameter
5052 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5053 if (MD->isInstance())
5054 ++PVIndex;
5055 // We also check if the formats are compatible.
5056 // We can't pass a 'scanf' string to a 'printf' function.
5057 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00005058 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00005059 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00005060 }
5061 }
5062 }
5063 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005064 }
Mike Stump11289f42009-09-09 15:08:12 +00005065
Richard Smith55ce3522012-06-25 20:30:08 +00005066 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005067 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005068
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005069 case Stmt::CallExprClass:
5070 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005071 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00005072 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5073 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005074 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
Richard Smithd7293d72013-08-05 18:49:43 +00005075 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005076 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00005077 Type, CallType, InFunctionCall,
Stephen Hines648c3692016-09-16 01:07:04 +00005078 CheckedVarArgs, UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005079 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5080 unsigned BuiltinID = FD->getBuiltinID();
5081 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5082 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5083 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00005084 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00005085 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005086 firstDataArg, Type, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005087 InFunctionCall, CheckedVarArgs,
Stephen Hines648c3692016-09-16 01:07:04 +00005088 UncoveredArg, Offset);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005089 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005090 }
5091 }
Mike Stump11289f42009-09-09 15:08:12 +00005092
Richard Smith55ce3522012-06-25 20:30:08 +00005093 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00005094 }
Alex Lorenzd9007142016-10-24 09:42:34 +00005095 case Stmt::ObjCMessageExprClass: {
5096 const auto *ME = cast<ObjCMessageExpr>(E);
5097 if (const auto *ND = ME->getMethodDecl()) {
5098 if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
Joel E. Denny81508102018-03-13 14:51:22 +00005099 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
Alex Lorenzd9007142016-10-24 09:42:34 +00005100 return checkFormatStringExpr(
5101 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5102 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5103 }
5104 }
5105
5106 return SLCT_NotALiteral;
5107 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005108 case Stmt::ObjCStringLiteralClass:
5109 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00005110 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005111
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005112 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005113 StrE = ObjCFExpr->getString();
5114 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005115 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005116
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005117 if (StrE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005118 if (Offset.isNegative() || Offset > StrE->getLength()) {
5119 // TODO: It would be better to have an explicit warning for out of
5120 // bounds literals.
5121 return SLCT_NotALiteral;
5122 }
5123 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5124 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00005125 firstDataArg, Type, InFunctionCall, CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005126 CheckedVarArgs, UncoveredArg);
Richard Smith55ce3522012-06-25 20:30:08 +00005127 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005128 }
Mike Stump11289f42009-09-09 15:08:12 +00005129
Richard Smith55ce3522012-06-25 20:30:08 +00005130 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005131 }
Stephen Hines648c3692016-09-16 01:07:04 +00005132 case Stmt::BinaryOperatorClass: {
5133 llvm::APSInt LResult;
5134 llvm::APSInt RResult;
5135
5136 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5137
5138 // A string literal + an int offset is still a string literal.
5139 if (BinOp->isAdditiveOp()) {
5140 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5141 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5142
5143 if (LIsInt != RIsInt) {
5144 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5145
5146 if (LIsInt) {
5147 if (BinOpKind == BO_Add) {
5148 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5149 E = BinOp->getRHS();
5150 goto tryAgain;
5151 }
5152 } else {
5153 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5154 E = BinOp->getLHS();
5155 goto tryAgain;
5156 }
5157 }
Stephen Hines648c3692016-09-16 01:07:04 +00005158 }
George Burgess IVd273aab2016-09-22 00:00:26 +00005159
5160 return SLCT_NotALiteral;
Stephen Hines648c3692016-09-16 01:07:04 +00005161 }
5162 case Stmt::UnaryOperatorClass: {
5163 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5164 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005165 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
Stephen Hines648c3692016-09-16 01:07:04 +00005166 llvm::APSInt IndexResult;
5167 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5168 sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5169 E = ASE->getBase();
5170 goto tryAgain;
5171 }
5172 }
5173
5174 return SLCT_NotALiteral;
5175 }
Mike Stump11289f42009-09-09 15:08:12 +00005176
Ted Kremenekdfd72c22009-03-20 21:35:28 +00005177 default:
Richard Smith55ce3522012-06-25 20:30:08 +00005178 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005179 }
5180}
5181
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005182Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00005183 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Mehdi Amini06d367c2016-10-24 20:39:34 +00005184 .Case("scanf", FST_Scanf)
5185 .Cases("printf", "printf0", FST_Printf)
5186 .Cases("NSString", "CFString", FST_NSString)
5187 .Case("strftime", FST_Strftime)
5188 .Case("strfmon", FST_Strfmon)
5189 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5190 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5191 .Case("os_trace", FST_OSLog)
5192 .Case("os_log", FST_OSLog)
5193 .Default(FST_Unknown);
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005194}
5195
Jordan Rose3e0ec582012-07-19 18:10:23 +00005196/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00005197/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00005198/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005199bool Sema::CheckFormatArguments(const FormatAttr *Format,
5200 ArrayRef<const Expr *> Args,
5201 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005202 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005203 SourceLocation Loc, SourceRange Range,
5204 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00005205 FormatStringInfo FSI;
5206 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005207 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00005208 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00005209 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00005210 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005211}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00005212
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005213bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00005214 bool HasVAListArg, unsigned format_idx,
5215 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005216 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00005217 SourceLocation Loc, SourceRange Range,
5218 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00005219 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005220 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005221 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00005222 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005223 }
Mike Stump11289f42009-09-09 15:08:12 +00005224
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005225 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005226
Chris Lattnerb87b1b32007-08-10 20:18:51 +00005227 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00005228 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005229 // Dynamically generated format strings are difficult to
5230 // automatically vet at compile time. Requiring that format strings
5231 // are string literals: (1) permits the checking of format strings by
5232 // the compiler and thereby (2) can practically remove the source of
5233 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00005234
Mike Stump11289f42009-09-09 15:08:12 +00005235 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00005236 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00005237 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00005238 // the same format string checking logic for both ObjC and C strings.
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005239 UncoveredArgHandler UncoveredArg;
Richard Smith55ce3522012-06-25 20:30:08 +00005240 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00005241 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5242 format_idx, firstDataArg, Type, CallType,
Stephen Hines648c3692016-09-16 01:07:04 +00005243 /*IsFunctionCall*/ true, CheckedVarArgs,
5244 UncoveredArg,
5245 /*no string offset*/ llvm::APSInt(64, false) = 0);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005246
5247 // Generate a diagnostic where an uncovered argument is detected.
5248 if (UncoveredArg.hasUncoveredArg()) {
5249 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5250 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5251 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5252 }
5253
Richard Smith55ce3522012-06-25 20:30:08 +00005254 if (CT != SLCT_NotALiteral)
5255 // Literal format string found, check done!
5256 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00005257
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005258 // Strftime is particular as it always uses a single 'time' argument,
5259 // so it is safe to pass a non-literal string.
5260 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00005261 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00005262
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005263 // Do not emit diag when the string param is a macro expansion and the
5264 // format is either NSString or CFString. This is a hack to prevent
5265 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5266 // which are usually used in place of NS and CF string literals.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005267 SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5268 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
Richard Smith55ce3522012-06-25 20:30:08 +00005269 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00005270
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005271 // If there are no arguments specified, warn with -Wformat-security, otherwise
5272 // warn only with -Wformat-nonliteral.
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005273 if (Args.size() == firstDataArg) {
Bob Wilson57819fc2016-03-15 20:56:38 +00005274 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5275 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005276 switch (Type) {
5277 default:
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005278 break;
5279 case FST_Kprintf:
5280 case FST_FreeBSDKPrintf:
5281 case FST_Printf:
Bob Wilson57819fc2016-03-15 20:56:38 +00005282 Diag(FormatLoc, diag::note_format_security_fixit)
5283 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005284 break;
5285 case FST_NSString:
Bob Wilson57819fc2016-03-15 20:56:38 +00005286 Diag(FormatLoc, diag::note_format_security_fixit)
5287 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005288 break;
5289 }
5290 } else {
5291 Diag(FormatLoc, diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00005292 << OrigFormatExpr->getSourceRange();
Bob Wilsoncf2cf0d2016-03-11 21:55:37 +00005293 }
Richard Smith55ce3522012-06-25 20:30:08 +00005294 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00005295}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00005296
Ted Kremenekab278de2010-01-28 23:39:18 +00005297namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005298
Ted Kremenek02087932010-07-16 02:11:22 +00005299class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5300protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00005301 Sema &S;
Stephen Hines648c3692016-09-16 01:07:04 +00005302 const FormatStringLiteral *FExpr;
Ted Kremenekab278de2010-01-28 23:39:18 +00005303 const Expr *OrigFormatExpr;
Mehdi Amini06d367c2016-10-24 20:39:34 +00005304 const Sema::FormatStringType FSType;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00005305 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00005306 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00005307 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00005308 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00005309 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00005310 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00005311 llvm::SmallBitVector CoveredArgs;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005312 bool usesPositionalArgs = false;
5313 bool atFirstArg = true;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005314 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00005315 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00005316 llvm::SmallBitVector &CheckedVarArgs;
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005317 UncoveredArgHandler &UncoveredArg;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00005318
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005319public:
Stephen Hines648c3692016-09-16 01:07:04 +00005320 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005321 const Expr *origFormatExpr,
5322 const Sema::FormatStringType type, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005323 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005324 ArrayRef<const Expr *> Args, unsigned formatIdx,
5325 bool inFunctionCall, Sema::VariadicCallType callType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005326 llvm::SmallBitVector &CheckedVarArgs,
5327 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005328 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5329 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5330 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
Mehdi Amini06d367c2016-10-24 20:39:34 +00005331 inFunctionCall(inFunctionCall), CallType(callType),
5332 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
Richard Smithd7293d72013-08-05 18:49:43 +00005333 CoveredArgs.resize(numDataArgs);
5334 CoveredArgs.reset();
5335 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005336
Ted Kremenek019d2242010-01-29 01:50:07 +00005337 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005338
Ted Kremenek02087932010-07-16 02:11:22 +00005339 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005340 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005341
Jordan Rose92303592012-09-08 04:00:03 +00005342 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005343 const analyze_format_string::FormatSpecifier &FS,
5344 const analyze_format_string::ConversionSpecifier &CS,
5345 const char *startSpecifier, unsigned specifierLen,
5346 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00005347
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005348 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005349 const analyze_format_string::FormatSpecifier &FS,
5350 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005351
5352 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00005353 const analyze_format_string::ConversionSpecifier &CS,
5354 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005355
Craig Toppere14c0f82014-03-12 04:55:44 +00005356 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005357
Craig Toppere14c0f82014-03-12 04:55:44 +00005358 void HandleInvalidPosition(const char *startSpecifier,
5359 unsigned specifierLen,
5360 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005361
Craig Toppere14c0f82014-03-12 04:55:44 +00005362 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00005363
Craig Toppere14c0f82014-03-12 04:55:44 +00005364 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005365
Richard Trieu03cf7b72011-10-28 00:41:25 +00005366 template <typename Range>
Benjamin Kramer7320b992016-06-15 14:20:56 +00005367 static void
5368 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5369 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5370 bool IsStringLocation, Range StringRange,
5371 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005372
Ted Kremenek02087932010-07-16 02:11:22 +00005373protected:
Ted Kremenekce815422010-07-19 21:25:57 +00005374 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5375 const char *startSpec,
5376 unsigned specifierLen,
5377 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005378
5379 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5380 const char *startSpec,
5381 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00005382
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005383 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00005384 CharSourceRange getSpecifierRange(const char *startSpecifier,
5385 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00005386 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005387
Ted Kremenek5739de72010-01-29 01:06:55 +00005388 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005389
5390 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5391 const analyze_format_string::ConversionSpecifier &CS,
5392 const char *startSpecifier, unsigned specifierLen,
5393 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00005394
5395 template <typename Range>
5396 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5397 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00005398 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00005399};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005400
5401} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00005402
Ted Kremenek02087932010-07-16 02:11:22 +00005403SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00005404 return OrigFormatExpr->getSourceRange();
5405}
5406
Ted Kremenek02087932010-07-16 02:11:22 +00005407CharSourceRange CheckFormatHandler::
5408getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00005409 SourceLocation Start = getLocationOfByte(startSpecifier);
5410 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
5411
5412 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00005413 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00005414
5415 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00005416}
5417
Ted Kremenek02087932010-07-16 02:11:22 +00005418SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Stephen Hines648c3692016-09-16 01:07:04 +00005419 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5420 S.getLangOpts(), S.Context.getTargetInfo());
Ted Kremenekab278de2010-01-28 23:39:18 +00005421}
5422
Ted Kremenek02087932010-07-16 02:11:22 +00005423void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5424 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00005425 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5426 getLocationOfByte(startSpecifier),
5427 /*IsStringLocation*/true,
5428 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00005429}
5430
Jordan Rose92303592012-09-08 04:00:03 +00005431void CheckFormatHandler::HandleInvalidLengthModifier(
5432 const analyze_format_string::FormatSpecifier &FS,
5433 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00005434 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00005435 using namespace analyze_format_string;
5436
5437 const LengthModifier &LM = FS.getLengthModifier();
5438 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5439
5440 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005441 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00005442 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005443 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005444 getLocationOfByte(LM.getStart()),
5445 /*IsStringLocation*/true,
5446 getSpecifierRange(startSpecifier, specifierLen));
5447
5448 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5449 << FixedLM->toString()
5450 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5451
5452 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005453 FixItHint Hint;
5454 if (DiagID == diag::warn_format_nonsensical_length)
5455 Hint = FixItHint::CreateRemoval(LMRange);
5456
5457 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00005458 getLocationOfByte(LM.getStart()),
5459 /*IsStringLocation*/true,
5460 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00005461 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00005462 }
5463}
5464
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005465void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00005466 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005467 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00005468 using namespace analyze_format_string;
5469
5470 const LengthModifier &LM = FS.getLengthModifier();
5471 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5472
5473 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00005474 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00005475 if (FixedLM) {
5476 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5477 << LM.toString() << 0,
5478 getLocationOfByte(LM.getStart()),
5479 /*IsStringLocation*/true,
5480 getSpecifierRange(startSpecifier, specifierLen));
5481
5482 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5483 << FixedLM->toString()
5484 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5485
5486 } else {
5487 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5488 << LM.toString() << 0,
5489 getLocationOfByte(LM.getStart()),
5490 /*IsStringLocation*/true,
5491 getSpecifierRange(startSpecifier, specifierLen));
5492 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005493}
5494
5495void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5496 const analyze_format_string::ConversionSpecifier &CS,
5497 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00005498 using namespace analyze_format_string;
5499
5500 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00005501 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00005502 if (FixedCS) {
5503 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5504 << CS.toString() << /*conversion specifier*/1,
5505 getLocationOfByte(CS.getStart()),
5506 /*IsStringLocation*/true,
5507 getSpecifierRange(startSpecifier, specifierLen));
5508
5509 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5510 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5511 << FixedCS->toString()
5512 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5513 } else {
5514 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5515 << CS.toString() << /*conversion specifier*/1,
5516 getLocationOfByte(CS.getStart()),
5517 /*IsStringLocation*/true,
5518 getSpecifierRange(startSpecifier, specifierLen));
5519 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00005520}
5521
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00005522void CheckFormatHandler::HandlePosition(const char *startPos,
5523 unsigned posLen) {
5524 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5525 getLocationOfByte(startPos),
5526 /*IsStringLocation*/true,
5527 getSpecifierRange(startPos, posLen));
5528}
5529
Ted Kremenekd1668192010-02-27 01:41:03 +00005530void
Ted Kremenek02087932010-07-16 02:11:22 +00005531CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5532 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005533 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5534 << (unsigned) p,
5535 getLocationOfByte(startPos), /*IsStringLocation*/true,
5536 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005537}
5538
Ted Kremenek02087932010-07-16 02:11:22 +00005539void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00005540 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005541 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5542 getLocationOfByte(startPos),
5543 /*IsStringLocation*/true,
5544 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00005545}
5546
Ted Kremenek02087932010-07-16 02:11:22 +00005547void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00005548 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005549 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005550 EmitFormatDiagnostic(
5551 S.PDiag(diag::warn_printf_format_string_contains_null_char),
5552 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5553 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00005554 }
Ted Kremenek02087932010-07-16 02:11:22 +00005555}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005556
Jordan Rose58bbe422012-07-19 18:10:08 +00005557// Note that this may return NULL if there was an error parsing or building
5558// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00005559const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005560 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00005561}
5562
5563void CheckFormatHandler::DoneProcessing() {
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005564 // Does the number of data arguments exceed the number of
5565 // format conversions in the format string?
Ted Kremenek02087932010-07-16 02:11:22 +00005566 if (!HasVAListArg) {
5567 // Find any arguments that weren't covered.
5568 CoveredArgs.flip();
5569 signed notCoveredArg = CoveredArgs.find_first();
5570 if (notCoveredArg >= 0) {
5571 assert((unsigned)notCoveredArg < NumDataArgs);
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005572 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5573 } else {
5574 UncoveredArg.setAllCovered();
Ted Kremenek02087932010-07-16 02:11:22 +00005575 }
5576 }
5577}
5578
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005579void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5580 const Expr *ArgExpr) {
5581 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5582 "Invalid state");
5583
5584 if (!ArgExpr)
5585 return;
5586
5587 SourceLocation Loc = ArgExpr->getLocStart();
5588
5589 if (S.getSourceManager().isInSystemMacro(Loc))
5590 return;
5591
5592 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5593 for (auto E : DiagnosticExprs)
5594 PDiag << E->getSourceRange();
5595
5596 CheckFormatHandler::EmitFormatDiagnostic(
5597 S, IsFunctionCall, DiagnosticExprs[0],
5598 PDiag, Loc, /*IsStringLocation*/false,
5599 DiagnosticExprs[0]->getSourceRange());
5600}
5601
Ted Kremenekce815422010-07-19 21:25:57 +00005602bool
5603CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5604 SourceLocation Loc,
5605 const char *startSpec,
5606 unsigned specifierLen,
5607 const char *csStart,
5608 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00005609 bool keepGoing = true;
5610 if (argIndex < NumDataArgs) {
5611 // Consider the argument coverered, even though the specifier doesn't
5612 // make sense.
5613 CoveredArgs.set(argIndex);
5614 }
5615 else {
5616 // If argIndex exceeds the number of data arguments we
5617 // don't issue a warning because that is just a cascade of warnings (and
5618 // they may have intended '%%' anyway). We don't want to continue processing
5619 // the format string after this point, however, as we will like just get
5620 // gibberish when trying to match arguments.
5621 keepGoing = false;
5622 }
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005623
5624 StringRef Specifier(csStart, csLen);
5625
5626 // If the specifier in non-printable, it could be the first byte of a UTF-8
5627 // sequence. In that case, print the UTF-8 code point. If not, print the byte
5628 // hex value.
5629 std::string CodePointStr;
5630 if (!llvm::sys::locale::isPrint(*csStart)) {
Justin Lebar90910552016-09-30 00:38:45 +00005631 llvm::UTF32 CodePoint;
5632 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5633 const llvm::UTF8 *E =
5634 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5635 llvm::ConversionResult Result =
5636 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005637
Justin Lebar90910552016-09-30 00:38:45 +00005638 if (Result != llvm::conversionOK) {
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005639 unsigned char FirstChar = *csStart;
Justin Lebar90910552016-09-30 00:38:45 +00005640 CodePoint = (llvm::UTF32)FirstChar;
Bruno Cardoso Lopes0c18d032016-03-29 17:35:02 +00005641 }
5642
5643 llvm::raw_string_ostream OS(CodePointStr);
5644 if (CodePoint < 256)
5645 OS << "\\x" << llvm::format("%02x", CodePoint);
5646 else if (CodePoint <= 0xFFFF)
5647 OS << "\\u" << llvm::format("%04x", CodePoint);
5648 else
5649 OS << "\\U" << llvm::format("%08x", CodePoint);
5650 OS.flush();
5651 Specifier = CodePointStr;
5652 }
5653
5654 EmitFormatDiagnostic(
5655 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5656 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5657
Ted Kremenekce815422010-07-19 21:25:57 +00005658 return keepGoing;
5659}
5660
Richard Trieu03cf7b72011-10-28 00:41:25 +00005661void
5662CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5663 const char *startSpec,
5664 unsigned specifierLen) {
5665 EmitFormatDiagnostic(
5666 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5667 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5668}
5669
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005670bool
5671CheckFormatHandler::CheckNumArgs(
5672 const analyze_format_string::FormatSpecifier &FS,
5673 const analyze_format_string::ConversionSpecifier &CS,
5674 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5675
5676 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005677 PartialDiagnostic PDiag = FS.usesPositionalArg()
5678 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5679 << (argIndex+1) << NumDataArgs)
5680 : S.PDiag(diag::warn_printf_insufficient_data_args);
5681 EmitFormatDiagnostic(
5682 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5683 getSpecifierRange(startSpecifier, specifierLen));
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005684
5685 // Since more arguments than conversion tokens are given, by extension
5686 // all arguments are covered, so mark this as so.
5687 UncoveredArg.setAllCovered();
Ted Kremenek6adb7e32010-07-26 19:45:42 +00005688 return false;
5689 }
5690 return true;
5691}
5692
Richard Trieu03cf7b72011-10-28 00:41:25 +00005693template<typename Range>
5694void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5695 SourceLocation Loc,
5696 bool IsStringLocation,
5697 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00005698 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00005699 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00005700 Loc, IsStringLocation, StringRange, FixIt);
5701}
5702
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005703/// \brief If the format string is not within the function call, emit a note
Richard Trieu03cf7b72011-10-28 00:41:25 +00005704/// so that the function call and string are in diagnostic messages.
5705///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005706/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00005707/// call and only one diagnostic message will be produced. Otherwise, an
5708/// extra note will be emitted pointing to location of the format string.
5709///
5710/// \param ArgumentExpr the expression that is passed as the format string
5711/// argument in the function call. Used for getting locations when two
5712/// diagnostics are emitted.
5713///
5714/// \param PDiag the callee should already have provided any strings for the
5715/// diagnostic message. This function only adds locations and fixits
5716/// to diagnostics.
5717///
5718/// \param Loc primary location for diagnostic. If two diagnostics are
5719/// required, one will be at Loc and a new SourceLocation will be created for
5720/// the other one.
5721///
5722/// \param IsStringLocation if true, Loc points to the format string should be
5723/// used for the note. Otherwise, Loc points to the argument list and will
5724/// be used with PDiag.
5725///
5726/// \param StringRange some or all of the string to highlight. This is
5727/// templated so it can accept either a CharSourceRange or a SourceRange.
5728///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00005729/// \param FixIt optional fix it hint for the format string.
Benjamin Kramer7320b992016-06-15 14:20:56 +00005730template <typename Range>
5731void CheckFormatHandler::EmitFormatDiagnostic(
5732 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5733 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5734 Range StringRange, ArrayRef<FixItHint> FixIt) {
Jordan Roseaee34382012-09-05 22:56:26 +00005735 if (InFunctionCall) {
5736 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5737 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005738 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00005739 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005740 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5741 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00005742
5743 const Sema::SemaDiagnosticBuilder &Note =
5744 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5745 diag::note_format_string_defined);
5746
5747 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00005748 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00005749 }
5750}
5751
Ted Kremenek02087932010-07-16 02:11:22 +00005752//===--- CHECK: Printf format string checking ------------------------------===//
5753
5754namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005755
Ted Kremenek02087932010-07-16 02:11:22 +00005756class CheckPrintfHandler : public CheckFormatHandler {
5757public:
Stephen Hines648c3692016-09-16 01:07:04 +00005758 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00005759 const Expr *origFormatExpr,
5760 const Sema::FormatStringType type, unsigned firstDataArg,
5761 unsigned numDataArgs, bool isObjC, const char *beg,
5762 bool hasVAListArg, ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00005763 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00005764 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00005765 llvm::SmallBitVector &CheckedVarArgs,
5766 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00005767 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5768 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5769 inFunctionCall, CallType, CheckedVarArgs,
5770 UncoveredArg) {}
5771
5772 bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5773
5774 /// Returns true if '%@' specifiers are allowed in the format string.
5775 bool allowsObjCArg() const {
5776 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5777 FSType == Sema::FST_OSTrace;
5778 }
Jordan Rose3e0ec582012-07-19 18:10:23 +00005779
Ted Kremenek02087932010-07-16 02:11:22 +00005780 bool HandleInvalidPrintfConversionSpecifier(
5781 const analyze_printf::PrintfSpecifier &FS,
5782 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005783 unsigned specifierLen) override;
5784
Ted Kremenek02087932010-07-16 02:11:22 +00005785 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5786 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00005787 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005788 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5789 const char *StartSpecifier,
5790 unsigned SpecifierLen,
5791 const Expr *E);
5792
Ted Kremenek02087932010-07-16 02:11:22 +00005793 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5794 const char *startSpecifier, unsigned specifierLen);
5795 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5796 const analyze_printf::OptionalAmount &Amt,
5797 unsigned type,
5798 const char *startSpecifier, unsigned specifierLen);
5799 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5800 const analyze_printf::OptionalFlag &flag,
5801 const char *startSpecifier, unsigned specifierLen);
5802 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5803 const analyze_printf::OptionalFlag &ignoredFlag,
5804 const analyze_printf::OptionalFlag &flag,
5805 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005806 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00005807 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00005808
5809 void HandleEmptyObjCModifierFlag(const char *startFlag,
5810 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00005811
Ted Kremenek2b417712015-07-02 05:39:16 +00005812 void HandleInvalidObjCModifierFlag(const char *startFlag,
5813 unsigned flagLen) override;
5814
5815 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5816 const char *flagsEnd,
5817 const char *conversionPosition)
5818 override;
5819};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00005820
5821} // namespace
Ted Kremenek02087932010-07-16 02:11:22 +00005822
5823bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5824 const analyze_printf::PrintfSpecifier &FS,
5825 const char *startSpecifier,
5826 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005827 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00005828 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00005829
Ted Kremenekce815422010-07-19 21:25:57 +00005830 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5831 getLocationOfByte(CS.getStart()),
5832 startSpecifier, specifierLen,
5833 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00005834}
5835
Ted Kremenek02087932010-07-16 02:11:22 +00005836bool CheckPrintfHandler::HandleAmount(
5837 const analyze_format_string::OptionalAmount &Amt,
5838 unsigned k, const char *startSpecifier,
5839 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005840 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00005841 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00005842 unsigned argIndex = Amt.getArgIndex();
5843 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005844 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5845 << k,
5846 getLocationOfByte(Amt.getStart()),
5847 /*IsStringLocation*/true,
5848 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005849 // Don't do any more checking. We will just emit
5850 // spurious errors.
5851 return false;
5852 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005853
Ted Kremenek5739de72010-01-29 01:06:55 +00005854 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00005855 // Although not in conformance with C99, we also allow the argument to be
5856 // an 'unsigned int' as that is a reasonably safe case. GCC also
5857 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00005858 CoveredArgs.set(argIndex);
5859 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00005860 if (!Arg)
5861 return false;
5862
Ted Kremenek5739de72010-01-29 01:06:55 +00005863 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005864
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005865 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5866 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005867
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005868 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00005869 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00005870 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00005871 << T << Arg->getSourceRange(),
5872 getLocationOfByte(Amt.getStart()),
5873 /*IsStringLocation*/true,
5874 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00005875 // Don't do any more checking. We will just emit
5876 // spurious errors.
5877 return false;
5878 }
5879 }
5880 }
5881 return true;
5882}
Ted Kremenek5739de72010-01-29 01:06:55 +00005883
Tom Careb49ec692010-06-17 19:00:27 +00005884void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00005885 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005886 const analyze_printf::OptionalAmount &Amt,
5887 unsigned type,
5888 const char *startSpecifier,
5889 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005890 const analyze_printf::PrintfConversionSpecifier &CS =
5891 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00005892
Richard Trieu03cf7b72011-10-28 00:41:25 +00005893 FixItHint fixit =
5894 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5895 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5896 Amt.getConstantLength()))
5897 : FixItHint();
5898
5899 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5900 << type << CS.toString(),
5901 getLocationOfByte(Amt.getStart()),
5902 /*IsStringLocation*/true,
5903 getSpecifierRange(startSpecifier, specifierLen),
5904 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00005905}
5906
Ted Kremenek02087932010-07-16 02:11:22 +00005907void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005908 const analyze_printf::OptionalFlag &flag,
5909 const char *startSpecifier,
5910 unsigned specifierLen) {
5911 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00005912 const analyze_printf::PrintfConversionSpecifier &CS =
5913 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00005914 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5915 << flag.toString() << CS.toString(),
5916 getLocationOfByte(flag.getPosition()),
5917 /*IsStringLocation*/true,
5918 getSpecifierRange(startSpecifier, specifierLen),
5919 FixItHint::CreateRemoval(
5920 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005921}
5922
5923void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00005924 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00005925 const analyze_printf::OptionalFlag &ignoredFlag,
5926 const analyze_printf::OptionalFlag &flag,
5927 const char *startSpecifier,
5928 unsigned specifierLen) {
5929 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00005930 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5931 << ignoredFlag.toString() << flag.toString(),
5932 getLocationOfByte(ignoredFlag.getPosition()),
5933 /*IsStringLocation*/true,
5934 getSpecifierRange(startSpecifier, specifierLen),
5935 FixItHint::CreateRemoval(
5936 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00005937}
5938
Ted Kremenek2b417712015-07-02 05:39:16 +00005939void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5940 unsigned flagLen) {
5941 // Warn about an empty flag.
5942 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5943 getLocationOfByte(startFlag),
5944 /*IsStringLocation*/true,
5945 getSpecifierRange(startFlag, flagLen));
5946}
5947
5948void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5949 unsigned flagLen) {
5950 // Warn about an invalid flag.
5951 auto Range = getSpecifierRange(startFlag, flagLen);
5952 StringRef flag(startFlag, flagLen);
5953 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5954 getLocationOfByte(startFlag),
5955 /*IsStringLocation*/true,
5956 Range, FixItHint::CreateRemoval(Range));
5957}
5958
5959void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5960 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5961 // Warn about using '[...]' without a '@' conversion.
5962 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5963 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5964 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5965 getLocationOfByte(conversionPosition),
5966 /*IsStringLocation*/true,
5967 Range, FixItHint::CreateRemoval(Range));
5968}
5969
Richard Smith55ce3522012-06-25 20:30:08 +00005970// Determines if the specified is a C++ class or struct containing
5971// a member with the specified name and kind (e.g. a CXXMethodDecl named
5972// "c_str()").
5973template<typename MemberKind>
5974static llvm::SmallPtrSet<MemberKind*, 1>
5975CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5976 const RecordType *RT = Ty->getAs<RecordType>();
5977 llvm::SmallPtrSet<MemberKind*, 1> Results;
5978
5979 if (!RT)
5980 return Results;
5981 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00005982 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00005983 return Results;
5984
Alp Tokerb6cc5922014-05-03 03:45:55 +00005985 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00005986 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00005987 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00005988
5989 // We just need to include all members of the right kind turned up by the
5990 // filter, at this point.
5991 if (S.LookupQualifiedName(R, RT->getDecl()))
5992 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5993 NamedDecl *decl = (*I)->getUnderlyingDecl();
5994 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5995 Results.insert(FK);
5996 }
5997 return Results;
5998}
5999
Richard Smith2868a732014-02-28 01:36:39 +00006000/// Check if we could call '.c_str()' on an object.
6001///
6002/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
6003/// allow the call, or if it would be ambiguous).
6004bool Sema::hasCStrMethod(const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006005 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
6006
Richard Smith2868a732014-02-28 01:36:39 +00006007 MethodSet Results =
6008 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
6009 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6010 MI != ME; ++MI)
6011 if ((*MI)->getMinRequiredArguments() == 0)
6012 return true;
6013 return false;
6014}
6015
Richard Smith55ce3522012-06-25 20:30:08 +00006016// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00006017// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00006018// Returns true when a c_str() conversion method is found.
6019bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00006020 const analyze_printf::ArgType &AT, const Expr *E) {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006021 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
Richard Smith55ce3522012-06-25 20:30:08 +00006022
6023 MethodSet Results =
6024 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
6025
6026 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
6027 MI != ME; ++MI) {
6028 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00006029 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00006030 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00006031 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00006032 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00006033 S.Diag(E->getLocStart(), diag::note_printf_c_str)
6034 << "c_str()"
6035 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
6036 return true;
6037 }
6038 }
6039
6040 return false;
6041}
6042
Ted Kremenekab278de2010-01-28 23:39:18 +00006043bool
Ted Kremenek02087932010-07-16 02:11:22 +00006044CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00006045 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00006046 const char *startSpecifier,
6047 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006048 using namespace analyze_format_string;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006049 using namespace analyze_printf;
6050
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006051 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00006052
Ted Kremenek6cd69422010-07-19 22:01:06 +00006053 if (FS.consumesDataArgument()) {
6054 if (atFirstArg) {
6055 atFirstArg = false;
6056 usesPositionalArgs = FS.usesPositionalArg();
6057 }
6058 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006059 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6060 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006061 return false;
6062 }
Ted Kremenek5739de72010-01-29 01:06:55 +00006063 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006064
Ted Kremenekd1668192010-02-27 01:41:03 +00006065 // First check if the field width, precision, and conversion specifier
6066 // have matching data arguments.
6067 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6068 startSpecifier, specifierLen)) {
6069 return false;
6070 }
6071
6072 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6073 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00006074 return false;
6075 }
6076
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006077 if (!CS.consumesDataArgument()) {
6078 // FIXME: Technically specifying a precision or field width here
6079 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00006080 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00006081 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006082
Ted Kremenek4a49d982010-02-26 19:18:41 +00006083 // Consume the argument.
6084 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00006085 if (argIndex < NumDataArgs) {
6086 // The check to see if the argIndex is valid will come later.
6087 // We set the bit here because we may exit early from this
6088 // function if we encounter some other error.
6089 CoveredArgs.set(argIndex);
6090 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00006091
Dimitry Andric6b5ed342015-02-19 22:32:33 +00006092 // FreeBSD kernel extensions.
6093 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6094 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6095 // We need at least two arguments.
6096 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6097 return false;
6098
6099 // Claim the second argument.
6100 CoveredArgs.set(argIndex + 1);
6101
6102 // Type check the first argument (int for %b, pointer for %D)
6103 const Expr *Ex = getDataArg(argIndex);
6104 const analyze_printf::ArgType &AT =
6105 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6106 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6107 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6108 EmitFormatDiagnostic(
6109 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6110 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6111 << false << Ex->getSourceRange(),
6112 Ex->getLocStart(), /*IsStringLocation*/false,
6113 getSpecifierRange(startSpecifier, specifierLen));
6114
6115 // Type check the second argument (char * for both %b and %D)
6116 Ex = getDataArg(argIndex + 1);
6117 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6118 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6119 EmitFormatDiagnostic(
6120 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6121 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6122 << false << Ex->getSourceRange(),
6123 Ex->getLocStart(), /*IsStringLocation*/false,
6124 getSpecifierRange(startSpecifier, specifierLen));
6125
6126 return true;
6127 }
6128
Ted Kremenek4a49d982010-02-26 19:18:41 +00006129 // Check for using an Objective-C specific conversion specifier
6130 // in a non-ObjC literal.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006131 if (!allowsObjCArg() && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00006132 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6133 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00006134 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006135
Mehdi Amini06d367c2016-10-24 20:39:34 +00006136 // %P can only be used with os_log.
6137 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6138 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6139 specifierLen);
6140 }
6141
6142 // %n is not allowed with os_log.
6143 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6144 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6145 getLocationOfByte(CS.getStart()),
6146 /*IsStringLocation*/ false,
6147 getSpecifierRange(startSpecifier, specifierLen));
6148
6149 return true;
6150 }
6151
6152 // Only scalars are allowed for os_trace.
6153 if (FSType == Sema::FST_OSTrace &&
6154 (CS.getKind() == ConversionSpecifier::PArg ||
6155 CS.getKind() == ConversionSpecifier::sArg ||
6156 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6157 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6158 specifierLen);
6159 }
6160
6161 // Check for use of public/private annotation outside of os_log().
6162 if (FSType != Sema::FST_OSLog) {
6163 if (FS.isPublic().isSet()) {
6164 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6165 << "public",
6166 getLocationOfByte(FS.isPublic().getPosition()),
6167 /*IsStringLocation*/ false,
6168 getSpecifierRange(startSpecifier, specifierLen));
6169 }
6170 if (FS.isPrivate().isSet()) {
6171 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6172 << "private",
6173 getLocationOfByte(FS.isPrivate().getPosition()),
6174 /*IsStringLocation*/ false,
6175 getSpecifierRange(startSpecifier, specifierLen));
6176 }
6177 }
6178
Tom Careb49ec692010-06-17 19:00:27 +00006179 // Check for invalid use of field width
6180 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00006181 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00006182 startSpecifier, specifierLen);
6183 }
6184
6185 // Check for invalid use of precision
6186 if (!FS.hasValidPrecision()) {
6187 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6188 startSpecifier, specifierLen);
6189 }
6190
Mehdi Amini06d367c2016-10-24 20:39:34 +00006191 // Precision is mandatory for %P specifier.
6192 if (CS.getKind() == ConversionSpecifier::PArg &&
6193 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6194 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6195 getLocationOfByte(startSpecifier),
6196 /*IsStringLocation*/ false,
6197 getSpecifierRange(startSpecifier, specifierLen));
6198 }
6199
Tom Careb49ec692010-06-17 19:00:27 +00006200 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00006201 if (!FS.hasValidThousandsGroupingPrefix())
6202 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006203 if (!FS.hasValidLeadingZeros())
6204 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6205 if (!FS.hasValidPlusPrefix())
6206 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00006207 if (!FS.hasValidSpacePrefix())
6208 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006209 if (!FS.hasValidAlternativeForm())
6210 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6211 if (!FS.hasValidLeftJustified())
6212 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6213
6214 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00006215 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6216 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6217 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00006218 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6219 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6220 startSpecifier, specifierLen);
6221
6222 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006223 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006224 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6225 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006226 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006227 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006228 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006229 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6230 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00006231
Jordan Rose92303592012-09-08 04:00:03 +00006232 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6233 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6234
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006235 // The remaining checks depend on the data arguments.
6236 if (HasVAListArg)
6237 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006238
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006239 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00006240 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006241
Jordan Rose58bbe422012-07-19 18:10:08 +00006242 const Expr *Arg = getDataArg(argIndex);
6243 if (!Arg)
6244 return true;
6245
6246 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00006247}
6248
Jordan Roseaee34382012-09-05 22:56:26 +00006249static bool requiresParensToAddCast(const Expr *E) {
6250 // FIXME: We should have a general way to reason about operator
6251 // precedence and whether parens are actually needed here.
6252 // Take care of a few common cases where they aren't.
6253 const Expr *Inside = E->IgnoreImpCasts();
6254 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6255 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6256
6257 switch (Inside->getStmtClass()) {
6258 case Stmt::ArraySubscriptExprClass:
6259 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006260 case Stmt::CharacterLiteralClass:
6261 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006262 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006263 case Stmt::FloatingLiteralClass:
6264 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006265 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006266 case Stmt::ObjCArrayLiteralClass:
6267 case Stmt::ObjCBoolLiteralExprClass:
6268 case Stmt::ObjCBoxedExprClass:
6269 case Stmt::ObjCDictionaryLiteralClass:
6270 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006271 case Stmt::ObjCIvarRefExprClass:
6272 case Stmt::ObjCMessageExprClass:
6273 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006274 case Stmt::ObjCStringLiteralClass:
6275 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006276 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00006277 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00006278 case Stmt::UnaryOperatorClass:
6279 return false;
6280 default:
6281 return true;
6282 }
6283}
6284
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006285static std::pair<QualType, StringRef>
6286shouldNotPrintDirectly(const ASTContext &Context,
6287 QualType IntendedTy,
6288 const Expr *E) {
6289 // Use a 'while' to peel off layers of typedefs.
6290 QualType TyTy = IntendedTy;
6291 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6292 StringRef Name = UserTy->getDecl()->getName();
6293 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Saleem Abdulrasoola01ed932017-10-17 17:39:32 +00006294 .Case("CFIndex", Context.getNSIntegerType())
6295 .Case("NSInteger", Context.getNSIntegerType())
6296 .Case("NSUInteger", Context.getNSUIntegerType())
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006297 .Case("SInt32", Context.IntTy)
6298 .Case("UInt32", Context.UnsignedIntTy)
6299 .Default(QualType());
6300
6301 if (!CastTy.isNull())
6302 return std::make_pair(CastTy, Name);
6303
6304 TyTy = UserTy->desugar();
6305 }
6306
6307 // Strip parens if necessary.
6308 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6309 return shouldNotPrintDirectly(Context,
6310 PE->getSubExpr()->getType(),
6311 PE->getSubExpr());
6312
6313 // If this is a conditional expression, then its result type is constructed
6314 // via usual arithmetic conversions and thus there might be no necessary
6315 // typedef sugar there. Recurse to operands to check for NSInteger &
6316 // Co. usage condition.
6317 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6318 QualType TrueTy, FalseTy;
6319 StringRef TrueName, FalseName;
6320
6321 std::tie(TrueTy, TrueName) =
6322 shouldNotPrintDirectly(Context,
6323 CO->getTrueExpr()->getType(),
6324 CO->getTrueExpr());
6325 std::tie(FalseTy, FalseName) =
6326 shouldNotPrintDirectly(Context,
6327 CO->getFalseExpr()->getType(),
6328 CO->getFalseExpr());
6329
6330 if (TrueTy == FalseTy)
6331 return std::make_pair(TrueTy, TrueName);
6332 else if (TrueTy.isNull())
6333 return std::make_pair(FalseTy, FalseName);
6334 else if (FalseTy.isNull())
6335 return std::make_pair(TrueTy, TrueName);
6336 }
6337
6338 return std::make_pair(QualType(), StringRef());
6339}
6340
Richard Smith55ce3522012-06-25 20:30:08 +00006341bool
6342CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6343 const char *StartSpecifier,
6344 unsigned SpecifierLen,
6345 const Expr *E) {
6346 using namespace analyze_format_string;
6347 using namespace analyze_printf;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006348
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006349 // Now type check the data expression that matches the
6350 // format specifier.
Mehdi Amini06d367c2016-10-24 20:39:34 +00006351 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
Jordan Rose22b74712012-09-05 22:56:19 +00006352 if (!AT.isValid())
6353 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00006354
Jordan Rose598ec092012-12-05 18:44:40 +00006355 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00006356 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6357 ExprTy = TET->getUnderlyingExpr()->getType();
6358 }
6359
Seth Cantrellb4802962015-03-04 03:12:10 +00006360 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6361
6362 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00006363 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006364 }
Jordan Rose98709982012-06-04 22:48:57 +00006365
Jordan Rose22b74712012-09-05 22:56:19 +00006366 // Look through argument promotions for our error message's reported type.
6367 // This includes the integral and floating promotions, but excludes array
6368 // and function pointer decay; seeing that an argument intended to be a
6369 // string has type 'char [6]' is probably more confusing than 'char *'.
6370 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6371 if (ICE->getCastKind() == CK_IntegralCast ||
6372 ICE->getCastKind() == CK_FloatingCast) {
6373 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00006374 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00006375
6376 // Check if we didn't match because of an implicit cast from a 'char'
6377 // or 'short' to an 'int'. This is done because printf is a varargs
6378 // function.
6379 if (ICE->getType() == S.Context.IntTy ||
6380 ICE->getType() == S.Context.UnsignedIntTy) {
6381 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00006382 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00006383 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00006384 }
Jordan Rose98709982012-06-04 22:48:57 +00006385 }
Jordan Rose598ec092012-12-05 18:44:40 +00006386 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6387 // Special case for 'a', which has type 'int' in C.
6388 // Note, however, that we do /not/ want to treat multibyte constants like
6389 // 'MooV' as characters! This form is deprecated but still exists.
6390 if (ExprTy == S.Context.IntTy)
6391 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6392 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00006393 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006394
Jordan Rosebc53ed12014-05-31 04:12:14 +00006395 // Look through enums to their underlying type.
6396 bool IsEnum = false;
6397 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6398 ExprTy = EnumTy->getDecl()->getIntegerType();
6399 IsEnum = true;
6400 }
6401
Jordan Rose0e5badd2012-12-05 18:44:49 +00006402 // %C in an Objective-C context prints a unichar, not a wchar_t.
6403 // If the argument is an integer of some kind, believe the %C and suggest
6404 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00006405 QualType IntendedTy = ExprTy;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006406 if (isObjCContext() &&
Jordan Rose0e5badd2012-12-05 18:44:49 +00006407 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6408 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6409 !ExprTy->isCharType()) {
6410 // 'unichar' is defined as a typedef of unsigned short, but we should
6411 // prefer using the typedef if it is visible.
6412 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00006413
6414 // While we are here, check if the value is an IntegerLiteral that happens
6415 // to be within the valid range.
6416 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6417 const llvm::APInt &V = IL->getValue();
6418 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6419 return true;
6420 }
6421
Jordan Rose0e5badd2012-12-05 18:44:49 +00006422 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6423 Sema::LookupOrdinaryName);
6424 if (S.LookupName(Result, S.getCurScope())) {
6425 NamedDecl *ND = Result.getFoundDecl();
6426 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6427 if (TD->getUnderlyingType() == IntendedTy)
6428 IntendedTy = S.Context.getTypedefType(TD);
6429 }
6430 }
6431 }
6432
6433 // Special-case some of Darwin's platform-independence types by suggesting
6434 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006435 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00006436 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006437 QualType CastTy;
6438 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6439 if (!CastTy.isNull()) {
6440 IntendedTy = CastTy;
6441 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00006442 }
6443 }
6444
Jordan Rose22b74712012-09-05 22:56:19 +00006445 // We may be able to offer a FixItHint if it is a supported type.
6446 PrintfSpecifier fixedFS = FS;
Mehdi Amini06d367c2016-10-24 20:39:34 +00006447 bool success =
6448 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006449
Jordan Rose22b74712012-09-05 22:56:19 +00006450 if (success) {
6451 // Get the fix string from the fixed format specifier
6452 SmallString<16> buf;
6453 llvm::raw_svector_ostream os(buf);
6454 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006455
Jordan Roseaee34382012-09-05 22:56:26 +00006456 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6457
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006458 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00006459 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6460 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6461 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6462 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00006463 // In this case, the specifier is wrong and should be changed to match
6464 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00006465 EmitFormatDiagnostic(S.PDiag(diag)
6466 << AT.getRepresentativeTypeName(S.Context)
6467 << IntendedTy << IsEnum << E->getSourceRange(),
6468 E->getLocStart(),
6469 /*IsStringLocation*/ false, SpecRange,
6470 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00006471 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00006472 // The canonical type for formatting this value is different from the
6473 // actual type of the expression. (This occurs, for example, with Darwin's
6474 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6475 // should be printed as 'long' for 64-bit compatibility.)
6476 // Rather than emitting a normal format/argument mismatch, we want to
6477 // add a cast to the recommended type (and correct the format string
6478 // if necessary).
6479 SmallString<16> CastBuf;
6480 llvm::raw_svector_ostream CastFix(CastBuf);
6481 CastFix << "(";
6482 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6483 CastFix << ")";
6484
6485 SmallVector<FixItHint,4> Hints;
Alexander Shaposhnikov1788a9b2017-09-22 18:36:06 +00006486 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
Jordan Roseaee34382012-09-05 22:56:26 +00006487 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6488
6489 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6490 // If there's already a cast present, just replace it.
6491 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6492 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6493
6494 } else if (!requiresParensToAddCast(E)) {
6495 // If the expression has high enough precedence,
6496 // just write the C-style cast.
6497 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6498 CastFix.str()));
6499 } else {
6500 // Otherwise, add parens around the expression as well as the cast.
6501 CastFix << "(";
6502 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6503 CastFix.str()));
6504
Alp Tokerb6cc5922014-05-03 03:45:55 +00006505 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00006506 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6507 }
6508
Jordan Rose0e5badd2012-12-05 18:44:49 +00006509 if (ShouldNotPrintDirectly) {
6510 // The expression has a type that should not be printed directly.
6511 // We extract the name from the typedef because we don't want to show
6512 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00006513 StringRef Name;
6514 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6515 Name = TypedefTy->getDecl()->getName();
6516 else
6517 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00006518 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00006519 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006520 << E->getSourceRange(),
6521 E->getLocStart(), /*IsStringLocation=*/false,
6522 SpecRange, Hints);
6523 } else {
6524 // In this case, the expression could be printed using a different
6525 // specifier, but we've decided that the specifier is probably correct
6526 // and we should cast instead. Just use the normal warning message.
6527 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00006528 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6529 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00006530 << E->getSourceRange(),
6531 E->getLocStart(), /*IsStringLocation*/false,
6532 SpecRange, Hints);
6533 }
Jordan Roseaee34382012-09-05 22:56:26 +00006534 }
Jordan Rose22b74712012-09-05 22:56:19 +00006535 } else {
6536 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6537 SpecifierLen);
6538 // Since the warning for passing non-POD types to variadic functions
6539 // was deferred until now, we emit a warning for non-POD
6540 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00006541 switch (S.isValidVarArgType(ExprTy)) {
6542 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00006543 case Sema::VAK_ValidInCXX11: {
6544 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6545 if (match == analyze_printf::ArgType::NoMatchPedantic) {
6546 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6547 }
Richard Smithd7293d72013-08-05 18:49:43 +00006548
Seth Cantrellb4802962015-03-04 03:12:10 +00006549 EmitFormatDiagnostic(
6550 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6551 << IsEnum << CSR << E->getSourceRange(),
6552 E->getLocStart(), /*IsStringLocation*/ false, CSR);
6553 break;
6554 }
Richard Smithd7293d72013-08-05 18:49:43 +00006555 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00006556 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00006557 EmitFormatDiagnostic(
6558 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006559 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00006560 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00006561 << CallType
6562 << AT.getRepresentativeTypeName(S.Context)
6563 << CSR
6564 << E->getSourceRange(),
6565 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00006566 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00006567 break;
6568
6569 case Sema::VAK_Invalid:
6570 if (ExprTy->isObjCObjectType())
6571 EmitFormatDiagnostic(
6572 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6573 << S.getLangOpts().CPlusPlus11
6574 << ExprTy
6575 << CallType
6576 << AT.getRepresentativeTypeName(S.Context)
6577 << CSR
6578 << E->getSourceRange(),
6579 E->getLocStart(), /*IsStringLocation*/false, CSR);
6580 else
6581 // FIXME: If this is an initializer list, suggest removing the braces
6582 // or inserting a cast to the target type.
6583 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6584 << isa<InitListExpr>(E) << ExprTy << CallType
6585 << AT.getRepresentativeTypeName(S.Context)
6586 << E->getSourceRange();
6587 break;
6588 }
6589
6590 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6591 "format string specifier index out of range");
6592 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00006593 }
6594
Ted Kremenekab278de2010-01-28 23:39:18 +00006595 return true;
6596}
6597
Ted Kremenek02087932010-07-16 02:11:22 +00006598//===--- CHECK: Scanf format string checking ------------------------------===//
6599
6600namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006601
Ted Kremenek02087932010-07-16 02:11:22 +00006602class CheckScanfHandler : public CheckFormatHandler {
6603public:
Stephen Hines648c3692016-09-16 01:07:04 +00006604 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
Mehdi Amini06d367c2016-10-24 20:39:34 +00006605 const Expr *origFormatExpr, Sema::FormatStringType type,
6606 unsigned firstDataArg, unsigned numDataArgs,
6607 const char *beg, bool hasVAListArg,
6608 ArrayRef<const Expr *> Args, unsigned formatIdx,
6609 bool inFunctionCall, Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006610 llvm::SmallBitVector &CheckedVarArgs,
6611 UncoveredArgHandler &UncoveredArg)
Mehdi Amini06d367c2016-10-24 20:39:34 +00006612 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6613 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6614 inFunctionCall, CallType, CheckedVarArgs,
6615 UncoveredArg) {}
6616
Ted Kremenek02087932010-07-16 02:11:22 +00006617 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6618 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006619 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00006620
6621 bool HandleInvalidScanfConversionSpecifier(
6622 const analyze_scanf::ScanfSpecifier &FS,
6623 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00006624 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006625
Craig Toppere14c0f82014-03-12 04:55:44 +00006626 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00006627};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00006628
6629} // namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00006630
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006631void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6632 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006633 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6634 getLocationOfByte(end), /*IsStringLocation*/true,
6635 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00006636}
6637
Ted Kremenekce815422010-07-19 21:25:57 +00006638bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6639 const analyze_scanf::ScanfSpecifier &FS,
6640 const char *startSpecifier,
6641 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006642 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00006643 FS.getConversionSpecifier();
6644
6645 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6646 getLocationOfByte(CS.getStart()),
6647 startSpecifier, specifierLen,
6648 CS.getStart(), CS.getLength());
6649}
6650
Ted Kremenek02087932010-07-16 02:11:22 +00006651bool CheckScanfHandler::HandleScanfSpecifier(
6652 const analyze_scanf::ScanfSpecifier &FS,
6653 const char *startSpecifier,
6654 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00006655 using namespace analyze_scanf;
6656 using namespace analyze_format_string;
6657
Ted Kremenekf03e6d852010-07-20 20:04:27 +00006658 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00006659
Ted Kremenek6cd69422010-07-19 22:01:06 +00006660 // Handle case where '%' and '*' don't consume an argument. These shouldn't
6661 // be used to decide if we are using positional arguments consistently.
6662 if (FS.consumesDataArgument()) {
6663 if (atFirstArg) {
6664 atFirstArg = false;
6665 usesPositionalArgs = FS.usesPositionalArg();
6666 }
6667 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006668 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6669 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00006670 return false;
6671 }
Ted Kremenek02087932010-07-16 02:11:22 +00006672 }
6673
6674 // Check if the field with is non-zero.
6675 const OptionalAmount &Amt = FS.getFieldWidth();
6676 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6677 if (Amt.getConstantAmount() == 0) {
6678 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6679 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00006680 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6681 getLocationOfByte(Amt.getStart()),
6682 /*IsStringLocation*/true, R,
6683 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00006684 }
6685 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006686
Ted Kremenek02087932010-07-16 02:11:22 +00006687 if (!FS.consumesDataArgument()) {
6688 // FIXME: Technically specifying a precision or field width here
6689 // makes no sense. Worth issuing a warning at some point.
6690 return true;
6691 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006692
Ted Kremenek02087932010-07-16 02:11:22 +00006693 // Consume the argument.
6694 unsigned argIndex = FS.getArgIndex();
6695 if (argIndex < NumDataArgs) {
6696 // The check to see if the argIndex is valid will come later.
6697 // We set the bit here because we may exit early from this
6698 // function if we encounter some other error.
6699 CoveredArgs.set(argIndex);
6700 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006701
Ted Kremenek4407ea42010-07-20 20:04:47 +00006702 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00006703 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00006704 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6705 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00006706 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006707 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00006708 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00006709 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6710 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00006711
Jordan Rose92303592012-09-08 04:00:03 +00006712 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6713 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6714
Ted Kremenek02087932010-07-16 02:11:22 +00006715 // The remaining checks depend on the data arguments.
6716 if (HasVAListArg)
6717 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00006718
Ted Kremenek6adb7e32010-07-26 19:45:42 +00006719 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00006720 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00006721
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006722 // Check that the argument type matches the format specifier.
6723 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00006724 if (!Ex)
6725 return true;
6726
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00006727 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00006728
6729 if (!AT.isValid()) {
6730 return true;
6731 }
6732
Seth Cantrellb4802962015-03-04 03:12:10 +00006733 analyze_format_string::ArgType::MatchKind match =
6734 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00006735 if (match == analyze_format_string::ArgType::Match) {
6736 return true;
6737 }
Seth Cantrellb4802962015-03-04 03:12:10 +00006738
Seth Cantrell79340072015-03-04 05:58:08 +00006739 ScanfSpecifier fixedFS = FS;
6740 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6741 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006742
Seth Cantrell79340072015-03-04 05:58:08 +00006743 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6744 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6745 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6746 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006747
Seth Cantrell79340072015-03-04 05:58:08 +00006748 if (success) {
6749 // Get the fix string from the fixed format specifier.
6750 SmallString<128> buf;
6751 llvm::raw_svector_ostream os(buf);
6752 fixedFS.toString(os);
6753
6754 EmitFormatDiagnostic(
6755 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6756 << Ex->getType() << false << Ex->getSourceRange(),
6757 Ex->getLocStart(),
6758 /*IsStringLocation*/ false,
6759 getSpecifierRange(startSpecifier, specifierLen),
6760 FixItHint::CreateReplacement(
6761 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6762 } else {
6763 EmitFormatDiagnostic(S.PDiag(diag)
6764 << AT.getRepresentativeTypeName(S.Context)
6765 << Ex->getType() << false << Ex->getSourceRange(),
6766 Ex->getLocStart(),
6767 /*IsStringLocation*/ false,
6768 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00006769 }
6770
Ted Kremenek02087932010-07-16 02:11:22 +00006771 return true;
6772}
6773
Stephen Hines648c3692016-09-16 01:07:04 +00006774static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006775 const Expr *OrigFormatExpr,
6776 ArrayRef<const Expr *> Args,
6777 bool HasVAListArg, unsigned format_idx,
6778 unsigned firstDataArg,
6779 Sema::FormatStringType Type,
6780 bool inFunctionCall,
6781 Sema::VariadicCallType CallType,
Andy Gibbs9a31b3b2016-02-26 15:35:16 +00006782 llvm::SmallBitVector &CheckedVarArgs,
6783 UncoveredArgHandler &UncoveredArg) {
Ted Kremenekab278de2010-01-28 23:39:18 +00006784 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00006785 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006786 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006787 S, inFunctionCall, Args[format_idx],
6788 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006789 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006790 return;
6791 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006792
Ted Kremenekab278de2010-01-28 23:39:18 +00006793 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006794 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00006795 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006796 // Account for cases where the string literal is truncated in a declaration.
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006797 const ConstantArrayType *T =
6798 S.Context.getAsConstantArrayType(FExpr->getType());
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006799 assert(T && "String literal not of constant array type!");
6800 size_t TypeSize = T->getSize().getZExtValue();
6801 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00006802 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006803
6804 // Emit a warning if the string literal is truncated and does not contain an
6805 // embedded null character.
6806 if (TypeSize <= StrRef.size() &&
6807 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6808 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006809 S, inFunctionCall, Args[format_idx],
6810 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00006811 FExpr->getLocStart(),
6812 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6813 return;
6814 }
6815
Ted Kremenekab278de2010-01-28 23:39:18 +00006816 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00006817 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00006818 CheckFormatHandler::EmitFormatDiagnostic(
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006819 S, inFunctionCall, Args[format_idx],
6820 S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
Richard Trieu03cf7b72011-10-28 00:41:25 +00006821 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00006822 return;
6823 }
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006824
6825 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Mehdi Amini06d367c2016-10-24 20:39:34 +00006826 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6827 Type == Sema::FST_OSTrace) {
6828 CheckPrintfHandler H(
6829 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6830 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6831 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6832 CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006833
Hans Wennborg23926bd2011-12-15 10:25:47 +00006834 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006835 S.getLangOpts(),
6836 S.Context.getTargetInfo(),
6837 Type == Sema::FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00006838 H.DoneProcessing();
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006839 } else if (Type == Sema::FST_Scanf) {
Mehdi Amini06d367c2016-10-24 20:39:34 +00006840 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6841 numDataArgs, Str, HasVAListArg, Args, format_idx,
6842 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006843
Hans Wennborg23926bd2011-12-15 10:25:47 +00006844 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Andy Gibbs4b3e3c82016-02-22 13:00:43 +00006845 S.getLangOpts(),
6846 S.Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00006847 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00006848 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00006849}
6850
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00006851bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6852 // Str - The format string. NOTE: this is NOT null-terminated!
6853 StringRef StrRef = FExpr->getString();
6854 const char *Str = StrRef.data();
6855 // Account for cases where the string literal is truncated in a declaration.
6856 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6857 assert(T && "String literal not of constant array type!");
6858 size_t TypeSize = T->getSize().getZExtValue();
6859 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6860 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6861 getLangOpts(),
6862 Context.getTargetInfo());
6863}
6864
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00006865//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6866
6867// Returns the related absolute value function that is larger, of 0 if one
6868// does not exist.
6869static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6870 switch (AbsFunction) {
6871 default:
6872 return 0;
6873
6874 case Builtin::BI__builtin_abs:
6875 return Builtin::BI__builtin_labs;
6876 case Builtin::BI__builtin_labs:
6877 return Builtin::BI__builtin_llabs;
6878 case Builtin::BI__builtin_llabs:
6879 return 0;
6880
6881 case Builtin::BI__builtin_fabsf:
6882 return Builtin::BI__builtin_fabs;
6883 case Builtin::BI__builtin_fabs:
6884 return Builtin::BI__builtin_fabsl;
6885 case Builtin::BI__builtin_fabsl:
6886 return 0;
6887
6888 case Builtin::BI__builtin_cabsf:
6889 return Builtin::BI__builtin_cabs;
6890 case Builtin::BI__builtin_cabs:
6891 return Builtin::BI__builtin_cabsl;
6892 case Builtin::BI__builtin_cabsl:
6893 return 0;
6894
6895 case Builtin::BIabs:
6896 return Builtin::BIlabs;
6897 case Builtin::BIlabs:
6898 return Builtin::BIllabs;
6899 case Builtin::BIllabs:
6900 return 0;
6901
6902 case Builtin::BIfabsf:
6903 return Builtin::BIfabs;
6904 case Builtin::BIfabs:
6905 return Builtin::BIfabsl;
6906 case Builtin::BIfabsl:
6907 return 0;
6908
6909 case Builtin::BIcabsf:
6910 return Builtin::BIcabs;
6911 case Builtin::BIcabs:
6912 return Builtin::BIcabsl;
6913 case Builtin::BIcabsl:
6914 return 0;
6915 }
6916}
6917
6918// Returns the argument type of the absolute value function.
6919static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6920 unsigned AbsType) {
6921 if (AbsType == 0)
6922 return QualType();
6923
6924 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6925 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6926 if (Error != ASTContext::GE_None)
6927 return QualType();
6928
6929 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6930 if (!FT)
6931 return QualType();
6932
6933 if (FT->getNumParams() != 1)
6934 return QualType();
6935
6936 return FT->getParamType(0);
6937}
6938
6939// Returns the best absolute value function, or zero, based on type and
6940// current absolute value function.
6941static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6942 unsigned AbsFunctionKind) {
6943 unsigned BestKind = 0;
6944 uint64_t ArgSize = Context.getTypeSize(ArgType);
6945 for (unsigned Kind = AbsFunctionKind; Kind != 0;
6946 Kind = getLargerAbsoluteValueFunction(Kind)) {
6947 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6948 if (Context.getTypeSize(ParamType) >= ArgSize) {
6949 if (BestKind == 0)
6950 BestKind = Kind;
6951 else if (Context.hasSameType(ParamType, ArgType)) {
6952 BestKind = Kind;
6953 break;
6954 }
6955 }
6956 }
6957 return BestKind;
6958}
6959
6960enum AbsoluteValueKind {
6961 AVK_Integer,
6962 AVK_Floating,
6963 AVK_Complex
6964};
6965
6966static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6967 if (T->isIntegralOrEnumerationType())
6968 return AVK_Integer;
6969 if (T->isRealFloatingType())
6970 return AVK_Floating;
6971 if (T->isAnyComplexType())
6972 return AVK_Complex;
6973
6974 llvm_unreachable("Type not integer, floating, or complex");
6975}
6976
6977// Changes the absolute value function to a different type. Preserves whether
6978// the function is a builtin.
6979static unsigned changeAbsFunction(unsigned AbsKind,
6980 AbsoluteValueKind ValueKind) {
6981 switch (ValueKind) {
6982 case AVK_Integer:
6983 switch (AbsKind) {
6984 default:
6985 return 0;
6986 case Builtin::BI__builtin_fabsf:
6987 case Builtin::BI__builtin_fabs:
6988 case Builtin::BI__builtin_fabsl:
6989 case Builtin::BI__builtin_cabsf:
6990 case Builtin::BI__builtin_cabs:
6991 case Builtin::BI__builtin_cabsl:
6992 return Builtin::BI__builtin_abs;
6993 case Builtin::BIfabsf:
6994 case Builtin::BIfabs:
6995 case Builtin::BIfabsl:
6996 case Builtin::BIcabsf:
6997 case Builtin::BIcabs:
6998 case Builtin::BIcabsl:
6999 return Builtin::BIabs;
7000 }
7001 case AVK_Floating:
7002 switch (AbsKind) {
7003 default:
7004 return 0;
7005 case Builtin::BI__builtin_abs:
7006 case Builtin::BI__builtin_labs:
7007 case Builtin::BI__builtin_llabs:
7008 case Builtin::BI__builtin_cabsf:
7009 case Builtin::BI__builtin_cabs:
7010 case Builtin::BI__builtin_cabsl:
7011 return Builtin::BI__builtin_fabsf;
7012 case Builtin::BIabs:
7013 case Builtin::BIlabs:
7014 case Builtin::BIllabs:
7015 case Builtin::BIcabsf:
7016 case Builtin::BIcabs:
7017 case Builtin::BIcabsl:
7018 return Builtin::BIfabsf;
7019 }
7020 case AVK_Complex:
7021 switch (AbsKind) {
7022 default:
7023 return 0;
7024 case Builtin::BI__builtin_abs:
7025 case Builtin::BI__builtin_labs:
7026 case Builtin::BI__builtin_llabs:
7027 case Builtin::BI__builtin_fabsf:
7028 case Builtin::BI__builtin_fabs:
7029 case Builtin::BI__builtin_fabsl:
7030 return Builtin::BI__builtin_cabsf;
7031 case Builtin::BIabs:
7032 case Builtin::BIlabs:
7033 case Builtin::BIllabs:
7034 case Builtin::BIfabsf:
7035 case Builtin::BIfabs:
7036 case Builtin::BIfabsl:
7037 return Builtin::BIcabsf;
7038 }
7039 }
7040 llvm_unreachable("Unable to convert function");
7041}
7042
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00007043static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007044 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
7045 if (!FnInfo)
7046 return 0;
7047
7048 switch (FDecl->getBuiltinID()) {
7049 default:
7050 return 0;
7051 case Builtin::BI__builtin_abs:
7052 case Builtin::BI__builtin_fabs:
7053 case Builtin::BI__builtin_fabsf:
7054 case Builtin::BI__builtin_fabsl:
7055 case Builtin::BI__builtin_labs:
7056 case Builtin::BI__builtin_llabs:
7057 case Builtin::BI__builtin_cabs:
7058 case Builtin::BI__builtin_cabsf:
7059 case Builtin::BI__builtin_cabsl:
7060 case Builtin::BIabs:
7061 case Builtin::BIlabs:
7062 case Builtin::BIllabs:
7063 case Builtin::BIfabs:
7064 case Builtin::BIfabsf:
7065 case Builtin::BIfabsl:
7066 case Builtin::BIcabs:
7067 case Builtin::BIcabsf:
7068 case Builtin::BIcabsl:
7069 return FDecl->getBuiltinID();
7070 }
7071 llvm_unreachable("Unknown Builtin type");
7072}
7073
7074// If the replacement is valid, emit a note with replacement function.
7075// Additionally, suggest including the proper header if not already included.
7076static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00007077 unsigned AbsKind, QualType ArgType) {
7078 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007079 const char *HeaderName = nullptr;
Mehdi Amini7186a432016-10-11 19:04:24 +00007080 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007081 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7082 FunctionName = "std::abs";
7083 if (ArgType->isIntegralOrEnumerationType()) {
7084 HeaderName = "cstdlib";
7085 } else if (ArgType->isRealFloatingType()) {
7086 HeaderName = "cmath";
7087 } else {
7088 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007089 }
Richard Trieubeffb832014-04-15 23:47:53 +00007090
7091 // Lookup all std::abs
7092 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00007093 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00007094 R.suppressDiagnostics();
7095 S.LookupQualifiedName(R, Std);
7096
7097 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007098 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00007099 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7100 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7101 } else {
7102 FDecl = dyn_cast<FunctionDecl>(I);
7103 }
7104 if (!FDecl)
7105 continue;
7106
7107 // Found std::abs(), check that they are the right ones.
7108 if (FDecl->getNumParams() != 1)
7109 continue;
7110
7111 // Check that the parameter type can handle the argument.
7112 QualType ParamType = FDecl->getParamDecl(0)->getType();
7113 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7114 S.Context.getTypeSize(ArgType) <=
7115 S.Context.getTypeSize(ParamType)) {
7116 // Found a function, don't need the header hint.
7117 EmitHeaderHint = false;
7118 break;
7119 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007120 }
Richard Trieubeffb832014-04-15 23:47:53 +00007121 }
7122 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00007123 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00007124 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7125
7126 if (HeaderName) {
7127 DeclarationName DN(&S.Context.Idents.get(FunctionName));
7128 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7129 R.suppressDiagnostics();
7130 S.LookupName(R, S.getCurScope());
7131
7132 if (R.isSingleResult()) {
7133 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7134 if (FD && FD->getBuiltinID() == AbsKind) {
7135 EmitHeaderHint = false;
7136 } else {
7137 return;
7138 }
7139 } else if (!R.empty()) {
7140 return;
7141 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007142 }
7143 }
7144
7145 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00007146 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007147
Richard Trieubeffb832014-04-15 23:47:53 +00007148 if (!HeaderName)
7149 return;
7150
7151 if (!EmitHeaderHint)
7152 return;
7153
Alp Toker5d96e0a2014-07-11 20:53:51 +00007154 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7155 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00007156}
7157
Richard Trieua7f30b12016-12-06 01:42:28 +00007158template <std::size_t StrLen>
7159static bool IsStdFunction(const FunctionDecl *FDecl,
7160 const char (&Str)[StrLen]) {
Richard Trieubeffb832014-04-15 23:47:53 +00007161 if (!FDecl)
7162 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007163 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
Richard Trieubeffb832014-04-15 23:47:53 +00007164 return false;
Richard Trieua7f30b12016-12-06 01:42:28 +00007165 if (!FDecl->isInStdNamespace())
Richard Trieubeffb832014-04-15 23:47:53 +00007166 return false;
7167
7168 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007169}
7170
7171// Warn when using the wrong abs() function.
7172void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
Richard Trieua7f30b12016-12-06 01:42:28 +00007173 const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007174 if (Call->getNumArgs() != 1)
7175 return;
7176
7177 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieua7f30b12016-12-06 01:42:28 +00007178 bool IsStdAbs = IsStdFunction(FDecl, "abs");
Richard Trieubeffb832014-04-15 23:47:53 +00007179 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007180 return;
7181
7182 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7183 QualType ParamType = Call->getArg(0)->getType();
7184
Alp Toker5d96e0a2014-07-11 20:53:51 +00007185 // Unsigned types cannot be negative. Suggest removing the absolute value
7186 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007187 if (ArgType->isUnsignedIntegerType()) {
Mehdi Amini7186a432016-10-11 19:04:24 +00007188 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00007189 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007190 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7191 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00007192 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007193 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7194 return;
7195 }
7196
David Majnemer7f77eb92015-11-15 03:04:34 +00007197 // Taking the absolute value of a pointer is very suspicious, they probably
7198 // wanted to index into an array, dereference a pointer, call a function, etc.
7199 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7200 unsigned DiagType = 0;
7201 if (ArgType->isFunctionType())
7202 DiagType = 1;
7203 else if (ArgType->isArrayType())
7204 DiagType = 2;
7205
7206 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7207 return;
7208 }
7209
Richard Trieubeffb832014-04-15 23:47:53 +00007210 // std::abs has overloads which prevent most of the absolute value problems
7211 // from occurring.
7212 if (IsStdAbs)
7213 return;
7214
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007215 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7216 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7217
7218 // The argument and parameter are the same kind. Check if they are the right
7219 // size.
7220 if (ArgValueKind == ParamValueKind) {
7221 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7222 return;
7223
7224 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7225 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7226 << FDecl << ArgType << ParamType;
7227
7228 if (NewAbsKind == 0)
7229 return;
7230
7231 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007232 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007233 return;
7234 }
7235
7236 // ArgValueKind != ParamValueKind
7237 // The wrong type of absolute value function was used. Attempt to find the
7238 // proper one.
7239 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7240 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7241 if (NewAbsKind == 0)
7242 return;
7243
7244 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7245 << FDecl << ParamValueKind << ArgValueKind;
7246
7247 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00007248 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007249}
7250
Richard Trieu67c00712016-12-05 23:41:46 +00007251//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
Richard Trieua7f30b12016-12-06 01:42:28 +00007252void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7253 const FunctionDecl *FDecl) {
Richard Trieu67c00712016-12-05 23:41:46 +00007254 if (!Call || !FDecl) return;
7255
7256 // Ignore template specializations and macros.
Richard Smith51ec0cf2017-02-21 01:17:38 +00007257 if (inTemplateInstantiation()) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007258 if (Call->getExprLoc().isMacroID()) return;
7259
7260 // Only care about the one template argument, two function parameter std::max
7261 if (Call->getNumArgs() != 2) return;
Richard Trieua7f30b12016-12-06 01:42:28 +00007262 if (!IsStdFunction(FDecl, "max")) return;
Richard Trieu67c00712016-12-05 23:41:46 +00007263 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7264 if (!ArgList) return;
7265 if (ArgList->size() != 1) return;
7266
7267 // Check that template type argument is unsigned integer.
7268 const auto& TA = ArgList->get(0);
7269 if (TA.getKind() != TemplateArgument::Type) return;
7270 QualType ArgType = TA.getAsType();
7271 if (!ArgType->isUnsignedIntegerType()) return;
7272
7273 // See if either argument is a literal zero.
7274 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7275 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7276 if (!MTE) return false;
7277 const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7278 if (!Num) return false;
7279 if (Num->getValue() != 0) return false;
7280 return true;
7281 };
7282
7283 const Expr *FirstArg = Call->getArg(0);
7284 const Expr *SecondArg = Call->getArg(1);
7285 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7286 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7287
7288 // Only warn when exactly one argument is zero.
7289 if (IsFirstArgZero == IsSecondArgZero) return;
7290
7291 SourceRange FirstRange = FirstArg->getSourceRange();
7292 SourceRange SecondRange = SecondArg->getSourceRange();
7293
7294 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7295
7296 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7297 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7298
7299 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7300 SourceRange RemovalRange;
7301 if (IsFirstArgZero) {
7302 RemovalRange = SourceRange(FirstRange.getBegin(),
7303 SecondRange.getBegin().getLocWithOffset(-1));
7304 } else {
7305 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7306 SecondRange.getEnd());
7307 }
7308
7309 Diag(Call->getExprLoc(), diag::note_remove_max_call)
7310 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7311 << FixItHint::CreateRemoval(RemovalRange);
7312}
7313
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007314//===--- CHECK: Standard memory functions ---------------------------------===//
7315
Nico Weber0e6daef2013-12-26 23:38:39 +00007316/// \brief Takes the expression passed to the size_t parameter of functions
7317/// such as memcmp, strncat, etc and warns if it's a comparison.
7318///
7319/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7320static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7321 IdentifierInfo *FnName,
7322 SourceLocation FnLoc,
7323 SourceLocation RParenLoc) {
7324 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7325 if (!Size)
7326 return false;
7327
Richard Smithc70f1d62017-12-14 15:16:18 +00007328 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7329 if (!Size->isComparisonOp() && !Size->isLogicalOp())
Nico Weber0e6daef2013-12-26 23:38:39 +00007330 return false;
7331
Nico Weber0e6daef2013-12-26 23:38:39 +00007332 SourceRange SizeRange = Size->getSourceRange();
7333 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7334 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00007335 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007336 << FnName << FixItHint::CreateInsertion(
7337 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00007338 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00007339 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00007340 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00007341 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7342 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00007343
7344 return true;
7345}
7346
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007347/// \brief Determine whether the given type is or contains a dynamic class type
7348/// (e.g., whether it has a vtable).
7349static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7350 bool &IsContained) {
7351 // Look through array types while ignoring qualifiers.
7352 const Type *Ty = T->getBaseElementTypeUnsafe();
7353 IsContained = false;
7354
7355 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7356 RD = RD ? RD->getDefinition() : nullptr;
Richard Trieu1c7237a2016-03-31 04:18:07 +00007357 if (!RD || RD->isInvalidDecl())
Reid Kleckner5fb5b122014-06-27 23:58:21 +00007358 return nullptr;
7359
7360 if (RD->isDynamicClass())
7361 return RD;
7362
7363 // Check all the fields. If any bases were dynamic, the class is dynamic.
7364 // It's impossible for a class to transitively contain itself by value, so
7365 // infinite recursion is impossible.
7366 for (auto *FD : RD->fields()) {
7367 bool SubContained;
7368 if (const CXXRecordDecl *ContainedRD =
7369 getContainedDynamicClass(FD->getType(), SubContained)) {
7370 IsContained = true;
7371 return ContainedRD;
7372 }
7373 }
7374
7375 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00007376}
7377
Chandler Carruth889ed862011-06-21 23:04:20 +00007378/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007379/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00007380static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00007381 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007382 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007383 if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007384 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007385
Craig Topperc3ec1492014-05-26 06:22:03 +00007386 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007387}
7388
Chandler Carruth889ed862011-06-21 23:04:20 +00007389/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00007390static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007391 if (const UnaryExprOrTypeTraitExpr *SizeOf =
7392 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007393 if (SizeOf->getKind() == UETT_SizeOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007394 return SizeOf->getTypeOfArgument();
7395
7396 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00007397}
7398
Akira Hatanaka2be04412018-04-17 19:13:41 +00007399namespace {
7400
7401struct SearchNonTrivialToInitializeField
7402 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
7403 using Super =
7404 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
7405
7406 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
7407
7408 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
7409 SourceLocation SL) {
7410 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7411 asDerived().visitArray(PDIK, AT, SL);
7412 return;
7413 }
7414
7415 Super::visitWithKind(PDIK, FT, SL);
7416 }
7417
7418 void visitARCStrong(QualType FT, SourceLocation SL) {
7419 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7420 }
7421 void visitARCWeak(QualType FT, SourceLocation SL) {
7422 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
7423 }
7424 void visitStruct(QualType FT, SourceLocation SL) {
7425 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7426 visit(FD->getType(), FD->getLocation());
7427 }
7428 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
7429 const ArrayType *AT, SourceLocation SL) {
7430 visit(getContext().getBaseElementType(AT), SL);
7431 }
7432 void visitTrivial(QualType FT, SourceLocation SL) {}
7433
7434 static void diag(QualType RT, const Expr *E, Sema &S) {
7435 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
7436 }
7437
7438 ASTContext &getContext() { return S.getASTContext(); }
7439
7440 const Expr *E;
7441 Sema &S;
7442};
7443
7444struct SearchNonTrivialToCopyField
7445 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
7446 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
7447
7448 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
7449
7450 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
7451 SourceLocation SL) {
7452 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
7453 asDerived().visitArray(PCK, AT, SL);
7454 return;
7455 }
7456
7457 Super::visitWithKind(PCK, FT, SL);
7458 }
7459
7460 void visitARCStrong(QualType FT, SourceLocation SL) {
7461 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7462 }
7463 void visitARCWeak(QualType FT, SourceLocation SL) {
7464 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
7465 }
7466 void visitStruct(QualType FT, SourceLocation SL) {
7467 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
7468 visit(FD->getType(), FD->getLocation());
7469 }
7470 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
7471 SourceLocation SL) {
7472 visit(getContext().getBaseElementType(AT), SL);
7473 }
7474 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
7475 SourceLocation SL) {}
7476 void visitTrivial(QualType FT, SourceLocation SL) {}
7477 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
7478
7479 static void diag(QualType RT, const Expr *E, Sema &S) {
7480 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
7481 }
7482
7483 ASTContext &getContext() { return S.getASTContext(); }
7484
7485 const Expr *E;
7486 Sema &S;
7487};
7488
7489}
7490
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007491/// \brief Check for dangerous or invalid arguments to memset().
7492///
Chandler Carruthac687262011-06-03 06:23:57 +00007493/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007494/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7495/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007496///
7497/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007498void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00007499 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00007500 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00007501 assert(BId != 0);
7502
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007503 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00007504 // we have enough arguments, and if not, abort further checking.
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007505 unsigned ExpectedNumArgs =
7506 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00007507 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00007508 return;
7509
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007510 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
Anna Zaks22122702012-01-17 00:37:07 +00007511 BId == Builtin::BIstrndup ? 1 : 2);
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00007512 unsigned LenArg =
7513 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00007514 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007515
Nico Weber0e6daef2013-12-26 23:38:39 +00007516 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7517 Call->getLocStart(), Call->getRParenLoc()))
7518 return;
7519
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007520 // We have special checking when the length is a sizeof expression.
7521 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7522 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7523 llvm::FoldingSetNodeID SizeOfArgID;
7524
Bruno Cardoso Lopesc73e4c32016-08-11 18:33:15 +00007525 // Although widely used, 'bzero' is not a standard function. Be more strict
7526 // with the argument types before allowing diagnostics and only allow the
7527 // form bzero(ptr, sizeof(...)).
7528 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7529 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7530 return;
7531
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007532 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7533 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00007534 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007535
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007536 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00007537 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007538 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00007539 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00007540
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007541 // Never warn about void type pointers. This can be used to suppress
7542 // false positives.
7543 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00007544 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007545
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007546 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7547 // actually comparing the expressions for equality. Because computing the
7548 // expression IDs can be expensive, we only do this if the diagnostic is
7549 // enabled.
7550 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007551 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7552 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007553 // We only compute IDs for expressions if the warning is enabled, and
7554 // cache the sizeof arg's ID.
7555 if (SizeOfArgID == llvm::FoldingSetNodeID())
7556 SizeOfArg->Profile(SizeOfArgID, Context, true);
7557 llvm::FoldingSetNodeID DestID;
7558 Dest->Profile(DestID, Context, true);
7559 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00007560 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7561 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007562 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00007563 StringRef ReadableName = FnName->getName();
7564
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007565 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00007566 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007567 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00007568 if (!PointeeTy->isIncompleteType() &&
7569 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007570 ActionIdx = 2; // If the pointee's size is sizeof(char),
7571 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00007572
7573 // If the function is defined as a builtin macro, do not show macro
7574 // expansion.
7575 SourceLocation SL = SizeOfArg->getExprLoc();
7576 SourceRange DSR = Dest->getSourceRange();
7577 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007578 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00007579
7580 if (SM.isMacroArgExpansion(SL)) {
7581 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7582 SL = SM.getSpellingLoc(SL);
7583 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7584 SM.getSpellingLoc(DSR.getEnd()));
7585 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7586 SM.getSpellingLoc(SSR.getEnd()));
7587 }
7588
Anna Zaksd08d9152012-05-30 23:14:52 +00007589 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007590 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00007591 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00007592 << PointeeTy
7593 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00007594 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00007595 << SSR);
7596 DiagRuntimeBehavior(SL, SizeOfArg,
7597 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7598 << ActionIdx
7599 << SSR);
7600
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00007601 break;
7602 }
7603 }
7604
7605 // Also check for cases where the sizeof argument is the exact same
7606 // type as the memory argument, and where it points to a user-defined
7607 // record type.
7608 if (SizeOfArgTy != QualType()) {
7609 if (PointeeTy->isRecordType() &&
7610 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7611 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7612 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7613 << FnName << SizeOfArgTy << ArgIdx
7614 << PointeeTy << Dest->getSourceRange()
7615 << LenExpr->getSourceRange());
7616 break;
7617 }
Nico Weberc5e73862011-06-14 16:14:58 +00007618 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00007619 } else if (DestTy->isArrayType()) {
7620 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00007621 }
Nico Weberc5e73862011-06-14 16:14:58 +00007622
Nico Weberc44b35e2015-03-21 17:37:46 +00007623 if (PointeeTy == QualType())
7624 continue;
Anna Zaks22122702012-01-17 00:37:07 +00007625
Nico Weberc44b35e2015-03-21 17:37:46 +00007626 // Always complain about dynamic classes.
7627 bool IsContained;
7628 if (const CXXRecordDecl *ContainedRD =
7629 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00007630
Nico Weberc44b35e2015-03-21 17:37:46 +00007631 unsigned OperationType = 0;
7632 // "overwritten" if we're warning about the destination for any call
7633 // but memcmp; otherwise a verb appropriate to the call.
7634 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7635 if (BId == Builtin::BImemcpy)
7636 OperationType = 1;
7637 else if(BId == Builtin::BImemmove)
7638 OperationType = 2;
7639 else if (BId == Builtin::BImemcmp)
7640 OperationType = 3;
7641 }
7642
John McCall31168b02011-06-15 23:02:42 +00007643 DiagRuntimeBehavior(
7644 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00007645 PDiag(diag::warn_dyn_class_memaccess)
7646 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7647 << FnName << IsContained << ContainedRD << OperationType
7648 << Call->getCallee()->getSourceRange());
7649 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7650 BId != Builtin::BImemset)
7651 DiagRuntimeBehavior(
7652 Dest->getExprLoc(), Dest,
7653 PDiag(diag::warn_arc_object_memaccess)
7654 << ArgIdx << FnName << PointeeTy
7655 << Call->getCallee()->getSourceRange());
Akira Hatanaka2be04412018-04-17 19:13:41 +00007656 else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
7657 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
7658 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
7659 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7660 PDiag(diag::warn_cstruct_memaccess)
7661 << ArgIdx << FnName << PointeeTy << 0);
7662 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
7663 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
7664 RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
7665 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
7666 PDiag(diag::warn_cstruct_memaccess)
7667 << ArgIdx << FnName << PointeeTy << 1);
7668 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
7669 } else {
7670 continue;
7671 }
7672 } else
Nico Weberc44b35e2015-03-21 17:37:46 +00007673 continue;
7674
7675 DiagRuntimeBehavior(
7676 Dest->getExprLoc(), Dest,
7677 PDiag(diag::note_bad_memaccess_silence)
7678 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7679 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00007680 }
7681}
7682
Ted Kremenek6865f772011-08-18 20:55:45 +00007683// A little helper routine: ignore addition and subtraction of integer literals.
7684// This intentionally does not ignore all integer constant expressions because
7685// we don't want to remove sizeof().
7686static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7687 Ex = Ex->IgnoreParenCasts();
7688
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00007689 while (true) {
Ted Kremenek6865f772011-08-18 20:55:45 +00007690 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7691 if (!BO || !BO->isAdditiveOp())
7692 break;
7693
7694 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7695 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7696
7697 if (isa<IntegerLiteral>(RHS))
7698 Ex = LHS;
7699 else if (isa<IntegerLiteral>(LHS))
7700 Ex = RHS;
7701 else
7702 break;
7703 }
7704
7705 return Ex;
7706}
7707
Anna Zaks13b08572012-08-08 21:42:23 +00007708static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7709 ASTContext &Context) {
7710 // Only handle constant-sized or VLAs, but not flexible members.
7711 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7712 // Only issue the FIXIT for arrays of size > 1.
7713 if (CAT->getSize().getSExtValue() <= 1)
7714 return false;
7715 } else if (!Ty->isVariableArrayType()) {
7716 return false;
7717 }
7718 return true;
7719}
7720
Ted Kremenek6865f772011-08-18 20:55:45 +00007721// Warn if the user has made the 'size' argument to strlcpy or strlcat
7722// be the size of the source, instead of the destination.
7723void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7724 IdentifierInfo *FnName) {
7725
7726 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00007727 unsigned NumArgs = Call->getNumArgs();
7728 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00007729 return;
7730
7731 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7732 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00007733 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00007734
7735 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7736 Call->getLocStart(), Call->getRParenLoc()))
7737 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00007738
7739 // Look for 'strlcpy(dst, x, sizeof(x))'
7740 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7741 CompareWithSrc = Ex;
7742 else {
7743 // Look for 'strlcpy(dst, x, strlen(x))'
7744 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00007745 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7746 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00007747 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7748 }
7749 }
7750
7751 if (!CompareWithSrc)
7752 return;
7753
7754 // Determine if the argument to sizeof/strlen is equal to the source
7755 // argument. In principle there's all kinds of things you could do
7756 // here, for instance creating an == expression and evaluating it with
7757 // EvaluateAsBooleanCondition, but this uses a more direct technique:
7758 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7759 if (!SrcArgDRE)
7760 return;
7761
7762 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7763 if (!CompareWithSrcDRE ||
7764 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7765 return;
7766
7767 const Expr *OriginalSizeArg = Call->getArg(2);
7768 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7769 << OriginalSizeArg->getSourceRange() << FnName;
7770
7771 // Output a FIXIT hint if the destination is an array (rather than a
7772 // pointer to an array). This could be enhanced to handle some
7773 // pointers if we know the actual size, like if DstArg is 'array+2'
7774 // we could say 'sizeof(array)-2'.
7775 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00007776 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00007777 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007778
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007779 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00007780 llvm::raw_svector_ostream OS(sizeString);
7781 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007782 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00007783 OS << ")";
7784
7785 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7786 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7787 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00007788}
7789
Anna Zaks314cd092012-02-01 19:08:57 +00007790/// Check if two expressions refer to the same declaration.
7791static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7792 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7793 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7794 return D1->getDecl() == D2->getDecl();
7795 return false;
7796}
7797
7798static const Expr *getStrlenExprArg(const Expr *E) {
7799 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7800 const FunctionDecl *FD = CE->getDirectCallee();
7801 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00007802 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007803 return CE->getArg(0)->IgnoreParenCasts();
7804 }
Craig Topperc3ec1492014-05-26 06:22:03 +00007805 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00007806}
7807
7808// Warn on anti-patterns as the 'size' argument to strncat.
7809// The correct size argument should look like following:
7810// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7811void Sema::CheckStrncatArguments(const CallExpr *CE,
7812 IdentifierInfo *FnName) {
7813 // Don't crash if the user has the wrong number of arguments.
7814 if (CE->getNumArgs() < 3)
7815 return;
7816 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7817 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7818 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7819
Nico Weber0e6daef2013-12-26 23:38:39 +00007820 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7821 CE->getRParenLoc()))
7822 return;
7823
Anna Zaks314cd092012-02-01 19:08:57 +00007824 // Identify common expressions, which are wrongly used as the size argument
7825 // to strncat and may lead to buffer overflows.
7826 unsigned PatternType = 0;
7827 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7828 // - sizeof(dst)
7829 if (referToTheSameDecl(SizeOfArg, DstArg))
7830 PatternType = 1;
7831 // - sizeof(src)
7832 else if (referToTheSameDecl(SizeOfArg, SrcArg))
7833 PatternType = 2;
7834 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7835 if (BE->getOpcode() == BO_Sub) {
7836 const Expr *L = BE->getLHS()->IgnoreParenCasts();
7837 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7838 // - sizeof(dst) - strlen(dst)
7839 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7840 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7841 PatternType = 1;
7842 // - sizeof(src) - (anything)
7843 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7844 PatternType = 2;
7845 }
7846 }
7847
7848 if (PatternType == 0)
7849 return;
7850
Anna Zaks5069aa32012-02-03 01:27:37 +00007851 // Generate the diagnostic.
7852 SourceLocation SL = LenArg->getLocStart();
7853 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00007854 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00007855
7856 // If the function is defined as a builtin macro, do not show macro expansion.
7857 if (SM.isMacroArgExpansion(SL)) {
7858 SL = SM.getSpellingLoc(SL);
7859 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7860 SM.getSpellingLoc(SR.getEnd()));
7861 }
7862
Anna Zaks13b08572012-08-08 21:42:23 +00007863 // Check if the destination is an array (rather than a pointer to an array).
7864 QualType DstTy = DstArg->getType();
7865 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7866 Context);
7867 if (!isKnownSizeArray) {
7868 if (PatternType == 1)
7869 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7870 else
7871 Diag(SL, diag::warn_strncat_src_size) << SR;
7872 return;
7873 }
7874
Anna Zaks314cd092012-02-01 19:08:57 +00007875 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00007876 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007877 else
Anna Zaks5069aa32012-02-03 01:27:37 +00007878 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00007879
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007880 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00007881 llvm::raw_svector_ostream OS(sizeString);
7882 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007883 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007884 OS << ") - ";
7885 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00007886 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00007887 OS << ") - 1";
7888
Anna Zaks5069aa32012-02-03 01:27:37 +00007889 Diag(SL, diag::note_strncat_wrong_size)
7890 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00007891}
7892
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007893//===--- CHECK: Return Address of Stack Variable --------------------------===//
7894
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007895static const Expr *EvalVal(const Expr *E,
7896 SmallVectorImpl<const DeclRefExpr *> &refVars,
7897 const Decl *ParentDecl);
7898static const Expr *EvalAddr(const Expr *E,
7899 SmallVectorImpl<const DeclRefExpr *> &refVars,
7900 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007901
7902/// CheckReturnStackAddr - Check if a return statement returns the address
7903/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007904static void
7905CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7906 SourceLocation ReturnLoc) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007907 const Expr *stackE = nullptr;
7908 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007909
7910 // Perform checking for returned stack addresses, local blocks,
7911 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00007912 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007913 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007914 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00007915 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007916 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007917 }
7918
Craig Topperc3ec1492014-05-26 06:22:03 +00007919 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007920 return; // Nothing suspicious was found.
7921
Simon Pilgrim750bde62017-03-31 11:00:53 +00007922 // Parameters are initialized in the calling scope, so taking the address
Richard Trieu81b6c562016-08-05 23:24:47 +00007923 // of a parameter reference doesn't need a warning.
7924 for (auto *DRE : refVars)
7925 if (isa<ParmVarDecl>(DRE->getDecl()))
7926 return;
7927
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007928 SourceLocation diagLoc;
7929 SourceRange diagRange;
7930 if (refVars.empty()) {
7931 diagLoc = stackE->getLocStart();
7932 diagRange = stackE->getSourceRange();
7933 } else {
7934 // We followed through a reference variable. 'stackE' contains the
7935 // problematic expression but we will warn at the return statement pointing
7936 // at the reference variable. We will later display the "trail" of
7937 // reference variables using notes.
7938 diagLoc = refVars[0]->getLocStart();
7939 diagRange = refVars[0]->getSourceRange();
7940 }
7941
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007942 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7943 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00007944 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007945 << DR->getDecl()->getDeclName() << diagRange;
7946 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007947 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007948 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007949 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007950 } else { // local temporary.
Richard Trieu81b6c562016-08-05 23:24:47 +00007951 // If there is an LValue->RValue conversion, then the value of the
7952 // reference type is used, not the reference.
7953 if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7954 if (ICE->getCastKind() == CK_LValueToRValue) {
7955 return;
7956 }
7957 }
Craig Topperda7b27f2015-11-17 05:40:09 +00007958 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7959 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007960 }
7961
7962 // Display the "trail" of reference variables that we followed until we
7963 // found the problematic expression using notes.
7964 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007965 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007966 // If this var binds to another reference var, show the range of the next
7967 // var, otherwise the var binds to the problematic expression, in which case
7968 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00007969 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7970 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00007971 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7972 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007973 }
7974}
7975
7976/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7977/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007978/// to a location on the stack, a local block, an address of a label, or a
7979/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007980/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007981/// encounter a subexpression that (1) clearly does not lead to one of the
7982/// above problematic expressions (2) is something we cannot determine leads to
7983/// a problematic expression based on such local checking.
7984///
7985/// Both EvalAddr and EvalVal follow through reference variables to evaluate
7986/// the expression that they point to. Such variables are added to the
7987/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007988///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00007989/// EvalAddr processes expressions that are pointers that are used as
7990/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00007991/// At the base case of the recursion is a check for the above problematic
7992/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00007993///
7994/// This implementation handles:
7995///
7996/// * pointer-to-pointer casts
7997/// * implicit conversions from array references to pointers
7998/// * taking the address of fields
7999/// * arbitrary interplay between "&" and "*" operators
8000/// * pointer arithmetic from an address of a stack variable
8001/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008002static const Expr *EvalAddr(const Expr *E,
8003 SmallVectorImpl<const DeclRefExpr *> &refVars,
8004 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008005 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00008006 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008007
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008008 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00008009 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00008010 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00008011 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00008012 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00008013
Peter Collingbourne91147592011-04-15 00:35:48 +00008014 E = E->IgnoreParens();
8015
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008016 // Our "symbolic interpreter" is just a dispatch off the currently
8017 // viewed AST node. We then recursively traverse the AST by calling
8018 // EvalAddr and EvalVal appropriately.
8019 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008020 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008021 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008022
Richard Smith40f08eb2014-01-30 22:05:38 +00008023 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00008024 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00008025 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00008026
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008027 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008028 // If this is a reference variable, follow through to the expression that
8029 // it points to.
8030 if (V->hasLocalStorage() &&
8031 V->getType()->isReferenceType() && V->hasInit()) {
8032 // Add the reference variable to the "trail".
8033 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008034 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008035 }
8036
Craig Topperc3ec1492014-05-26 06:22:03 +00008037 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008038 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008039
Chris Lattner934edb22007-12-28 05:31:15 +00008040 case Stmt::UnaryOperatorClass: {
8041 // The only unary operator that make sense to handle here
8042 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008043 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008044
John McCalle3027922010-08-25 11:45:40 +00008045 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008046 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008047 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008048 }
Mike Stump11289f42009-09-09 15:08:12 +00008049
Chris Lattner934edb22007-12-28 05:31:15 +00008050 case Stmt::BinaryOperatorClass: {
8051 // Handle pointer arithmetic. All other binary operators are not valid
8052 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008053 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00008054 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00008055
John McCalle3027922010-08-25 11:45:40 +00008056 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00008057 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008058
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008059 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00008060
8061 // Determine which argument is the real pointer base. It could be
8062 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008063 if (!Base->getType()->isPointerType())
8064 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00008065
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008066 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008067 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008068 }
Steve Naroff2752a172008-09-10 19:17:48 +00008069
Chris Lattner934edb22007-12-28 05:31:15 +00008070 // For conditional operators we need to see if either the LHS or RHS are
8071 // valid DeclRefExpr*s. If one of them is valid, we return it.
8072 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008073 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008074
Chris Lattner934edb22007-12-28 05:31:15 +00008075 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008076 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008077 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008078 // In C++, we can have a throw-expression, which has 'void' type.
8079 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008080 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008081 return LHS;
8082 }
Chris Lattner934edb22007-12-28 05:31:15 +00008083
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008084 // In C++, we can have a throw-expression, which has 'void' type.
8085 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00008086 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00008087
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008088 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00008089 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008090
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008091 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00008092 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008093 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00008094 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008095
8096 case Stmt::AddrLabelExprClass:
8097 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00008098
John McCall28fc7092011-11-10 05:35:25 +00008099 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008100 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8101 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00008102
Ted Kremenekc3b4c522008-08-07 00:49:01 +00008103 // For casts, we need to handle conversions from arrays to
8104 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00008105 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00008106 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008107 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00008108 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00008109 case Stmt::CXXStaticCastExprClass:
8110 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00008111 case Stmt::CXXConstCastExprClass:
8112 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008113 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00008114 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00008115 case CK_LValueToRValue:
8116 case CK_NoOp:
8117 case CK_BaseToDerived:
8118 case CK_DerivedToBase:
8119 case CK_UncheckedDerivedToBase:
8120 case CK_Dynamic:
8121 case CK_CPointerToObjCPointerCast:
8122 case CK_BlockPointerToObjCPointerCast:
8123 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008124 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008125
8126 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008127 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00008128
Richard Trieudadefde2014-07-02 04:39:38 +00008129 case CK_BitCast:
8130 if (SubExpr->getType()->isAnyPointerType() ||
8131 SubExpr->getType()->isBlockPointerType() ||
8132 SubExpr->getType()->isObjCQualifiedIdType())
8133 return EvalAddr(SubExpr, refVars, ParentDecl);
8134 else
8135 return nullptr;
8136
Eli Friedman8195ad72012-02-23 23:04:32 +00008137 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008138 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00008139 }
Chris Lattner934edb22007-12-28 05:31:15 +00008140 }
Mike Stump11289f42009-09-09 15:08:12 +00008141
Douglas Gregorfe314812011-06-21 17:03:29 +00008142 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008143 if (const Expr *Result =
8144 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8145 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00008146 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00008147 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008148
Chris Lattner934edb22007-12-28 05:31:15 +00008149 // Everything else: we simply don't reason about them.
8150 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00008151 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00008152 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008153}
Mike Stump11289f42009-09-09 15:08:12 +00008154
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008155/// EvalVal - This function is complements EvalAddr in the mutual recursion.
8156/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008157static const Expr *EvalVal(const Expr *E,
8158 SmallVectorImpl<const DeclRefExpr *> &refVars,
8159 const Decl *ParentDecl) {
8160 do {
8161 // We should only be called for evaluating non-pointer expressions, or
8162 // expressions with a pointer type that are not used as references but
8163 // instead
8164 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00008165
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008166 // Our "symbolic interpreter" is just a dispatch off the currently
8167 // viewed AST node. We then recursively traverse the AST by calling
8168 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00008169
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008170 E = E->IgnoreParens();
8171 switch (E->getStmtClass()) {
8172 case Stmt::ImplicitCastExprClass: {
8173 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8174 if (IE->getValueKind() == VK_LValue) {
8175 E = IE->getSubExpr();
8176 continue;
8177 }
Craig Topperc3ec1492014-05-26 06:22:03 +00008178 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008179 }
Richard Smith40f08eb2014-01-30 22:05:38 +00008180
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008181 case Stmt::ExprWithCleanupsClass:
8182 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8183 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008184
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008185 case Stmt::DeclRefExprClass: {
8186 // When we hit a DeclRefExpr we are looking at code that refers to a
8187 // variable's name. If it's not a reference variable we check if it has
8188 // local storage within the function, and if so, return the expression.
8189 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8190
8191 // If we leave the immediate function, the lifetime isn't about to end.
8192 if (DR->refersToEnclosingVariableOrCapture())
8193 return nullptr;
8194
8195 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8196 // Check if it refers to itself, e.g. "int& i = i;".
8197 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008198 return DR;
8199
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008200 if (V->hasLocalStorage()) {
8201 if (!V->getType()->isReferenceType())
8202 return DR;
8203
8204 // Reference variable, follow through to the expression that
8205 // it points to.
8206 if (V->hasInit()) {
8207 // Add the reference variable to the "trail".
8208 refVars.push_back(DR);
8209 return EvalVal(V->getInit(), refVars, V);
8210 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008211 }
8212 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008213
8214 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00008215 }
Mike Stump11289f42009-09-09 15:08:12 +00008216
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008217 case Stmt::UnaryOperatorClass: {
8218 // The only unary operator that make sense to handle here
8219 // is Deref. All others don't resolve to a "name." This includes
8220 // handling all sorts of rvalues passed to a unary operator.
8221 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00008222
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008223 if (U->getOpcode() == UO_Deref)
8224 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00008225
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008226 return nullptr;
8227 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008228
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008229 case Stmt::ArraySubscriptExprClass: {
8230 // Array subscripts are potential references to data on the stack. We
8231 // retrieve the DeclRefExpr* for the array variable if it indeed
8232 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00008233 const auto *ASE = cast<ArraySubscriptExpr>(E);
8234 if (ASE->isTypeDependent())
8235 return nullptr;
8236 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008237 }
Mike Stump11289f42009-09-09 15:08:12 +00008238
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008239 case Stmt::OMPArraySectionExprClass: {
8240 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8241 ParentDecl);
8242 }
Mike Stump11289f42009-09-09 15:08:12 +00008243
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008244 case Stmt::ConditionalOperatorClass: {
8245 // For conditional operators we need to see if either the LHS or RHS are
8246 // non-NULL Expr's. If one is non-NULL, we return it.
8247 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008248
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008249 // Handle the GNU extension for missing LHS.
8250 if (const Expr *LHSExpr = C->getLHS()) {
8251 // In C++, we can have a throw-expression, which has 'void' type.
8252 if (!LHSExpr->getType()->isVoidType())
8253 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8254 return LHS;
8255 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008256
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008257 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008258 if (C->getRHS()->getType()->isVoidType())
8259 return nullptr;
8260
8261 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00008262 }
8263
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008264 // Accesses to members are potential references to data on the stack.
8265 case Stmt::MemberExprClass: {
8266 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00008267
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008268 // Check for indirect access. We only want direct field accesses.
8269 if (M->isArrow())
8270 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008271
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008272 // Check whether the member type is itself a reference, in which case
8273 // we're not going to refer to the member, but to what the member refers
8274 // to.
8275 if (M->getMemberDecl()->getType()->isReferenceType())
8276 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00008277
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008278 return EvalVal(M->getBase(), refVars, ParentDecl);
8279 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00008280
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008281 case Stmt::MaterializeTemporaryExprClass:
8282 if (const Expr *Result =
8283 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8284 refVars, ParentDecl))
8285 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00008286 return E;
8287
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00008288 default:
8289 // Check that we don't return or take the address of a reference to a
8290 // temporary. This is only useful in C++.
8291 if (!E->isTypeDependent() && E->isRValue())
8292 return E;
8293
8294 // Everything else: we simply don't reason about them.
8295 return nullptr;
8296 }
8297 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00008298}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008299
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008300void
8301Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8302 SourceLocation ReturnLoc,
8303 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00008304 const AttrVec *Attrs,
8305 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008306 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8307
8308 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00008309 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8310 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00008311 CheckNonNullExpr(*this, RetValExp))
8312 Diag(ReturnLoc, diag::warn_null_ret)
8313 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00008314
8315 // C++11 [basic.stc.dynamic.allocation]p4:
8316 // If an allocation function declared with a non-throwing
8317 // exception-specification fails to allocate storage, it shall return
8318 // a null pointer. Any other allocation function that fails to allocate
8319 // storage shall indicate failure only by throwing an exception [...]
8320 if (FD) {
8321 OverloadedOperatorKind Op = FD->getOverloadedOperator();
8322 if (Op == OO_New || Op == OO_Array_New) {
8323 const FunctionProtoType *Proto
8324 = FD->getType()->castAs<FunctionProtoType>();
8325 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8326 CheckNonNullExpr(*this, RetValExp))
8327 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8328 << FD << getLangOpts().CPlusPlus11;
8329 }
8330 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00008331}
8332
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008333//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8334
8335/// Check for comparisons of floating point operands using != and ==.
8336/// Issue a warning if these are no self-comparisons, as they are not likely
8337/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00008338void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00008339 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8340 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008341
8342 // Special case: check for x == x (which is OK).
8343 // Do not emit warnings for such cases.
8344 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8345 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8346 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00008347 return;
Mike Stump11289f42009-09-09 15:08:12 +00008348
Ted Kremenekeda40e22007-11-29 00:59:04 +00008349 // Special case: check for comparisons against literals that can be exactly
8350 // represented by APFloat. In such cases, do not emit a warning. This
8351 // is a heuristic: often comparison against such literals are used to
8352 // detect if a value in a variable has not changed. This clearly can
8353 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00008354 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8355 if (FLL->isExact())
8356 return;
8357 } else
8358 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8359 if (FLR->isExact())
8360 return;
Mike Stump11289f42009-09-09 15:08:12 +00008361
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008362 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00008363 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008364 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008365 return;
Mike Stump11289f42009-09-09 15:08:12 +00008366
David Blaikie1f4ff152012-07-16 20:47:22 +00008367 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00008368 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00008369 return;
Mike Stump11289f42009-09-09 15:08:12 +00008370
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008371 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00008372 Diag(Loc, diag::warn_floatingpoint_eq)
8373 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00008374}
John McCallca01b222010-01-04 23:21:16 +00008375
John McCall70aa5392010-01-06 05:24:50 +00008376//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8377//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00008378
John McCall70aa5392010-01-06 05:24:50 +00008379namespace {
John McCallca01b222010-01-04 23:21:16 +00008380
John McCall70aa5392010-01-06 05:24:50 +00008381/// Structure recording the 'active' range of an integer-valued
8382/// expression.
8383struct IntRange {
8384 /// The number of bits active in the int.
8385 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00008386
John McCall70aa5392010-01-06 05:24:50 +00008387 /// True if the int is known not to have negative values.
8388 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00008389
John McCall70aa5392010-01-06 05:24:50 +00008390 IntRange(unsigned Width, bool NonNegative)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008391 : Width(Width), NonNegative(NonNegative) {}
John McCallca01b222010-01-04 23:21:16 +00008392
John McCall817d4af2010-11-10 23:38:19 +00008393 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00008394 static IntRange forBoolType() {
8395 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00008396 }
8397
John McCall817d4af2010-11-10 23:38:19 +00008398 /// Returns the range of an opaque value of the given integral type.
8399 static IntRange forValueOfType(ASTContext &C, QualType T) {
8400 return forValueOfCanonicalType(C,
8401 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00008402 }
8403
John McCall817d4af2010-11-10 23:38:19 +00008404 /// Returns the range of an opaque value of a canonical integral type.
8405 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00008406 assert(T->isCanonicalUnqualified());
8407
8408 if (const VectorType *VT = dyn_cast<VectorType>(T))
8409 T = VT->getElementType().getTypePtr();
8410 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8411 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008412 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8413 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00008414
Roman Lebedevca1aaac2017-10-21 16:44:03 +00008415 if (!C.getLangOpts().CPlusPlus) {
8416 // For enum types in C code, use the underlying datatype.
8417 if (const EnumType *ET = dyn_cast<EnumType>(T))
8418 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8419 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8420 // For enum types in C++, use the known bit width of the enumerators.
David Majnemer6a426652013-06-07 22:07:20 +00008421 EnumDecl *Enum = ET->getDecl();
Richard Smith371e9e8a2017-12-06 03:00:51 +00008422 // In C++11, enums can have a fixed underlying type. Use this type to
8423 // compute the range.
8424 if (Enum->isFixed()) {
Erich Keane69dbbb02017-09-21 19:58:55 +00008425 return IntRange(C.getIntWidth(QualType(T, 0)),
8426 !ET->isSignedIntegerOrEnumerationType());
Richard Smith371e9e8a2017-12-06 03:00:51 +00008427 }
John McCall18a2c2c2010-11-09 22:22:12 +00008428
David Majnemer6a426652013-06-07 22:07:20 +00008429 unsigned NumPositive = Enum->getNumPositiveBits();
8430 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00008431
David Majnemer6a426652013-06-07 22:07:20 +00008432 if (NumNegative == 0)
8433 return IntRange(NumPositive, true/*NonNegative*/);
8434 else
8435 return IntRange(std::max(NumPositive + 1, NumNegative),
8436 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00008437 }
John McCall70aa5392010-01-06 05:24:50 +00008438
8439 const BuiltinType *BT = cast<BuiltinType>(T);
8440 assert(BT->isInteger());
8441
8442 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8443 }
8444
John McCall817d4af2010-11-10 23:38:19 +00008445 /// Returns the "target" range of a canonical integral type, i.e.
8446 /// the range of values expressible in the type.
8447 ///
8448 /// This matches forValueOfCanonicalType except that enums have the
8449 /// full range of their type, not the range of their enumerators.
8450 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8451 assert(T->isCanonicalUnqualified());
8452
8453 if (const VectorType *VT = dyn_cast<VectorType>(T))
8454 T = VT->getElementType().getTypePtr();
8455 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8456 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00008457 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8458 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008459 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00008460 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00008461
8462 const BuiltinType *BT = cast<BuiltinType>(T);
8463 assert(BT->isInteger());
8464
8465 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8466 }
8467
8468 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00008469 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00008470 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00008471 L.NonNegative && R.NonNegative);
8472 }
8473
John McCall817d4af2010-11-10 23:38:19 +00008474 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00008475 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00008476 return IntRange(std::min(L.Width, R.Width),
8477 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00008478 }
8479};
8480
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008481} // namespace
8482
8483static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8484 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008485 if (value.isSigned() && value.isNegative())
8486 return IntRange(value.getMinSignedBits(), false);
8487
8488 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00008489 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008490
8491 // isNonNegative() just checks the sign bit without considering
8492 // signedness.
8493 return IntRange(value.getActiveBits(), true);
8494}
8495
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008496static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8497 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008498 if (result.isInt())
8499 return GetValueRange(C, result.getInt(), MaxWidth);
8500
8501 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00008502 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8503 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8504 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8505 R = IntRange::join(R, El);
8506 }
John McCall70aa5392010-01-06 05:24:50 +00008507 return R;
8508 }
8509
8510 if (result.isComplexInt()) {
8511 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8512 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8513 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00008514 }
8515
8516 // This can happen with lossless casts to intptr_t of "based" lvalues.
8517 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00008518 // FIXME: The only reason we need to pass the type in here is to get
8519 // the sign right on this one case. It would be nice if APValue
8520 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008521 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00008522 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00008523}
John McCall70aa5392010-01-06 05:24:50 +00008524
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008525static QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008526 QualType Ty = E->getType();
8527 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8528 Ty = AtomicRHS->getValueType();
8529 return Ty;
8530}
8531
John McCall70aa5392010-01-06 05:24:50 +00008532/// Pseudo-evaluate the given integer expression, estimating the
8533/// range of values it might take.
8534///
8535/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008536static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00008537 E = E->IgnoreParens();
8538
8539 // Try a full evaluation first.
8540 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00008541 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00008542 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00008543
8544 // I think we only want to look through implicit casts here; if the
8545 // user has an explicit widening cast, we should treat the value as
8546 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008547 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00008548 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00008549 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8550
Eli Friedmane6d33952013-07-08 20:20:06 +00008551 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00008552
George Burgess IVdf1ed002016-01-13 01:52:39 +00008553 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8554 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00008555
John McCall70aa5392010-01-06 05:24:50 +00008556 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00008557 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00008558 return OutputTypeRange;
8559
8560 IntRange SubRange
8561 = GetExprRange(C, CE->getSubExpr(),
8562 std::min(MaxWidth, OutputTypeRange.Width));
8563
8564 // Bail out if the subexpr's range is as wide as the cast type.
8565 if (SubRange.Width >= OutputTypeRange.Width)
8566 return OutputTypeRange;
8567
8568 // Otherwise, we take the smaller width, and we're non-negative if
8569 // either the output type or the subexpr is.
8570 return IntRange(SubRange.Width,
8571 SubRange.NonNegative || OutputTypeRange.NonNegative);
8572 }
8573
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008574 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008575 // If we can fold the condition, just take that operand.
8576 bool CondResult;
8577 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8578 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8579 : CO->getFalseExpr(),
8580 MaxWidth);
8581
8582 // Otherwise, conservatively merge.
8583 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8584 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8585 return IntRange::join(L, R);
8586 }
8587
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008588 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008589 switch (BO->getOpcode()) {
Richard Smithc70f1d62017-12-14 15:16:18 +00008590 case BO_Cmp:
8591 llvm_unreachable("builtin <=> should have class type");
John McCall70aa5392010-01-06 05:24:50 +00008592
8593 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00008594 case BO_LAnd:
8595 case BO_LOr:
8596 case BO_LT:
8597 case BO_GT:
8598 case BO_LE:
8599 case BO_GE:
8600 case BO_EQ:
8601 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00008602 return IntRange::forBoolType();
8603
John McCallc3688382011-07-13 06:35:24 +00008604 // The type of the assignments is the type of the LHS, so the RHS
8605 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00008606 case BO_MulAssign:
8607 case BO_DivAssign:
8608 case BO_RemAssign:
8609 case BO_AddAssign:
8610 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00008611 case BO_XorAssign:
8612 case BO_OrAssign:
8613 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00008614 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00008615
John McCallc3688382011-07-13 06:35:24 +00008616 // Simple assignments just pass through the RHS, which will have
8617 // been coerced to the LHS type.
8618 case BO_Assign:
8619 // TODO: bitfields?
8620 return GetExprRange(C, BO->getRHS(), MaxWidth);
8621
John McCall70aa5392010-01-06 05:24:50 +00008622 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008623 case BO_PtrMemD:
8624 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00008625 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008626
John McCall2ce81ad2010-01-06 22:07:33 +00008627 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00008628 case BO_And:
8629 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00008630 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8631 GetExprRange(C, BO->getRHS(), MaxWidth));
8632
John McCall70aa5392010-01-06 05:24:50 +00008633 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00008634 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00008635 // ...except that we want to treat '1 << (blah)' as logically
8636 // positive. It's an important idiom.
8637 if (IntegerLiteral *I
8638 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8639 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008640 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00008641 return IntRange(R.Width, /*NonNegative*/ true);
8642 }
8643 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00008644 LLVM_FALLTHROUGH;
John McCall1bff9932010-04-07 01:14:35 +00008645
John McCalle3027922010-08-25 11:45:40 +00008646 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00008647 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008648
John McCall2ce81ad2010-01-06 22:07:33 +00008649 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00008650 case BO_Shr:
8651 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00008652 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8653
8654 // If the shift amount is a positive constant, drop the width by
8655 // that much.
8656 llvm::APSInt shift;
8657 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8658 shift.isNonNegative()) {
8659 unsigned zext = shift.getZExtValue();
8660 if (zext >= L.Width)
8661 L.Width = (L.NonNegative ? 0 : 1);
8662 else
8663 L.Width -= zext;
8664 }
8665
8666 return L;
8667 }
8668
8669 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00008670 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00008671 return GetExprRange(C, BO->getRHS(), MaxWidth);
8672
John McCall2ce81ad2010-01-06 22:07:33 +00008673 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00008674 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00008675 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00008676 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008677 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00008678
John McCall51431812011-07-14 22:39:48 +00008679 // The width of a division result is mostly determined by the size
8680 // of the LHS.
8681 case BO_Div: {
8682 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008683 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008684 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8685
8686 // If the divisor is constant, use that.
8687 llvm::APSInt divisor;
8688 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8689 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8690 if (log2 >= L.Width)
8691 L.Width = (L.NonNegative ? 0 : 1);
8692 else
8693 L.Width = std::min(L.Width - log2, MaxWidth);
8694 return L;
8695 }
8696
8697 // Otherwise, just use the LHS's width.
8698 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8699 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8700 }
8701
8702 // The result of a remainder can't be larger than the result of
8703 // either side.
8704 case BO_Rem: {
8705 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00008706 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00008707 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8708 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8709
8710 IntRange meet = IntRange::meet(L, R);
8711 meet.Width = std::min(meet.Width, MaxWidth);
8712 return meet;
8713 }
8714
8715 // The default behavior is okay for these.
8716 case BO_Mul:
8717 case BO_Add:
8718 case BO_Xor:
8719 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00008720 break;
8721 }
8722
John McCall51431812011-07-14 22:39:48 +00008723 // The default case is to treat the operation as if it were closed
8724 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00008725 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8726 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8727 return IntRange::join(L, R);
8728 }
8729
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008730 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00008731 switch (UO->getOpcode()) {
8732 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00008733 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00008734 return IntRange::forBoolType();
8735
8736 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00008737 case UO_Deref:
8738 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00008739 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008740
8741 default:
8742 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8743 }
8744 }
8745
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008746 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00008747 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8748
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00008749 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00008750 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00008751 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00008752
Eli Friedmane6d33952013-07-08 20:20:06 +00008753 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00008754}
John McCall263a48b2010-01-04 23:31:57 +00008755
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008756static IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00008757 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00008758}
8759
John McCall263a48b2010-01-04 23:31:57 +00008760/// Checks whether the given value, which currently has the given
8761/// source semantics, has the same value when coerced through the
8762/// target semantics.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008763static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8764 const llvm::fltSemantics &Src,
8765 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008766 llvm::APFloat truncated = value;
8767
8768 bool ignored;
8769 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8770 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8771
8772 return truncated.bitwiseIsEqual(value);
8773}
8774
8775/// Checks whether the given value, which currently has the given
8776/// source semantics, has the same value when coerced through the
8777/// target semantics.
8778///
8779/// The value might be a vector of floats (or a complex number).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008780static bool IsSameFloatAfterCast(const APValue &value,
8781 const llvm::fltSemantics &Src,
8782 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00008783 if (value.isFloat())
8784 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8785
8786 if (value.isVector()) {
8787 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8788 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8789 return false;
8790 return true;
8791 }
8792
8793 assert(value.isComplexFloat());
8794 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8795 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8796}
8797
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008798static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008799
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008800static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00008801 // Suppress cases where we are comparing against an enum constant.
8802 if (const DeclRefExpr *DR =
8803 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8804 if (isa<EnumConstantDecl>(DR->getDecl()))
Roman Lebedev6de129e2017-10-15 20:13:17 +00008805 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008806
8807 // Suppress cases where the '0' value is expanded from a macro.
8808 if (E->getLocStart().isMacroID())
Roman Lebedev6de129e2017-10-15 20:13:17 +00008809 return true;
Ted Kremenek6274be42010-09-23 21:43:44 +00008810
Roman Lebedev6de129e2017-10-15 20:13:17 +00008811 return false;
8812}
8813
Richard Smith692f66ab2017-12-06 19:23:19 +00008814static bool isKnownToHaveUnsignedValue(Expr *E) {
8815 return E->getType()->isIntegerType() &&
Roman Lebedev6de129e2017-10-15 20:13:17 +00008816 (!E->getType()->isSignedIntegerType() ||
8817 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8818}
8819
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008820namespace {
Richard Smitha5370fb2017-12-08 22:57:11 +00008821/// The promoted range of values of a type. In general this has the
8822/// following structure:
8823///
8824/// |-----------| . . . |-----------|
8825/// ^ ^ ^ ^
8826/// Min HoleMin HoleMax Max
8827///
8828/// ... where there is only a hole if a signed type is promoted to unsigned
8829/// (in which case Min and Max are the smallest and largest representable
8830/// values).
8831struct PromotedRange {
8832 // Min, or HoleMax if there is a hole.
8833 llvm::APSInt PromotedMin;
8834 // Max, or HoleMin if there is a hole.
8835 llvm::APSInt PromotedMax;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008836
Richard Smitha5370fb2017-12-08 22:57:11 +00008837 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8838 if (R.Width == 0)
8839 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8840 else if (R.Width >= BitWidth && !Unsigned) {
8841 // Promotion made the type *narrower*. This happens when promoting
8842 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8843 // Treat all values of 'signed int' as being in range for now.
8844 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8845 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8846 } else {
8847 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8848 .extOrTrunc(BitWidth);
8849 PromotedMin.setIsUnsigned(Unsigned);
8850
8851 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8852 .extOrTrunc(BitWidth);
8853 PromotedMax.setIsUnsigned(Unsigned);
8854 }
8855 }
8856
8857 // Determine whether this range is contiguous (has no hole).
8858 bool isContiguous() const { return PromotedMin <= PromotedMax; }
8859
8860 // Where a constant value is within the range.
8861 enum ComparisonResult {
8862 LT = 0x1,
8863 LE = 0x2,
8864 GT = 0x4,
8865 GE = 0x8,
8866 EQ = 0x10,
8867 NE = 0x20,
8868 InRangeFlag = 0x40,
8869
8870 Less = LE | LT | NE,
8871 Min = LE | InRangeFlag,
8872 InRange = InRangeFlag,
8873 Max = GE | InRangeFlag,
8874 Greater = GE | GT | NE,
8875
8876 OnlyValue = LE | GE | EQ | InRangeFlag,
8877 InHole = NE
8878 };
8879
8880 ComparisonResult compare(const llvm::APSInt &Value) const {
8881 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8882 Value.isUnsigned() == PromotedMin.isUnsigned());
8883 if (!isContiguous()) {
8884 assert(Value.isUnsigned() && "discontiguous range for signed compare");
8885 if (Value.isMinValue()) return Min;
8886 if (Value.isMaxValue()) return Max;
8887 if (Value >= PromotedMin) return InRange;
8888 if (Value <= PromotedMax) return InRange;
8889 return InHole;
8890 }
8891
8892 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8893 case -1: return Less;
8894 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8895 case 1:
8896 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8897 case -1: return InRange;
8898 case 0: return Max;
8899 case 1: return Greater;
8900 }
8901 }
8902
8903 llvm_unreachable("impossible compare result");
8904 }
8905
Richard Smithc70f1d62017-12-14 15:16:18 +00008906 static llvm::Optional<StringRef>
8907 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8908 if (Op == BO_Cmp) {
8909 ComparisonResult LTFlag = LT, GTFlag = GT;
8910 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8911
8912 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8913 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8914 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8915 return llvm::None;
8916 }
8917
Richard Smitha5370fb2017-12-08 22:57:11 +00008918 ComparisonResult TrueFlag, FalseFlag;
8919 if (Op == BO_EQ) {
8920 TrueFlag = EQ;
8921 FalseFlag = NE;
8922 } else if (Op == BO_NE) {
8923 TrueFlag = NE;
8924 FalseFlag = EQ;
8925 } else {
8926 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8927 TrueFlag = LT;
8928 FalseFlag = GE;
8929 } else {
8930 TrueFlag = GT;
8931 FalseFlag = LE;
8932 }
8933 if (Op == BO_GE || Op == BO_LE)
8934 std::swap(TrueFlag, FalseFlag);
8935 }
8936 if (R & TrueFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00008937 return StringRef("true");
Richard Smitha5370fb2017-12-08 22:57:11 +00008938 if (R & FalseFlag)
Richard Smithc70f1d62017-12-14 15:16:18 +00008939 return StringRef("false");
Richard Smitha5370fb2017-12-08 22:57:11 +00008940 return llvm::None;
8941 }
Roman Lebedev6de129e2017-10-15 20:13:17 +00008942};
John McCallcc7e5bf2010-05-06 08:58:33 +00008943}
8944
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008945static bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00008946 // Strip off implicit integral promotions.
8947 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008948 if (ICE->getCastKind() != CK_IntegralCast &&
8949 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00008950 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00008951 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00008952 }
8953
8954 return E->getType()->isEnumeralType();
8955}
8956
Richard Smith692f66ab2017-12-06 19:23:19 +00008957static int classifyConstantValue(Expr *Constant) {
8958 // The values of this enumeration are used in the diagnostics
8959 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8960 enum ConstantValueKind {
8961 Miscellaneous = 0,
8962 LiteralTrue,
8963 LiteralFalse
8964 };
8965 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8966 return BL->getValue() ? ConstantValueKind::LiteralTrue
8967 : ConstantValueKind::LiteralFalse;
8968 return ConstantValueKind::Miscellaneous;
8969}
8970
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00008971static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8972 Expr *Constant, Expr *Other,
8973 const llvm::APSInt &Value,
8974 bool RhsConstant) {
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008975 if (S.inTemplateInstantiation())
8976 return false;
8977
Richard Smitha5370fb2017-12-08 22:57:11 +00008978 Expr *OriginalOther = Other;
8979
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008980 Constant = Constant->IgnoreParenImpCasts();
8981 Other = Other->IgnoreParenImpCasts();
8982
Richard Smitha5370fb2017-12-08 22:57:11 +00008983 // Suppress warnings on tautological comparisons between values of the same
8984 // enumeration type. There are only two ways we could warn on this:
8985 // - If the constant is outside the range of representable values of
8986 // the enumeration. In such a case, we should warn about the cast
8987 // to enumeration type, not about the comparison.
8988 // - If the constant is the maximum / minimum in-range value. For an
8989 // enumeratin type, such comparisons can be meaningful and useful.
8990 if (Constant->getType()->isEnumeralType() &&
8991 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8992 return false;
8993
Hans Wennborg5bb88e02017-12-08 05:19:12 +00008994 // TODO: Investigate using GetExprRange() to get tighter bounds
8995 // on the bit ranges.
8996 QualType OtherT = Other->getType();
8997 if (const auto *AT = OtherT->getAs<AtomicType>())
8998 OtherT = AT->getValueType();
8999 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9000
9001 // Whether we're treating Other as being a bool because of the form of
9002 // expression despite it having another type (typically 'int' in C).
9003 bool OtherIsBooleanDespiteType =
9004 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9005 if (OtherIsBooleanDespiteType)
9006 OtherRange = IntRange::forBoolType();
9007
Richard Smitha5370fb2017-12-08 22:57:11 +00009008 // Determine the promoted range of the other type and see if a comparison of
9009 // the constant against that range is tautological.
9010 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9011 Value.isUnsigned());
9012 auto Cmp = OtherPromotedRange.compare(Value);
9013 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9014 if (!Result)
9015 return false;
Hans Wennborg5791ce72017-12-08 16:54:08 +00009016
Richard Smitha5370fb2017-12-08 22:57:11 +00009017 // Suppress the diagnostic for an in-range comparison if the constant comes
9018 // from a macro or enumerator. We don't want to diagnose
9019 //
9020 // some_long_value <= INT_MAX
9021 //
9022 // when sizeof(int) == sizeof(long).
9023 bool InRange = Cmp & PromotedRange::InRangeFlag;
9024 if (InRange && IsEnumConstOrFromMacro(S, Constant))
9025 return false;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009026
9027 // If this is a comparison to an enum constant, include that
9028 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00009029 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009030 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
9031 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
9032
Richard Smitha5370fb2017-12-08 22:57:11 +00009033 // Should be enough for uint128 (39 decimal digits)
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009034 SmallString<64> PrettySourceValue;
9035 llvm::raw_svector_ostream OS(PrettySourceValue);
9036 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00009037 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00009038 else
9039 OS << Value;
9040
Richard Smitha5370fb2017-12-08 22:57:11 +00009041 // FIXME: We use a somewhat different formatting for the in-range cases and
9042 // cases involving boolean values for historical reasons. We should pick a
9043 // consistent way of presenting these diagnostics.
9044 if (!InRange || Other->isKnownToHaveBooleanValue()) {
9045 S.DiagRuntimeBehavior(
9046 E->getOperatorLoc(), E,
9047 S.PDiag(!InRange ? diag::warn_out_of_range_compare
9048 : diag::warn_tautological_bool_compare)
9049 << OS.str() << classifyConstantValue(Constant)
9050 << OtherT << OtherIsBooleanDespiteType << *Result
9051 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
9052 } else {
9053 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
9054 ? (HasEnumType(OriginalOther)
9055 ? diag::warn_unsigned_enum_always_true_comparison
9056 : diag::warn_unsigned_always_true_comparison)
9057 : diag::warn_tautological_constant_compare;
Roman Lebedev6de129e2017-10-15 20:13:17 +00009058
Richard Smitha5370fb2017-12-08 22:57:11 +00009059 S.Diag(E->getOperatorLoc(), Diag)
9060 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
9061 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
9062 }
9063
9064 return true;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009065}
9066
John McCallcc7e5bf2010-05-06 08:58:33 +00009067/// Analyze the operands of the given comparison. Implements the
9068/// fallback case from AnalyzeComparison.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009069static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00009070 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9071 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009072}
John McCall263a48b2010-01-04 23:31:57 +00009073
John McCallca01b222010-01-04 23:21:16 +00009074/// \brief Implements -Wsign-compare.
9075///
Richard Trieu82402a02011-09-15 21:56:47 +00009076/// \param E the binary operator to check for warnings
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009077static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009078 // The type the comparison is being performed in.
9079 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00009080
9081 // Only analyze comparison operators where both sides have been converted to
9082 // the same type.
9083 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9084 return AnalyzeImpConvsInComparison(S, E);
9085
9086 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00009087 if (E->isValueDependent())
9088 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009089
Roman Lebedev6de129e2017-10-15 20:13:17 +00009090 Expr *LHS = E->getLHS();
9091 Expr *RHS = E->getRHS();
9092
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009093 if (T->isIntegralType(S.Context)) {
9094 llvm::APSInt RHSValue;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00009095 llvm::APSInt LHSValue;
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009096
Roman Lebedev6de129e2017-10-15 20:13:17 +00009097 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9098 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
Roman Lebedevbd1fc222017-10-12 20:16:51 +00009099
Roman Lebedev6de129e2017-10-15 20:13:17 +00009100 // We don't care about expressions whose result is a constant.
9101 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9102 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6f405db2017-10-12 22:03:20 +00009103
Roman Lebedev6de129e2017-10-15 20:13:17 +00009104 // We only care about expressions where just one side is literal
9105 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9106 // Is the constant on the RHS or LHS?
9107 const bool RhsConstant = IsRHSIntegralLiteral;
9108 Expr *Const = RhsConstant ? RHS : LHS;
9109 Expr *Other = RhsConstant ? LHS : RHS;
9110 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9111
9112 // Check whether an integer constant comparison results in a value
9113 // of 'true' or 'false'.
Roman Lebedev6de129e2017-10-15 20:13:17 +00009114 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9115 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009116 }
9117 }
9118
9119 if (!T->hasUnsignedIntegerRepresentation()) {
9120 // We don't do anything special if this isn't an unsigned integral
9121 // comparison: we're only interested in integral comparisons, and
9122 // signed comparisons only happen in cases we don't care to warn about.
Roman Lebedev6f405db2017-10-12 22:03:20 +00009123 return AnalyzeImpConvsInComparison(S, E);
Roman Lebedev6de129e2017-10-15 20:13:17 +00009124 }
9125
9126 LHS = LHS->IgnoreParenImpCasts();
9127 RHS = RHS->IgnoreParenImpCasts();
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009128
Alex Lorenzb57409f2018-02-07 20:45:39 +00009129 if (!S.getLangOpts().CPlusPlus) {
9130 // Avoid warning about comparison of integers with different signs when
9131 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
9132 // the type of `E`.
9133 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
9134 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9135 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
9136 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
9137 }
9138
John McCallcc7e5bf2010-05-06 08:58:33 +00009139 // Check to see if one of the (unmodified) operands is of different
9140 // signedness.
9141 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00009142 if (LHS->getType()->hasSignedIntegerRepresentation()) {
9143 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00009144 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00009145 signedOperand = LHS;
9146 unsignedOperand = RHS;
9147 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9148 signedOperand = RHS;
9149 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00009150 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00009151 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00009152 }
9153
John McCallcc7e5bf2010-05-06 08:58:33 +00009154 // Otherwise, calculate the effective range of the signed operand.
9155 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00009156
John McCallcc7e5bf2010-05-06 08:58:33 +00009157 // Go ahead and analyze implicit conversions in the operands. Note
9158 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00009159 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9160 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00009161
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009162 // If the signed range is non-negative, -Wsign-compare won't fire.
John McCallcc7e5bf2010-05-06 08:58:33 +00009163 if (signedRange.NonNegative)
Roman Lebedev6aa34aa2017-09-07 22:14:25 +00009164 return;
John McCallca01b222010-01-04 23:21:16 +00009165
9166 // For (in)equality comparisons, if the unsigned operand is a
9167 // constant which cannot collide with a overflowed signed operand,
9168 // then reinterpreting the signed operand as unsigned will not
9169 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00009170 if (E->isEqualityOp()) {
9171 unsigned comparisonWidth = S.Context.getIntWidth(T);
9172 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00009173
John McCallcc7e5bf2010-05-06 08:58:33 +00009174 // We should never be unable to prove that the unsigned operand is
9175 // non-negative.
9176 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9177
9178 if (unsignedRange.Width < comparisonWidth)
9179 return;
9180 }
9181
Douglas Gregorbfb4a212012-05-01 01:53:49 +00009182 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9183 S.PDiag(diag::warn_mixed_sign_comparison)
9184 << LHS->getType() << RHS->getType()
9185 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00009186}
9187
John McCall1f425642010-11-11 03:21:53 +00009188/// Analyzes an attempt to assign the given value to a bitfield.
9189///
9190/// Returns true if there was something fishy about the attempt.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009191static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9192 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00009193 assert(Bitfield->isBitField());
9194 if (Bitfield->isInvalidDecl())
9195 return false;
9196
John McCalldeebbcf2010-11-11 05:33:51 +00009197 // White-list bool bitfields.
Reid Klecknerad425622016-11-16 23:40:00 +00009198 QualType BitfieldType = Bitfield->getType();
9199 if (BitfieldType->isBooleanType())
9200 return false;
9201
9202 if (BitfieldType->isEnumeralType()) {
9203 EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9204 // If the underlying enum type was not explicitly specified as an unsigned
9205 // type and the enum contain only positive values, MSVC++ will cause an
9206 // inconsistency by storing this as a signed type.
9207 if (S.getLangOpts().CPlusPlus11 &&
9208 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9209 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9210 BitfieldEnumDecl->getNumNegativeBits() == 0) {
9211 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9212 << BitfieldEnumDecl->getNameAsString();
9213 }
9214 }
9215
John McCalldeebbcf2010-11-11 05:33:51 +00009216 if (Bitfield->getType()->isBooleanType())
9217 return false;
9218
Douglas Gregor789adec2011-02-04 13:09:01 +00009219 // Ignore value- or type-dependent expressions.
9220 if (Bitfield->getBitWidth()->isValueDependent() ||
9221 Bitfield->getBitWidth()->isTypeDependent() ||
9222 Init->isValueDependent() ||
9223 Init->isTypeDependent())
9224 return false;
9225
John McCall1f425642010-11-11 03:21:53 +00009226 Expr *OriginalInit = Init->IgnoreParenImpCasts();
Reid Kleckner329f24d2017-03-14 18:01:02 +00009227 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00009228
Richard Smith5fab0c92011-12-28 19:48:30 +00009229 llvm::APSInt Value;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009230 if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9231 Expr::SE_AllowSideEffects)) {
9232 // The RHS is not constant. If the RHS has an enum type, make sure the
9233 // bitfield is wide enough to hold all the values of the enum without
9234 // truncation.
9235 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9236 EnumDecl *ED = EnumTy->getDecl();
9237 bool SignedBitfield = BitfieldType->isSignedIntegerType();
9238
9239 // Enum types are implicitly signed on Windows, so check if there are any
9240 // negative enumerators to see if the enum was intended to be signed or
9241 // not.
9242 bool SignedEnum = ED->getNumNegativeBits() > 0;
9243
9244 // Check for surprising sign changes when assigning enum values to a
9245 // bitfield of different signedness. If the bitfield is signed and we
9246 // have exactly the right number of bits to store this unsigned enum,
9247 // suggest changing the enum to an unsigned type. This typically happens
9248 // on Windows where unfixed enums always use an underlying type of 'int'.
9249 unsigned DiagID = 0;
9250 if (SignedEnum && !SignedBitfield) {
9251 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9252 } else if (SignedBitfield && !SignedEnum &&
9253 ED->getNumPositiveBits() == FieldWidth) {
9254 DiagID = diag::warn_signed_bitfield_enum_conversion;
9255 }
9256
9257 if (DiagID) {
9258 S.Diag(InitLoc, DiagID) << Bitfield << ED;
9259 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9260 SourceRange TypeRange =
9261 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9262 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9263 << SignedEnum << TypeRange;
9264 }
9265
9266 // Compute the required bitwidth. If the enum has negative values, we need
9267 // one more bit than the normal number of positive bits to represent the
9268 // sign bit.
9269 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9270 ED->getNumNegativeBits())
9271 : ED->getNumPositiveBits();
9272
9273 // Check the bitwidth.
9274 if (BitsNeeded > FieldWidth) {
9275 Expr *WidthExpr = Bitfield->getBitWidth();
9276 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9277 << Bitfield << ED;
9278 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9279 << BitsNeeded << ED << WidthExpr->getSourceRange();
9280 }
9281 }
9282
John McCall1f425642010-11-11 03:21:53 +00009283 return false;
Reid Kleckner329f24d2017-03-14 18:01:02 +00009284 }
John McCall1f425642010-11-11 03:21:53 +00009285
John McCall1f425642010-11-11 03:21:53 +00009286 unsigned OriginalWidth = Value.getBitWidth();
John McCall1f425642010-11-11 03:21:53 +00009287
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009288 if (!Value.isSigned() || Value.isNegative())
Richard Trieu7561ed02016-08-05 02:39:30 +00009289 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
Daniel Marjamakiee5b5f52016-09-22 14:13:46 +00009290 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9291 OriginalWidth = Value.getMinSignedBits();
Richard Trieu7561ed02016-08-05 02:39:30 +00009292
John McCall1f425642010-11-11 03:21:53 +00009293 if (OriginalWidth <= FieldWidth)
9294 return false;
9295
Eli Friedmanc267a322012-01-26 23:11:39 +00009296 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00009297 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Reid Klecknerad425622016-11-16 23:40:00 +00009298 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00009299
Eli Friedmanc267a322012-01-26 23:11:39 +00009300 // Check whether the stored value is equal to the original value.
9301 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00009302 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00009303 return false;
9304
Eli Friedmanc267a322012-01-26 23:11:39 +00009305 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00009306 // therefore don't strictly fit into a signed bitfield of width 1.
9307 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00009308 return false;
9309
John McCall1f425642010-11-11 03:21:53 +00009310 std::string PrettyValue = Value.toString(10);
9311 std::string PrettyTrunc = TruncatedValue.toString(10);
9312
9313 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9314 << PrettyValue << PrettyTrunc << OriginalInit->getType()
9315 << Init->getSourceRange();
9316
9317 return true;
9318}
9319
John McCalld2a53122010-11-09 23:24:47 +00009320/// Analyze the given simple or compound assignment for warning-worthy
9321/// operations.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009322static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00009323 // Just recurse on the LHS.
9324 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9325
9326 // We want to recurse on the RHS as normal unless we're assigning to
9327 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00009328 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009329 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00009330 E->getOperatorLoc())) {
9331 // Recurse, ignoring any implicit conversions on the RHS.
9332 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9333 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00009334 }
9335 }
9336
9337 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9338}
9339
John McCall263a48b2010-01-04 23:31:57 +00009340/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009341static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9342 SourceLocation CContext, unsigned diag,
9343 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009344 if (pruneControlFlow) {
9345 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9346 S.PDiag(diag)
9347 << SourceType << T << E->getSourceRange()
9348 << SourceRange(CContext));
9349 return;
9350 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00009351 S.Diag(E->getExprLoc(), diag)
9352 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9353}
9354
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009355/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009356static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9357 SourceLocation CContext,
9358 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00009359 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00009360}
9361
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009362/// Analyze the given compound assignment for the possible losing of
9363/// floating-point precision.
9364static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9365 assert(isa<CompoundAssignOperator>(E) &&
9366 "Must be compound assignment operation");
9367 // Recurse on the LHS and RHS in here
9368 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9369 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9370
9371 // Now check the outermost expression
9372 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9373 const auto *RBT = cast<CompoundAssignOperator>(E)
9374 ->getComputationResultType()
9375 ->getAs<BuiltinType>();
9376
9377 // If both source and target are floating points.
9378 if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9379 // Builtin FP kinds are ordered by increasing FP rank.
9380 if (ResultBT->getKind() < RBT->getKind())
9381 // We don't want to warn for system macro.
9382 if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9383 // warn about dropping FP rank.
9384 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9385 E->getOperatorLoc(),
9386 diag::warn_impcast_float_result_precision);
9387}
Richard Trieube234c32016-04-21 21:04:55 +00009388
9389/// Diagnose an implicit cast from a floating point value to an integer value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009390static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9391 SourceLocation CContext) {
Richard Trieube234c32016-04-21 21:04:55 +00009392 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
Richard Smith51ec0cf2017-02-21 01:17:38 +00009393 const bool PruneWarnings = S.inTemplateInstantiation();
Richard Trieube234c32016-04-21 21:04:55 +00009394
9395 Expr *InnerE = E->IgnoreParenImpCasts();
9396 // We also want to warn on, e.g., "int i = -1.234"
9397 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9398 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9399 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9400
9401 const bool IsLiteral =
9402 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9403
9404 llvm::APFloat Value(0.0);
9405 bool IsConstant =
9406 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9407 if (!IsConstant) {
Richard Trieu891f0f12016-04-22 22:14:32 +00009408 return DiagnoseImpCast(S, E, T, CContext,
9409 diag::warn_impcast_float_integer, PruneWarnings);
Richard Trieube234c32016-04-21 21:04:55 +00009410 }
9411
Chandler Carruth016ef402011-04-10 08:36:24 +00009412 bool isExact = false;
Richard Trieube234c32016-04-21 21:04:55 +00009413
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00009414 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9415 T->hasUnsignedIntegerRepresentation());
Richard Trieube234c32016-04-21 21:04:55 +00009416 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9417 &isExact) == llvm::APFloat::opOK &&
Richard Trieu891f0f12016-04-22 22:14:32 +00009418 isExact) {
Richard Trieube234c32016-04-21 21:04:55 +00009419 if (IsLiteral) return;
9420 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9421 PruneWarnings);
9422 }
9423
9424 unsigned DiagID = 0;
Richard Trieu891f0f12016-04-22 22:14:32 +00009425 if (IsLiteral) {
Richard Trieube234c32016-04-21 21:04:55 +00009426 // Warn on floating point literal to integer.
9427 DiagID = diag::warn_impcast_literal_float_to_integer;
9428 } else if (IntegerValue == 0) {
9429 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
9430 return DiagnoseImpCast(S, E, T, CContext,
9431 diag::warn_impcast_float_integer, PruneWarnings);
9432 }
9433 // Warn on non-zero to zero conversion.
9434 DiagID = diag::warn_impcast_float_to_integer_zero;
9435 } else {
9436 if (IntegerValue.isUnsigned()) {
9437 if (!IntegerValue.isMaxValue()) {
9438 return DiagnoseImpCast(S, E, T, CContext,
9439 diag::warn_impcast_float_integer, PruneWarnings);
9440 }
9441 } else { // IntegerValue.isSigned()
9442 if (!IntegerValue.isMaxSignedValue() &&
9443 !IntegerValue.isMinSignedValue()) {
9444 return DiagnoseImpCast(S, E, T, CContext,
9445 diag::warn_impcast_float_integer, PruneWarnings);
9446 }
9447 }
9448 // Warn on evaluatable floating point expression to integer conversion.
9449 DiagID = diag::warn_impcast_float_to_integer;
9450 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009451
Eli Friedman07185912013-08-29 23:44:43 +00009452 // FIXME: Force the precision of the source value down so we don't print
9453 // digits which are usually useless (we don't really care here if we
9454 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
9455 // would automatically print the shortest representation, but it's a bit
9456 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00009457 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00009458 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9459 precision = (precision * 59 + 195) / 196;
9460 Value.toString(PrettySourceValue, precision);
9461
David Blaikie9b88cc02012-05-15 17:18:27 +00009462 SmallString<16> PrettyTargetValue;
Richard Trieube234c32016-04-21 21:04:55 +00009463 if (IsBool)
Aaron Ballmandbc441e2015-12-30 14:26:07 +00009464 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00009465 else
David Blaikie9b88cc02012-05-15 17:18:27 +00009466 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00009467
Richard Trieube234c32016-04-21 21:04:55 +00009468 if (PruneWarnings) {
9469 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9470 S.PDiag(DiagID)
9471 << E->getType() << T.getUnqualifiedType()
9472 << PrettySourceValue << PrettyTargetValue
9473 << E->getSourceRange() << SourceRange(CContext));
9474 } else {
9475 S.Diag(E->getExprLoc(), DiagID)
9476 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9477 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9478 }
Chandler Carruth016ef402011-04-10 08:36:24 +00009479}
9480
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009481static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9482 IntRange Range) {
John McCall18a2c2c2010-11-09 22:22:12 +00009483 if (!Range.Width) return "0";
9484
9485 llvm::APSInt ValueInRange = Value;
9486 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00009487 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00009488 return ValueInRange.toString(10);
9489}
9490
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009491static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009492 if (!isa<ImplicitCastExpr>(Ex))
9493 return false;
9494
9495 Expr *InnerE = Ex->IgnoreParenImpCasts();
9496 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9497 const Type *Source =
9498 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9499 if (Target->isDependentType())
9500 return false;
9501
9502 const BuiltinType *FloatCandidateBT =
9503 dyn_cast<BuiltinType>(ToBool ? Source : Target);
9504 const Type *BoolCandidateType = ToBool ? Target : Source;
9505
9506 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9507 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9508}
9509
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009510static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9511 SourceLocation CC) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009512 unsigned NumArgs = TheCall->getNumArgs();
9513 for (unsigned i = 0; i < NumArgs; ++i) {
9514 Expr *CurrA = TheCall->getArg(i);
9515 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9516 continue;
9517
9518 bool IsSwapped = ((i > 0) &&
9519 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9520 IsSwapped |= ((i < (NumArgs - 1)) &&
9521 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9522 if (IsSwapped) {
9523 // Warn on this floating-point to bool conversion.
9524 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9525 CurrA->getType(), CC,
9526 diag::warn_impcast_floating_point_to_bool);
9527 }
9528 }
9529}
9530
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009531static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9532 SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00009533 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9534 E->getExprLoc()))
9535 return;
9536
Richard Trieu09d6b802016-01-08 23:35:06 +00009537 // Don't warn on functions which have return type nullptr_t.
9538 if (isa<CallExpr>(E))
9539 return;
9540
Richard Trieu5b993502014-10-15 03:42:06 +00009541 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9542 const Expr::NullPointerConstantKind NullKind =
9543 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9544 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9545 return;
9546
9547 // Return if target type is a safe conversion.
9548 if (T->isAnyPointerType() || T->isBlockPointerType() ||
9549 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9550 return;
9551
9552 SourceLocation Loc = E->getSourceRange().getBegin();
9553
Richard Trieu0a5e1662016-02-13 00:58:53 +00009554 // Venture through the macro stacks to get to the source of macro arguments.
9555 // The new location is a better location than the complete location that was
9556 // passed in.
George Karpenkov441e8fd2018-02-09 23:30:07 +00009557 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9558 CC = S.SourceMgr.getTopMacroCallerLoc(CC);
Richard Trieu0a5e1662016-02-13 00:58:53 +00009559
Richard Trieu5b993502014-10-15 03:42:06 +00009560 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00009561 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9562 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9563 Loc, S.SourceMgr, S.getLangOpts());
9564 if (MacroName == "NULL")
9565 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00009566 }
9567
9568 // Only warn if the null and context location are in the same macro expansion.
9569 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9570 return;
9571
9572 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009573 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
Richard Trieu5b993502014-10-15 03:42:06 +00009574 << FixItHint::CreateReplacement(Loc,
9575 S.getFixItZeroLiteralForType(T, Loc));
9576}
9577
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009578static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9579 ObjCArrayLiteral *ArrayLiteral);
9580
9581static void
9582checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9583 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00009584
9585/// Check a single element within a collection literal against the
9586/// target element type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009587static void checkObjCCollectionLiteralElement(Sema &S,
9588 QualType TargetElementType,
9589 Expr *Element,
9590 unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009591 // Skip a bitcast to 'id' or qualified 'id'.
9592 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9593 if (ICE->getCastKind() == CK_BitCast &&
9594 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9595 Element = ICE->getSubExpr();
9596 }
9597
9598 QualType ElementType = Element->getType();
9599 ExprResult ElementResult(Element);
9600 if (ElementType->getAs<ObjCObjectPointerType>() &&
9601 S.CheckSingleAssignmentConstraints(TargetElementType,
9602 ElementResult,
9603 false, false)
9604 != Sema::Compatible) {
9605 S.Diag(Element->getLocStart(),
9606 diag::warn_objc_collection_literal_element)
9607 << ElementType << ElementKind << TargetElementType
9608 << Element->getSourceRange();
9609 }
9610
9611 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9612 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9613 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9614 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9615}
9616
9617/// Check an Objective-C array literal being converted to the given
9618/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009619static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9620 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009621 if (!S.NSArrayDecl)
9622 return;
9623
9624 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9625 if (!TargetObjCPtr)
9626 return;
9627
9628 if (TargetObjCPtr->isUnspecialized() ||
9629 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9630 != S.NSArrayDecl->getCanonicalDecl())
9631 return;
9632
9633 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9634 if (TypeArgs.size() != 1)
9635 return;
9636
9637 QualType TargetElementType = TypeArgs[0];
9638 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9639 checkObjCCollectionLiteralElement(S, TargetElementType,
9640 ArrayLiteral->getElement(I),
9641 0);
9642 }
9643}
9644
9645/// Check an Objective-C dictionary literal being converted to the given
9646/// target type.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009647static void
9648checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9649 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00009650 if (!S.NSDictionaryDecl)
9651 return;
9652
9653 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9654 if (!TargetObjCPtr)
9655 return;
9656
9657 if (TargetObjCPtr->isUnspecialized() ||
9658 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9659 != S.NSDictionaryDecl->getCanonicalDecl())
9660 return;
9661
9662 auto TypeArgs = TargetObjCPtr->getTypeArgs();
9663 if (TypeArgs.size() != 2)
9664 return;
9665
9666 QualType TargetKeyType = TypeArgs[0];
9667 QualType TargetObjectType = TypeArgs[1];
9668 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9669 auto Element = DictionaryLiteral->getKeyValueElement(I);
9670 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9671 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9672 }
9673}
9674
Richard Trieufc404c72016-02-05 23:02:38 +00009675// Helper function to filter out cases for constant width constant conversion.
9676// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009677static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9678 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00009679 // If initializing from a constant, and the constant starts with '0',
9680 // then it is a binary, octal, or hexadecimal. Allow these constants
9681 // to fill all the bits, even if there is a sign change.
9682 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9683 const char FirstLiteralCharacter =
9684 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9685 if (FirstLiteralCharacter == '0')
9686 return false;
9687 }
9688
9689 // If the CC location points to a '{', and the type is char, then assume
9690 // assume it is an array initialization.
9691 if (CC.isValid() && T->isCharType()) {
9692 const char FirstContextCharacter =
9693 S.getSourceManager().getCharacterData(CC)[0];
9694 if (FirstContextCharacter == '{')
9695 return false;
9696 }
9697
9698 return true;
9699}
9700
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009701static void
9702CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9703 bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009704 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00009705
John McCallcc7e5bf2010-05-06 08:58:33 +00009706 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9707 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9708 if (Source == Target) return;
9709 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00009710
Chandler Carruthc22845a2011-07-26 05:40:03 +00009711 // If the conversion context location is invalid don't complain. We also
9712 // don't want to emit a warning if the issue occurs from the expansion of
9713 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9714 // delay this check as long as possible. Once we detect we are in that
9715 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009716 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00009717 return;
9718
Richard Trieu021baa32011-09-23 20:10:00 +00009719 // Diagnose implicit casts to bool.
9720 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9721 if (isa<StringLiteral>(E))
9722 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00009723 // and expressions, for instance, assert(0 && "error here"), are
9724 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00009725 return DiagnoseImpCast(S, E, T, CC,
9726 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00009727 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9728 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9729 // This covers the literal expressions that evaluate to Objective-C
9730 // objects.
9731 return DiagnoseImpCast(S, E, T, CC,
9732 diag::warn_impcast_objective_c_literal_to_bool);
9733 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00009734 if (Source->isPointerType() || Source->canDecayToPointerType()) {
9735 // Warn on pointer to bool conversion that is always true.
9736 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9737 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00009738 }
Richard Trieu021baa32011-09-23 20:10:00 +00009739 }
John McCall263a48b2010-01-04 23:31:57 +00009740
Douglas Gregor5054cb02015-07-07 03:58:22 +00009741 // Check implicit casts from Objective-C collection literals to specialized
9742 // collection types, e.g., NSArray<NSString *> *.
9743 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9744 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9745 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9746 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9747
John McCall263a48b2010-01-04 23:31:57 +00009748 // Strip vector types.
9749 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009750 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009751 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009752 return;
John McCallacf0ee52010-10-08 02:01:28 +00009753 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009754 }
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +00009755
Chris Lattneree7286f2011-06-14 04:51:15 +00009756 // If the vector cast is cast between two vectors of the same size, it is
9757 // a bitcast, not a conversion.
9758 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9759 return;
John McCall263a48b2010-01-04 23:31:57 +00009760
9761 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9762 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9763 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00009764 if (auto VecTy = dyn_cast<VectorType>(Target))
9765 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00009766
9767 // Strip complex types.
9768 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009769 if (!isa<ComplexType>(Target)) {
Tim Northover02416372017-08-08 23:18:05 +00009770 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009771 return;
9772
Tim Northover02416372017-08-08 23:18:05 +00009773 return DiagnoseImpCast(S, E, T, CC,
9774 S.getLangOpts().CPlusPlus
9775 ? diag::err_impcast_complex_scalar
9776 : diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009777 }
John McCall263a48b2010-01-04 23:31:57 +00009778
9779 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9780 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9781 }
9782
9783 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9784 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9785
9786 // If the source is floating point...
9787 if (SourceBT && SourceBT->isFloatingPoint()) {
9788 // ...and the target is floating point...
9789 if (TargetBT && TargetBT->isFloatingPoint()) {
9790 // ...then warn if we're dropping FP rank.
9791
9792 // Builtin FP kinds are ordered by increasing FP rank.
9793 if (SourceBT->getKind() > TargetBT->getKind()) {
9794 // Don't warn about float constants that are precisely
9795 // representable in the target type.
9796 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00009797 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00009798 // Value might be a float, a float vector, or a float complex.
9799 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00009800 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9801 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00009802 return;
9803 }
9804
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009805 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009806 return;
9807
John McCallacf0ee52010-10-08 02:01:28 +00009808 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00009809 }
9810 // ... or possibly if we're increasing rank, too
9811 else if (TargetBT->getKind() > SourceBT->getKind()) {
9812 if (S.SourceMgr.isInSystemMacro(CC))
9813 return;
9814
9815 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00009816 }
9817 return;
9818 }
9819
Richard Trieube234c32016-04-21 21:04:55 +00009820 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00009821 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009822 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009823 return;
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00009824
Richard Trieube234c32016-04-21 21:04:55 +00009825 DiagnoseFloatingImpCast(S, E, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00009826 }
John McCall263a48b2010-01-04 23:31:57 +00009827
Richard Smith54894fd2015-12-30 01:06:52 +00009828 // Detect the case where a call result is converted from floating-point to
9829 // to bool, and the final argument to the call is converted from bool, to
9830 // discover this typo:
9831 //
9832 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
9833 //
9834 // FIXME: This is an incredibly special case; is there some more general
9835 // way to detect this class of misplaced-parentheses bug?
9836 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009837 // Check last argument of function call to see if it is an
9838 // implicit cast from a type matching the type the result
9839 // is being cast to.
9840 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00009841 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009842 Expr *LastA = CEx->getArg(NumArgs - 1);
9843 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00009844 if (isa<ImplicitCastExpr>(LastA) &&
9845 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00009846 // Warn on this floating-point to bool conversion
9847 DiagnoseImpCast(S, E, T, CC,
9848 diag::warn_impcast_floating_point_to_bool);
9849 }
9850 }
9851 }
John McCall263a48b2010-01-04 23:31:57 +00009852 return;
9853 }
9854
Richard Trieu5b993502014-10-15 03:42:06 +00009855 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00009856
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +00009857 S.DiscardMisalignedMemberAddress(Target, E);
9858
David Blaikie9366d2b2012-06-19 21:19:06 +00009859 if (!Source->isIntegerType() || !Target->isIntegerType())
9860 return;
9861
David Blaikie7555b6a2012-05-15 16:56:36 +00009862 // TODO: remove this early return once the false positives for constant->bool
9863 // in templates, macros, etc, are reduced or removed.
9864 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9865 return;
9866
John McCallcc7e5bf2010-05-06 08:58:33 +00009867 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00009868 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00009869
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009870 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00009871 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009872 // TODO: this should happen for bitfield stores, too.
9873 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00009874 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009875 if (S.SourceMgr.isInSystemMacro(CC))
9876 return;
9877
John McCall18a2c2c2010-11-09 22:22:12 +00009878 std::string PrettySourceValue = Value.toString(10);
9879 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009880
Ted Kremenek33ba9952011-10-22 02:37:33 +00009881 S.DiagRuntimeBehavior(E->getExprLoc(), E,
9882 S.PDiag(diag::warn_impcast_integer_precision_constant)
9883 << PrettySourceValue << PrettyTargetValue
9884 << E->getType() << T << E->getSourceRange()
9885 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00009886 return;
9887 }
9888
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00009889 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9890 if (S.SourceMgr.isInSystemMacro(CC))
9891 return;
9892
David Blaikie9455da02012-04-12 22:40:54 +00009893 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00009894 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9895 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00009896 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00009897 }
9898
Richard Trieudcb55572016-01-29 23:51:16 +00009899 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9900 SourceRange.NonNegative && Source->isSignedIntegerType()) {
9901 // Warn when doing a signed to signed conversion, warn if the positive
9902 // source value is exactly the width of the target type, which will
9903 // cause a negative value to be stored.
9904
9905 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00009906 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9907 !S.SourceMgr.isInSystemMacro(CC)) {
9908 if (isSameWidthConstantConversion(S, E, T, CC)) {
9909 std::string PrettySourceValue = Value.toString(10);
9910 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00009911
Richard Trieufc404c72016-02-05 23:02:38 +00009912 S.DiagRuntimeBehavior(
9913 E->getExprLoc(), E,
9914 S.PDiag(diag::warn_impcast_integer_precision_constant)
9915 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9916 << E->getSourceRange() << clang::SourceRange(CC));
9917 return;
Richard Trieudcb55572016-01-29 23:51:16 +00009918 }
9919 }
Richard Trieufc404c72016-02-05 23:02:38 +00009920
Richard Trieudcb55572016-01-29 23:51:16 +00009921 // Fall through for non-constants to give a sign conversion warning.
9922 }
9923
John McCallcc7e5bf2010-05-06 08:58:33 +00009924 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9925 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9926 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009927 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009928 return;
9929
John McCallcc7e5bf2010-05-06 08:58:33 +00009930 unsigned DiagID = diag::warn_impcast_integer_sign;
9931
9932 // Traditionally, gcc has warned about this under -Wsign-compare.
9933 // We also want to warn about it in -Wconversion.
9934 // So if -Wconversion is off, use a completely identical diagnostic
9935 // in the sign-compare group.
9936 // The conditional-checking code will
9937 if (ICContext) {
9938 DiagID = diag::warn_impcast_integer_sign_conditional;
9939 *ICContext = true;
9940 }
9941
John McCallacf0ee52010-10-08 02:01:28 +00009942 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00009943 }
9944
Douglas Gregora78f1932011-02-22 02:45:07 +00009945 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00009946 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9947 // type, to give us better diagnostics.
9948 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00009949 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00009950 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9951 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9952 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9953 SourceType = S.Context.getTypeDeclType(Enum);
9954 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9955 }
9956 }
9957
Douglas Gregora78f1932011-02-22 02:45:07 +00009958 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9959 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00009960 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9961 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009962 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00009963 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009964 return;
9965
Douglas Gregor364f7db2011-03-12 00:14:31 +00009966 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00009967 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00009968 }
John McCall263a48b2010-01-04 23:31:57 +00009969}
9970
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009971static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9972 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009973
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009974static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9975 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00009976 E = E->IgnoreParenImpCasts();
9977
9978 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00009979 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00009980
John McCallacf0ee52010-10-08 02:01:28 +00009981 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00009982 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00009983 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00009984}
9985
Eugene Zelenko11a7ef82017-11-15 22:00:04 +00009986static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9987 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00009988 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00009989
9990 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00009991 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9992 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00009993
9994 // If -Wconversion would have warned about either of the candidates
9995 // for a signedness conversion to the context type...
9996 if (!Suspicious) return;
9997
9998 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009999 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +000010000 return;
10001
John McCallcc7e5bf2010-05-06 08:58:33 +000010002 // ...then check whether it would have warned about either of the
10003 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +000010004 if (E->getType() == T) return;
10005
10006 Suspicious = false;
10007 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
10008 E->getType(), CC, &Suspicious);
10009 if (!Suspicious)
10010 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +000010011 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +000010012}
10013
Richard Trieu65724892014-11-15 06:37:39 +000010014/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10015/// Input argument E is a logical expression.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010016static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +000010017 if (S.getLangOpts().Bool)
10018 return;
10019 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
10020}
10021
John McCallcc7e5bf2010-05-06 08:58:33 +000010022/// AnalyzeImplicitConversions - Find and report any interesting
10023/// implicit conversions in the given expression. There are a couple
10024/// of competing diagnostics here, -Wconversion and -Wsign-compare.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010025static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
10026 SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +000010027 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +000010028 Expr *E = OrigE->IgnoreParenImpCasts();
10029
Douglas Gregor6e8da6a2011-10-10 17:38:18 +000010030 if (E->isTypeDependent() || E->isValueDependent())
10031 return;
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010032
John McCallcc7e5bf2010-05-06 08:58:33 +000010033 // For conditional operators, we analyze the arguments as if they
10034 // were being fed directly into the output.
10035 if (isa<ConditionalOperator>(E)) {
10036 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +000010037 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +000010038 return;
10039 }
10040
Hans Wennborgf4ad2322012-08-28 15:44:30 +000010041 // Check implicit argument conversions for function calls.
10042 if (CallExpr *Call = dyn_cast<CallExpr>(E))
10043 CheckImplicitArgumentConversions(S, Call, CC);
10044
John McCallcc7e5bf2010-05-06 08:58:33 +000010045 // Go ahead and check any implicit conversions we might have skipped.
10046 // The non-canonical typecheck is just an optimization;
10047 // CheckImplicitConversion will filter out dead implicit conversions.
10048 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +000010049 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010050
10051 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +000010052
10053 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
10054 // The bound subexpressions in a PseudoObjectExpr are not reachable
10055 // as transitive children.
10056 // FIXME: Use a more uniform representation for this.
10057 for (auto *SE : POE->semantics())
10058 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
10059 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +000010060 }
Richard Smithd7bed4d2015-11-22 02:57:17 +000010061
John McCallcc7e5bf2010-05-06 08:58:33 +000010062 // Skip past explicit casts.
10063 if (isa<ExplicitCastExpr>(E)) {
10064 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +000010065 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010066 }
10067
John McCalld2a53122010-11-09 23:24:47 +000010068 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10069 // Do a somewhat different check with comparison operators.
10070 if (BO->isComparisonOp())
10071 return AnalyzeComparison(S, BO);
10072
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +000010073 // And with simple assignments.
10074 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +000010075 return AnalyzeAssignment(S, BO);
Andrew V. Tischenko5704dc02018-03-15 10:03:35 +000010076 // And with compound assignments.
10077 if (BO->isAssignmentOp())
10078 return AnalyzeCompoundAssignment(S, BO);
John McCalld2a53122010-11-09 23:24:47 +000010079 }
John McCallcc7e5bf2010-05-06 08:58:33 +000010080
10081 // These break the otherwise-useful invariant below. Fortunately,
10082 // we don't really need to recurse into them, because any internal
10083 // expressions should have been analyzed already when they were
10084 // built into statements.
10085 if (isa<StmtExpr>(E)) return;
10086
10087 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +000010088 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +000010089
10090 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +000010091 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +000010092 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +000010093 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +000010094 for (Stmt *SubStmt : E->children()) {
10095 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +000010096 if (!ChildExpr)
10097 continue;
10098
Richard Trieu955231d2014-01-25 01:10:35 +000010099 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +000010100 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +000010101 // Ignore checking string literals that are in logical and operators.
10102 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +000010103 continue;
10104 AnalyzeImplicitConversions(S, ChildExpr, CC);
10105 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010106
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010107 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +000010108 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
10109 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010110 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +000010111
10112 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10113 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +000010114 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010115 }
Richard Trieu791b86e2014-11-19 06:08:18 +000010116
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +000010117 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10118 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +000010119 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010120}
10121
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000010122/// Diagnose integer type and any valid implicit conversion to it.
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010123static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10124 // Taking into account implicit conversions,
10125 // allow any integer.
10126 if (!E->getType()->isIntegerType()) {
10127 S.Diag(E->getLocStart(),
10128 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10129 return true;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010130 }
Anastasia Stulova0df4ac32016-11-14 17:39:58 +000010131 // Potentially emit standard warnings for implicit conversions if enabled
10132 // using -Wconversion.
10133 CheckImplicitConversion(S, E, IntT, E->getLocStart());
10134 return false;
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000010135}
10136
Richard Trieuc1888e02014-06-28 23:25:37 +000010137// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10138// Returns true when emitting a warning about taking the address of a reference.
10139static bool CheckForReference(Sema &SemaRef, const Expr *E,
Benjamin Kramer7320b992016-06-15 14:20:56 +000010140 const PartialDiagnostic &PD) {
Richard Trieuc1888e02014-06-28 23:25:37 +000010141 E = E->IgnoreParenImpCasts();
10142
10143 const FunctionDecl *FD = nullptr;
10144
10145 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10146 if (!DRE->getDecl()->getType()->isReferenceType())
10147 return false;
10148 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10149 if (!M->getMemberDecl()->getType()->isReferenceType())
10150 return false;
10151 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +000010152 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +000010153 return false;
10154 FD = Call->getDirectCallee();
10155 } else {
10156 return false;
10157 }
10158
10159 SemaRef.Diag(E->getExprLoc(), PD);
10160
10161 // If possible, point to location of function.
10162 if (FD) {
10163 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10164 }
10165
10166 return true;
10167}
10168
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010169// Returns true if the SourceLocation is expanded from any macro body.
10170// Returns false if the SourceLocation is invalid, is from not in a macro
10171// expansion, or is from expanded from a top-level macro argument.
10172static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10173 if (Loc.isInvalid())
10174 return false;
10175
10176 while (Loc.isMacroID()) {
10177 if (SM.isMacroBodyExpansion(Loc))
10178 return true;
10179 Loc = SM.getImmediateMacroCallerLoc(Loc);
10180 }
10181
10182 return false;
10183}
10184
Richard Trieu3bb8b562014-02-26 02:36:06 +000010185/// \brief Diagnose pointers that are always non-null.
10186/// \param E the expression containing the pointer
10187/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10188/// compared to a null pointer
10189/// \param IsEqual True when the comparison is equal to a null pointer
10190/// \param Range Extra SourceRange to highlight in the diagnostic
10191void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10192 Expr::NullPointerConstantKind NullKind,
10193 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +000010194 if (!E)
10195 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010196
10197 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010198 if (E->getExprLoc().isMacroID()) {
10199 const SourceManager &SM = getSourceManager();
10200 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10201 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +000010202 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +000010203 }
Richard Trieu3bb8b562014-02-26 02:36:06 +000010204 E = E->IgnoreImpCasts();
10205
10206 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10207
Richard Trieuf7432752014-06-06 21:39:26 +000010208 if (isa<CXXThisExpr>(E)) {
10209 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10210 : diag::warn_this_bool_conversion;
10211 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10212 return;
10213 }
10214
Richard Trieu3bb8b562014-02-26 02:36:06 +000010215 bool IsAddressOf = false;
10216
10217 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10218 if (UO->getOpcode() != UO_AddrOf)
10219 return;
10220 IsAddressOf = true;
10221 E = UO->getSubExpr();
10222 }
10223
Richard Trieuc1888e02014-06-28 23:25:37 +000010224 if (IsAddressOf) {
10225 unsigned DiagID = IsCompare
10226 ? diag::warn_address_of_reference_null_compare
10227 : diag::warn_address_of_reference_bool_conversion;
10228 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10229 << IsEqual;
10230 if (CheckForReference(*this, E, PD)) {
10231 return;
10232 }
10233 }
10234
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010235 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10236 bool IsParam = isa<NonNullAttr>(NonnullAttr);
George Burgess IV850269a2015-12-08 22:02:00 +000010237 std::string Str;
10238 llvm::raw_string_ostream S(Str);
10239 E->printPretty(S, nullptr, getPrintingPolicy());
10240 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10241 : diag::warn_cast_nonnull_to_bool;
10242 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10243 << E->getSourceRange() << Range << IsEqual;
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010244 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
George Burgess IV850269a2015-12-08 22:02:00 +000010245 };
10246
10247 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10248 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10249 if (auto *Callee = Call->getDirectCallee()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010250 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10251 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010252 return;
10253 }
10254 }
10255 }
10256
Richard Trieu3bb8b562014-02-26 02:36:06 +000010257 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +000010258 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010259 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10260 D = R->getDecl();
10261 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10262 D = M->getMemberDecl();
10263 }
10264
10265 // Weak Decls can be null.
10266 if (!D || D->isWeak())
10267 return;
George Burgess IV850269a2015-12-08 22:02:00 +000010268
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010269 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +000010270 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10271 if (getCurFunction() &&
10272 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010273 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10274 ComplainAboutNonnullParamOrCall(A);
George Burgess IV850269a2015-12-08 22:02:00 +000010275 return;
10276 }
10277
10278 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
David Majnemera3debed2016-06-24 05:33:44 +000010279 auto ParamIter = llvm::find(FD->parameters(), PV);
George Burgess IV850269a2015-12-08 22:02:00 +000010280 assert(ParamIter != FD->param_end());
10281 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10282
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010283 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10284 if (!NonNull->args_size()) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010285 ComplainAboutNonnullParamOrCall(NonNull);
George Burgess IV850269a2015-12-08 22:02:00 +000010286 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010287 }
George Burgess IV850269a2015-12-08 22:02:00 +000010288
Joel E. Denny81508102018-03-13 14:51:22 +000010289 for (const ParamIdx &ArgNo : NonNull->args()) {
10290 if (ArgNo.getASTIndex() == ParamNo) {
Nick Lewyckybc85ec82016-06-15 05:18:39 +000010291 ComplainAboutNonnullParamOrCall(NonNull);
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010292 return;
10293 }
George Burgess IV850269a2015-12-08 22:02:00 +000010294 }
10295 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +000010296 }
10297 }
George Burgess IV850269a2015-12-08 22:02:00 +000010298 }
10299
Richard Trieu3bb8b562014-02-26 02:36:06 +000010300 QualType T = D->getType();
10301 const bool IsArray = T->isArrayType();
10302 const bool IsFunction = T->isFunctionType();
10303
Richard Trieuc1888e02014-06-28 23:25:37 +000010304 // Address of function is used to silence the function warning.
10305 if (IsAddressOf && IsFunction) {
10306 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010307 }
10308
10309 // Found nothing.
10310 if (!IsAddressOf && !IsFunction && !IsArray)
10311 return;
10312
10313 // Pretty print the expression for the diagnostic.
10314 std::string Str;
10315 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +000010316 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +000010317
10318 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10319 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +000010320 enum {
10321 AddressOf,
10322 FunctionPointer,
10323 ArrayPointer
10324 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +000010325 if (IsAddressOf)
10326 DiagType = AddressOf;
10327 else if (IsFunction)
10328 DiagType = FunctionPointer;
10329 else if (IsArray)
10330 DiagType = ArrayPointer;
10331 else
10332 llvm_unreachable("Could not determine diagnostic.");
10333 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10334 << Range << IsEqual;
10335
10336 if (!IsFunction)
10337 return;
10338
10339 // Suggest '&' to silence the function warning.
10340 Diag(E->getExprLoc(), diag::note_function_warning_silence)
10341 << FixItHint::CreateInsertion(E->getLocStart(), "&");
10342
10343 // Check to see if '()' fixit should be emitted.
10344 QualType ReturnType;
10345 UnresolvedSet<4> NonTemplateOverloads;
10346 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10347 if (ReturnType.isNull())
10348 return;
10349
10350 if (IsCompare) {
10351 // There are two cases here. If there is null constant, the only suggest
10352 // for a pointer return type. If the null is 0, then suggest if the return
10353 // type is a pointer or an integer type.
10354 if (!ReturnType->isPointerType()) {
10355 if (NullKind == Expr::NPCK_ZeroExpression ||
10356 NullKind == Expr::NPCK_ZeroLiteral) {
10357 if (!ReturnType->isIntegerType())
10358 return;
10359 } else {
10360 return;
10361 }
10362 }
10363 } else { // !IsCompare
10364 // For function to bool, only suggest if the function pointer has bool
10365 // return type.
10366 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10367 return;
10368 }
10369 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +000010370 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +000010371}
10372
John McCallcc7e5bf2010-05-06 08:58:33 +000010373/// Diagnoses "dangerous" implicit conversions within the given
10374/// expression (which is a full expression). Implements -Wconversion
10375/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +000010376///
10377/// \param CC the "context" location of the implicit conversion, i.e.
10378/// the most location of the syntactic entity requiring the implicit
10379/// conversion
10380void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +000010381 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +000010382 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +000010383 return;
10384
10385 // Don't diagnose for value- or type-dependent expressions.
10386 if (E->isTypeDependent() || E->isValueDependent())
10387 return;
10388
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000010389 // Check for array bounds violations in cases where the check isn't triggered
10390 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10391 // ArraySubscriptExpr is on the RHS of a variable initialization.
10392 CheckArrayAccess(E);
10393
John McCallacf0ee52010-10-08 02:01:28 +000010394 // This is not the right CC for (e.g.) a variable initialization.
10395 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +000010396}
10397
Richard Trieu65724892014-11-15 06:37:39 +000010398/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10399/// Input argument E is a logical expression.
10400void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10401 ::CheckBoolLikeConversion(*this, E, CC);
10402}
10403
Richard Smith9f7df0c2017-06-26 23:19:32 +000010404/// Diagnose when expression is an integer constant expression and its evaluation
10405/// results in integer overflow
10406void Sema::CheckForIntOverflow (Expr *E) {
10407 // Use a work list to deal with nested struct initializers.
10408 SmallVector<Expr *, 2> Exprs(1, E);
10409
10410 do {
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010411 Expr *OriginalE = Exprs.pop_back_val();
10412 Expr *E = OriginalE->IgnoreParenCasts();
Richard Smith9f7df0c2017-06-26 23:19:32 +000010413
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010414 if (isa<BinaryOperator>(E)) {
10415 E->EvaluateForOverflow(Context);
Richard Smith9f7df0c2017-06-26 23:19:32 +000010416 continue;
10417 }
10418
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010419 if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
Richard Smith9f7df0c2017-06-26 23:19:32 +000010420 Exprs.append(InitList->inits().begin(), InitList->inits().end());
Volodymyr Sapsaica7902f2018-03-27 21:29:05 +000010421 else if (isa<ObjCBoxedExpr>(OriginalE))
10422 E->EvaluateForOverflow(Context);
10423 else if (auto Call = dyn_cast<CallExpr>(E))
10424 Exprs.append(Call->arg_begin(), Call->arg_end());
10425 else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10426 Exprs.append(Message->arg_begin(), Message->arg_end());
Richard Smith9f7df0c2017-06-26 23:19:32 +000010427 } while (!Exprs.empty());
10428}
10429
Richard Smithc406cb72013-01-17 01:17:56 +000010430namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010431
Richard Smithc406cb72013-01-17 01:17:56 +000010432/// \brief Visitor for expressions which looks for unsequenced operations on the
10433/// same object.
10434class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010435 using Base = EvaluatedExprVisitor<SequenceChecker>;
Richard Smithe3dbfe02013-06-30 10:40:20 +000010436
Richard Smithc406cb72013-01-17 01:17:56 +000010437 /// \brief A tree of sequenced regions within an expression. Two regions are
10438 /// unsequenced if one is an ancestor or a descendent of the other. When we
10439 /// finish processing an expression with sequencing, such as a comma
10440 /// expression, we fold its tree nodes into its parent, since they are
10441 /// unsequenced with respect to nodes we will visit later.
10442 class SequenceTree {
10443 struct Value {
10444 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10445 unsigned Parent : 31;
Aaron Ballmanaffa1c32016-07-06 18:33:01 +000010446 unsigned Merged : 1;
Richard Smithc406cb72013-01-17 01:17:56 +000010447 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010448 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +000010449
10450 public:
10451 /// \brief A region within an expression which may be sequenced with respect
10452 /// to some other region.
10453 class Seq {
Richard Smithc406cb72013-01-17 01:17:56 +000010454 friend class SequenceTree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010455
10456 unsigned Index = 0;
10457
10458 explicit Seq(unsigned N) : Index(N) {}
10459
Richard Smithc406cb72013-01-17 01:17:56 +000010460 public:
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010461 Seq() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010462 };
10463
10464 SequenceTree() { Values.push_back(Value(0)); }
10465 Seq root() const { return Seq(0); }
10466
10467 /// \brief Create a new sequence of operations, which is an unsequenced
10468 /// subset of \p Parent. This sequence of operations is sequenced with
10469 /// respect to other children of \p Parent.
10470 Seq allocate(Seq Parent) {
10471 Values.push_back(Value(Parent.Index));
10472 return Seq(Values.size() - 1);
10473 }
10474
10475 /// \brief Merge a sequence of operations into its parent.
10476 void merge(Seq S) {
10477 Values[S.Index].Merged = true;
10478 }
10479
10480 /// \brief Determine whether two operations are unsequenced. This operation
10481 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10482 /// should have been merged into its parent as appropriate.
10483 bool isUnsequenced(Seq Cur, Seq Old) {
10484 unsigned C = representative(Cur.Index);
10485 unsigned Target = representative(Old.Index);
10486 while (C >= Target) {
10487 if (C == Target)
10488 return true;
10489 C = Values[C].Parent;
10490 }
10491 return false;
10492 }
10493
10494 private:
10495 /// \brief Pick a representative for a sequence.
10496 unsigned representative(unsigned K) {
10497 if (Values[K].Merged)
10498 // Perform path compression as we go.
10499 return Values[K].Parent = representative(Values[K].Parent);
10500 return K;
10501 }
10502 };
10503
10504 /// An object for which we can track unsequenced uses.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010505 using Object = NamedDecl *;
Richard Smithc406cb72013-01-17 01:17:56 +000010506
10507 /// Different flavors of object usage which we track. We only track the
10508 /// least-sequenced usage of each kind.
10509 enum UsageKind {
10510 /// A read of an object. Multiple unsequenced reads are OK.
10511 UK_Use,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010512
Richard Smithc406cb72013-01-17 01:17:56 +000010513 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +000010514 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +000010515 UK_ModAsValue,
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010516
Richard Smithc406cb72013-01-17 01:17:56 +000010517 /// A modification of an object which is not sequenced before the value
10518 /// computation of the expression, such as n++.
10519 UK_ModAsSideEffect,
10520
10521 UK_Count = UK_ModAsSideEffect + 1
10522 };
10523
10524 struct Usage {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010525 Expr *Use = nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010526 SequenceTree::Seq Seq;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010527
10528 Usage() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010529 };
10530
10531 struct UsageInfo {
Richard Smithc406cb72013-01-17 01:17:56 +000010532 Usage Uses[UK_Count];
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010533
Richard Smithc406cb72013-01-17 01:17:56 +000010534 /// Have we issued a diagnostic for this variable already?
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010535 bool Diagnosed = false;
10536
10537 UsageInfo() = default;
Richard Smithc406cb72013-01-17 01:17:56 +000010538 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010539 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
Richard Smithc406cb72013-01-17 01:17:56 +000010540
10541 Sema &SemaRef;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010542
Richard Smithc406cb72013-01-17 01:17:56 +000010543 /// Sequenced regions within the expression.
10544 SequenceTree Tree;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010545
Richard Smithc406cb72013-01-17 01:17:56 +000010546 /// Declaration modifications and references which we have seen.
10547 UsageInfoMap UsageMap;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010548
Richard Smithc406cb72013-01-17 01:17:56 +000010549 /// The region we are currently within.
10550 SequenceTree::Seq Region;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010551
Richard Smithc406cb72013-01-17 01:17:56 +000010552 /// Filled in with declarations which were modified as a side-effect
10553 /// (that is, post-increment operations).
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010554 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10555
Richard Smithd33f5202013-01-17 23:18:09 +000010556 /// Expressions to check later. We defer checking these to reduce
10557 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010558 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +000010559
10560 /// RAII object wrapping the visitation of a sequenced subexpression of an
10561 /// expression. At the end of this process, the side-effects of the evaluation
10562 /// become sequenced with respect to the value computation of the result, so
10563 /// we downgrade any UK_ModAsSideEffect within the evaluation to
10564 /// UK_ModAsValue.
10565 struct SequencedSubexpression {
10566 SequencedSubexpression(SequenceChecker &Self)
10567 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10568 Self.ModAsSideEffect = &ModAsSideEffect;
10569 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010570
Richard Smithc406cb72013-01-17 01:17:56 +000010571 ~SequencedSubexpression() {
David Majnemerf7e36092016-06-23 00:15:04 +000010572 for (auto &M : llvm::reverse(ModAsSideEffect)) {
10573 UsageInfo &U = Self.UsageMap[M.first];
Richard Smithe8efd992014-12-03 01:05:50 +000010574 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
David Majnemerf7e36092016-06-23 00:15:04 +000010575 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10576 SideEffectUsage = M.second;
Richard Smithc406cb72013-01-17 01:17:56 +000010577 }
10578 Self.ModAsSideEffect = OldModAsSideEffect;
10579 }
10580
10581 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010582 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010583 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +000010584 };
10585
Richard Smith40238f02013-06-20 22:21:56 +000010586 /// RAII object wrapping the visitation of a subexpression which we might
10587 /// choose to evaluate as a constant. If any subexpression is evaluated and
10588 /// found to be non-constant, this allows us to suppress the evaluation of
10589 /// the outer expression.
10590 class EvaluationTracker {
10591 public:
10592 EvaluationTracker(SequenceChecker &Self)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010593 : Self(Self), Prev(Self.EvalTracker) {
Richard Smith40238f02013-06-20 22:21:56 +000010594 Self.EvalTracker = this;
10595 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010596
Richard Smith40238f02013-06-20 22:21:56 +000010597 ~EvaluationTracker() {
10598 Self.EvalTracker = Prev;
10599 if (Prev)
10600 Prev->EvalOK &= EvalOK;
10601 }
10602
10603 bool evaluate(const Expr *E, bool &Result) {
10604 if (!EvalOK || E->isValueDependent())
10605 return false;
10606 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10607 return EvalOK;
10608 }
10609
10610 private:
10611 SequenceChecker &Self;
10612 EvaluationTracker *Prev;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010613 bool EvalOK = true;
10614 } *EvalTracker = nullptr;
Richard Smith40238f02013-06-20 22:21:56 +000010615
Richard Smithc406cb72013-01-17 01:17:56 +000010616 /// \brief Find the object which is produced by the specified expression,
10617 /// if any.
10618 Object getObject(Expr *E, bool Mod) const {
10619 E = E->IgnoreParenCasts();
10620 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10621 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10622 return getObject(UO->getSubExpr(), Mod);
10623 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10624 if (BO->getOpcode() == BO_Comma)
10625 return getObject(BO->getRHS(), Mod);
10626 if (Mod && BO->isAssignmentOp())
10627 return getObject(BO->getLHS(), Mod);
10628 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10629 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10630 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10631 return ME->getMemberDecl();
10632 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10633 // FIXME: If this is a reference, map through to its value.
10634 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +000010635 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +000010636 }
10637
10638 /// \brief Note that an object was modified or used by an expression.
10639 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10640 Usage &U = UI.Uses[UK];
10641 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10642 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10643 ModAsSideEffect->push_back(std::make_pair(O, U));
10644 U.Use = Ref;
10645 U.Seq = Region;
10646 }
10647 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010648
Richard Smithc406cb72013-01-17 01:17:56 +000010649 /// \brief Check whether a modification or use conflicts with a prior usage.
10650 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10651 bool IsModMod) {
10652 if (UI.Diagnosed)
10653 return;
10654
10655 const Usage &U = UI.Uses[OtherKind];
10656 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10657 return;
10658
10659 Expr *Mod = U.Use;
10660 Expr *ModOrUse = Ref;
10661 if (OtherKind == UK_Use)
10662 std::swap(Mod, ModOrUse);
10663
10664 SemaRef.Diag(Mod->getExprLoc(),
10665 IsModMod ? diag::warn_unsequenced_mod_mod
10666 : diag::warn_unsequenced_mod_use)
10667 << O << SourceRange(ModOrUse->getExprLoc());
10668 UI.Diagnosed = true;
10669 }
10670
10671 void notePreUse(Object O, Expr *Use) {
10672 UsageInfo &U = UsageMap[O];
10673 // Uses conflict with other modifications.
10674 checkUsage(O, U, Use, UK_ModAsValue, false);
10675 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010676
Richard Smithc406cb72013-01-17 01:17:56 +000010677 void notePostUse(Object O, Expr *Use) {
10678 UsageInfo &U = UsageMap[O];
10679 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10680 addUsage(U, O, Use, UK_Use);
10681 }
10682
10683 void notePreMod(Object O, Expr *Mod) {
10684 UsageInfo &U = UsageMap[O];
10685 // Modifications conflict with other modifications and with uses.
10686 checkUsage(O, U, Mod, UK_ModAsValue, true);
10687 checkUsage(O, U, Mod, UK_Use, false);
10688 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010689
Richard Smithc406cb72013-01-17 01:17:56 +000010690 void notePostMod(Object O, Expr *Use, UsageKind UK) {
10691 UsageInfo &U = UsageMap[O];
10692 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10693 addUsage(U, O, Use, UK);
10694 }
10695
10696public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010697 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010698 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
Richard Smithc406cb72013-01-17 01:17:56 +000010699 Visit(E);
10700 }
10701
10702 void VisitStmt(Stmt *S) {
10703 // Skip all statements which aren't expressions for now.
10704 }
10705
10706 void VisitExpr(Expr *E) {
10707 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +000010708 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +000010709 }
10710
10711 void VisitCastExpr(CastExpr *E) {
10712 Object O = Object();
10713 if (E->getCastKind() == CK_LValueToRValue)
10714 O = getObject(E->getSubExpr(), false);
10715
10716 if (O)
10717 notePreUse(O, E);
10718 VisitExpr(E);
10719 if (O)
10720 notePostUse(O, E);
10721 }
10722
10723 void VisitBinComma(BinaryOperator *BO) {
10724 // C++11 [expr.comma]p1:
10725 // Every value computation and side effect associated with the left
10726 // expression is sequenced before every value computation and side
10727 // effect associated with the right expression.
10728 SequenceTree::Seq LHS = Tree.allocate(Region);
10729 SequenceTree::Seq RHS = Tree.allocate(Region);
10730 SequenceTree::Seq OldRegion = Region;
10731
10732 {
10733 SequencedSubexpression SeqLHS(*this);
10734 Region = LHS;
10735 Visit(BO->getLHS());
10736 }
10737
10738 Region = RHS;
10739 Visit(BO->getRHS());
10740
10741 Region = OldRegion;
10742
10743 // Forget that LHS and RHS are sequenced. They are both unsequenced
10744 // with respect to other stuff.
10745 Tree.merge(LHS);
10746 Tree.merge(RHS);
10747 }
10748
10749 void VisitBinAssign(BinaryOperator *BO) {
10750 // The modification is sequenced after the value computation of the LHS
10751 // and RHS, so check it before inspecting the operands and update the
10752 // map afterwards.
10753 Object O = getObject(BO->getLHS(), true);
10754 if (!O)
10755 return VisitExpr(BO);
10756
10757 notePreMod(O, BO);
10758
10759 // C++11 [expr.ass]p7:
10760 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10761 // only once.
10762 //
10763 // Therefore, for a compound assignment operator, O is considered used
10764 // everywhere except within the evaluation of E1 itself.
10765 if (isa<CompoundAssignOperator>(BO))
10766 notePreUse(O, BO);
10767
10768 Visit(BO->getLHS());
10769
10770 if (isa<CompoundAssignOperator>(BO))
10771 notePostUse(O, BO);
10772
10773 Visit(BO->getRHS());
10774
Richard Smith83e37bee2013-06-26 23:16:51 +000010775 // C++11 [expr.ass]p1:
10776 // the assignment is sequenced [...] before the value computation of the
10777 // assignment expression.
10778 // C11 6.5.16/3 has no such rule.
10779 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10780 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010781 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010782
Richard Smithc406cb72013-01-17 01:17:56 +000010783 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10784 VisitBinAssign(CAO);
10785 }
10786
10787 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10788 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10789 void VisitUnaryPreIncDec(UnaryOperator *UO) {
10790 Object O = getObject(UO->getSubExpr(), true);
10791 if (!O)
10792 return VisitExpr(UO);
10793
10794 notePreMod(O, UO);
10795 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +000010796 // C++11 [expr.pre.incr]p1:
10797 // the expression ++x is equivalent to x+=1
10798 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10799 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +000010800 }
10801
10802 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10803 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10804 void VisitUnaryPostIncDec(UnaryOperator *UO) {
10805 Object O = getObject(UO->getSubExpr(), true);
10806 if (!O)
10807 return VisitExpr(UO);
10808
10809 notePreMod(O, UO);
10810 Visit(UO->getSubExpr());
10811 notePostMod(O, UO, UK_ModAsSideEffect);
10812 }
10813
10814 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10815 void VisitBinLOr(BinaryOperator *BO) {
10816 // The side-effects of the LHS of an '&&' are sequenced before the
10817 // value computation of the RHS, and hence before the value computation
10818 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10819 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +000010820 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010821 {
10822 SequencedSubexpression Sequenced(*this);
10823 Visit(BO->getLHS());
10824 }
10825
10826 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010827 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010828 if (!Result)
10829 Visit(BO->getRHS());
10830 } else {
10831 // Check for unsequenced operations in the RHS, treating it as an
10832 // entirely separate evaluation.
10833 //
10834 // FIXME: If there are operations in the RHS which are unsequenced
10835 // with respect to operations outside the RHS, and those operations
10836 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +000010837 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010838 }
Richard Smithc406cb72013-01-17 01:17:56 +000010839 }
10840 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +000010841 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +000010842 {
10843 SequencedSubexpression Sequenced(*this);
10844 Visit(BO->getLHS());
10845 }
10846
10847 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010848 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +000010849 if (Result)
10850 Visit(BO->getRHS());
10851 } else {
Richard Smithd33f5202013-01-17 23:18:09 +000010852 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +000010853 }
Richard Smithc406cb72013-01-17 01:17:56 +000010854 }
10855
10856 // Only visit the condition, unless we can be sure which subexpression will
10857 // be chosen.
10858 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +000010859 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +000010860 {
10861 SequencedSubexpression Sequenced(*this);
10862 Visit(CO->getCond());
10863 }
Richard Smithc406cb72013-01-17 01:17:56 +000010864
10865 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +000010866 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +000010867 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010868 else {
Richard Smithd33f5202013-01-17 23:18:09 +000010869 WorkList.push_back(CO->getTrueExpr());
10870 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +000010871 }
Richard Smithc406cb72013-01-17 01:17:56 +000010872 }
10873
Richard Smithe3dbfe02013-06-30 10:40:20 +000010874 void VisitCallExpr(CallExpr *CE) {
10875 // C++11 [intro.execution]p15:
10876 // When calling a function [...], every value computation and side effect
10877 // associated with any argument expression, or with the postfix expression
10878 // designating the called function, is sequenced before execution of every
10879 // expression or statement in the body of the function [and thus before
10880 // the value computation of its result].
10881 SequencedSubexpression Sequenced(*this);
10882 Base::VisitCallExpr(CE);
10883
10884 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10885 }
10886
Richard Smithc406cb72013-01-17 01:17:56 +000010887 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +000010888 // This is a call, so all subexpressions are sequenced before the result.
10889 SequencedSubexpression Sequenced(*this);
10890
Richard Smithc406cb72013-01-17 01:17:56 +000010891 if (!CCE->isListInitialization())
10892 return VisitExpr(CCE);
10893
10894 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010895 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010896 SequenceTree::Seq Parent = Region;
10897 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10898 E = CCE->arg_end();
10899 I != E; ++I) {
10900 Region = Tree.allocate(Parent);
10901 Elts.push_back(Region);
10902 Visit(*I);
10903 }
10904
10905 // Forget that the initializers are sequenced.
10906 Region = Parent;
10907 for (unsigned I = 0; I < Elts.size(); ++I)
10908 Tree.merge(Elts[I]);
10909 }
10910
10911 void VisitInitListExpr(InitListExpr *ILE) {
10912 if (!SemaRef.getLangOpts().CPlusPlus11)
10913 return VisitExpr(ILE);
10914
10915 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010916 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +000010917 SequenceTree::Seq Parent = Region;
10918 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10919 Expr *E = ILE->getInit(I);
10920 if (!E) continue;
10921 Region = Tree.allocate(Parent);
10922 Elts.push_back(Region);
10923 Visit(E);
10924 }
10925
10926 // Forget that the initializers are sequenced.
10927 Region = Parent;
10928 for (unsigned I = 0; I < Elts.size(); ++I)
10929 Tree.merge(Elts[I]);
10930 }
10931};
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000010932
10933} // namespace
Richard Smithc406cb72013-01-17 01:17:56 +000010934
10935void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +000010936 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +000010937 WorkList.push_back(E);
10938 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +000010939 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +000010940 SequenceChecker(*this, Item, WorkList);
10941 }
Richard Smithc406cb72013-01-17 01:17:56 +000010942}
10943
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010944void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10945 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +000010946 CheckImplicitConversions(E, CheckLoc);
Richard Trieu71d74d42016-08-05 21:02:34 +000010947 if (!E->isInstantiationDependent())
10948 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010949 if (!IsConstexpr && !E->isValueDependent())
Richard Smith9f7df0c2017-06-26 23:19:32 +000010950 CheckForIntOverflow(E);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000010951 DiagnoseMisalignedMembers();
Richard Smithc406cb72013-01-17 01:17:56 +000010952}
10953
John McCall1f425642010-11-11 03:21:53 +000010954void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10955 FieldDecl *BitField,
10956 Expr *Init) {
10957 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10958}
10959
David Majnemer61a5bbf2015-04-07 22:08:51 +000010960static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10961 SourceLocation Loc) {
10962 if (!PType->isVariablyModifiedType())
10963 return;
10964 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10965 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10966 return;
10967 }
David Majnemerdf8f73f2015-04-09 19:53:25 +000010968 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10969 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10970 return;
10971 }
David Majnemer61a5bbf2015-04-07 22:08:51 +000010972 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10973 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10974 return;
10975 }
10976
10977 const ArrayType *AT = S.Context.getAsArrayType(PType);
10978 if (!AT)
10979 return;
10980
10981 if (AT->getSizeModifier() != ArrayType::Star) {
10982 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10983 return;
10984 }
10985
10986 S.Diag(Loc, diag::err_array_star_in_function_definition);
10987}
10988
Mike Stump0c2ec772010-01-21 03:59:47 +000010989/// CheckParmsForFunctionDef - Check that the parameters of the given
10990/// function are appropriate for the definition of a function. This
10991/// takes care of any checks that cannot be performed on the
10992/// declaration itself, e.g., that the types of each of the function
10993/// parameters are complete.
David Majnemer59f77922016-06-24 04:05:48 +000010994bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
Douglas Gregorb524d902010-11-01 18:37:59 +000010995 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010996 bool HasInvalidParm = false;
David Majnemer59f77922016-06-24 04:05:48 +000010997 for (ParmVarDecl *Param : Parameters) {
Mike Stump0c2ec772010-01-21 03:59:47 +000010998 // C99 6.7.5.3p4: the parameters in a parameter type list in a
10999 // function declarator that is part of a function definition of
11000 // that function shall not have incomplete type.
11001 //
11002 // This is also C++ [dcl.fct]p6.
11003 if (!Param->isInvalidDecl() &&
11004 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011005 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +000011006 Param->setInvalidDecl();
11007 HasInvalidParm = true;
11008 }
11009
11010 // C99 6.9.1p5: If the declarator includes a parameter type list, the
11011 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +000011012 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +000011013 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +000011014 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +000011015 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +000011016 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +000011017
11018 // C99 6.7.5.3p12:
11019 // If the function declarator is not part of a definition of that
11020 // function, parameters may have incomplete type and may use the [*]
11021 // notation in their sequences of declarator specifiers to specify
11022 // variable length array types.
11023 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +000011024 // FIXME: This diagnostic should point the '[*]' if source-location
11025 // information is added for it.
11026 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011027
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011028 // If the parameter is a c++ class type and it has to be destructed in the
11029 // callee function, declare the destructor so that it can be called by the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +000011030 // callee function. Do not perform any direct access check on the dtor here.
Akira Hatanaka02914dc2018-02-05 20:23:22 +000011031 if (!Param->isInvalidDecl()) {
11032 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
11033 if (!ClassDecl->isInvalidDecl() &&
11034 !ClassDecl->hasIrrelevantDestructor() &&
11035 !ClassDecl->isDependentContext() &&
11036 Context.isParamDestroyedInCallee(Param->getType())) {
11037 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11038 MarkFunctionReferenced(Param->getLocation(), Destructor);
11039 DiagnoseUseOfDecl(Destructor, Param->getLocation());
Hans Wennborg0f3c10c2014-01-13 17:23:24 +000011040 }
11041 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +000011042 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000011043
11044 // Parameters with the pass_object_size attribute only need to be marked
11045 // constant at function definitions. Because we lack information about
11046 // whether we're on a declaration or definition when we're instantiating the
11047 // attribute, we need to check for constness here.
11048 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
11049 if (!Param->getType().isConstQualified())
11050 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
11051 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +000011052 }
11053
11054 return HasInvalidParm;
11055}
John McCall2b5c1b22010-08-12 21:44:57 +000011056
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011057/// A helper function to get the alignment of a Decl referred to by DeclRefExpr
11058/// or MemberExpr.
11059static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
11060 ASTContext &Context) {
11061 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
11062 return Context.getDeclAlign(DRE->getDecl());
11063
11064 if (const auto *ME = dyn_cast<MemberExpr>(E))
11065 return Context.getDeclAlign(ME->getMemberDecl());
11066
11067 return TypeAlign;
11068}
11069
John McCall2b5c1b22010-08-12 21:44:57 +000011070/// CheckCastAlign - Implements -Wcast-align, which warns when a
11071/// pointer cast increases the alignment requirements.
11072void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
11073 // This is actually a lot of work to potentially be doing on every
11074 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011075 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +000011076 return;
11077
11078 // Ignore dependent types.
11079 if (T->isDependentType() || Op->getType()->isDependentType())
11080 return;
11081
11082 // Require that the destination be a pointer type.
11083 const PointerType *DestPtr = T->getAs<PointerType>();
11084 if (!DestPtr) return;
11085
11086 // If the destination has alignment 1, we're done.
11087 QualType DestPointee = DestPtr->getPointeeType();
11088 if (DestPointee->isIncompleteType()) return;
11089 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
11090 if (DestAlign.isOne()) return;
11091
11092 // Require that the source be a pointer type.
11093 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
11094 if (!SrcPtr) return;
11095 QualType SrcPointee = SrcPtr->getPointeeType();
11096
11097 // Whitelist casts from cv void*. We already implicitly
11098 // whitelisted casts to cv void*, since they have alignment 1.
11099 // Also whitelist casts involving incomplete types, which implicitly
11100 // includes 'void'.
11101 if (SrcPointee->isIncompleteType()) return;
11102
11103 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
Akira Hatanaka21e5fdd2016-11-30 19:42:03 +000011104
11105 if (auto *CE = dyn_cast<CastExpr>(Op)) {
11106 if (CE->getCastKind() == CK_ArrayToPointerDecay)
11107 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
11108 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
11109 if (UO->getOpcode() == UO_AddrOf)
11110 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11111 }
11112
John McCall2b5c1b22010-08-12 21:44:57 +000011113 if (SrcAlign >= DestAlign) return;
11114
11115 Diag(TRange.getBegin(), diag::warn_cast_align)
11116 << Op->getType() << T
11117 << static_cast<unsigned>(SrcAlign.getQuantity())
11118 << static_cast<unsigned>(DestAlign.getQuantity())
11119 << TRange << Op->getSourceRange();
11120}
11121
Chandler Carruth28389f02011-08-05 09:10:50 +000011122/// \brief Check whether this array fits the idiom of a size-one tail padded
11123/// array member of a struct.
11124///
11125/// We avoid emitting out-of-bounds access warnings for such arrays as they are
11126/// commonly used to emulate flexible arrays in C89 code.
Benjamin Kramer7320b992016-06-15 14:20:56 +000011127static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
Chandler Carruth28389f02011-08-05 09:10:50 +000011128 const NamedDecl *ND) {
11129 if (Size != 1 || !ND) return false;
11130
11131 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11132 if (!FD) return false;
11133
11134 // Don't consider sizes resulting from macro expansions or template argument
11135 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +000011136
11137 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011138 while (TInfo) {
11139 TypeLoc TL = TInfo->getTypeLoc();
11140 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +000011141 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11142 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011143 TInfo = TDL->getTypeSourceInfo();
11144 continue;
11145 }
David Blaikie6adc78e2013-02-18 22:06:02 +000011146 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11147 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +000011148 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11149 return false;
11150 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +000011151 break;
Sean Callanan06a48a62012-05-04 18:22:53 +000011152 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011153
11154 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +000011155 if (!RD) return false;
11156 if (RD->isUnion()) return false;
11157 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11158 if (!CRD->isStandardLayout()) return false;
11159 }
Chandler Carruth28389f02011-08-05 09:10:50 +000011160
Benjamin Kramer8c543672011-08-06 03:04:42 +000011161 // See if this is the last field decl in the record.
11162 const Decl *D = FD;
11163 while ((D = D->getNextDeclInContext()))
11164 if (isa<FieldDecl>(D))
11165 return false;
11166 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +000011167}
11168
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011169void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011170 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +000011171 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011172 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011173 if (IndexExpr->isValueDependent())
11174 return;
11175
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011176 const Type *EffectiveType =
11177 BaseExpr->getType()->getPointeeOrArrayElementType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011178 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011179 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011180 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011181 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +000011182 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +000011183
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011184 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +000011185 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +000011186 return;
Richard Smith13f67182011-12-16 19:31:14 +000011187 if (IndexNegated)
11188 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +000011189
Craig Topperc3ec1492014-05-26 06:22:03 +000011190 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +000011191 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011192 ND = DRE->getDecl();
Chandler Carruth28389f02011-08-05 09:10:50 +000011193 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011194 ND = ME->getMemberDecl();
Chandler Carruth126b1552011-08-05 08:07:29 +000011195
Ted Kremeneke4b316c2011-02-23 23:06:04 +000011196 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011197 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +000011198 if (!size.isStrictlyPositive())
11199 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011200
Anastasia Stulovadb7a31c2016-07-05 11:31:24 +000011201 const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
Nico Weber7c299802011-09-17 22:59:41 +000011202 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011203 // Make sure we're comparing apples to apples when comparing index to size
11204 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11205 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +000011206 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +000011207 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011208 if (ptrarith_typesize != array_typesize) {
11209 // There's a cast to a different size type involved
11210 uint64_t ratio = array_typesize / ptrarith_typesize;
11211 // TODO: Be smarter about handling cases where array_typesize is not a
11212 // multiple of ptrarith_typesize
11213 if (ptrarith_typesize * ratio == array_typesize)
11214 size *= llvm::APInt(size.getBitWidth(), ratio);
11215 }
11216 }
11217
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011218 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011219 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011220 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011221 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +000011222
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011223 // For array subscripting the index must be less than size, but for pointer
11224 // arithmetic also allow the index (offset) to be equal to size since
11225 // computing the next address after the end of the array is legal and
11226 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +000011227 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +000011228 return;
11229
11230 // Also don't warn for arrays of size 1 which are members of some
11231 // structure. These are often used to approximate flexible arrays in C89
11232 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011233 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +000011234 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011235
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011236 // Suppress the warning if the subscript expression (as identified by the
11237 // ']' location) and the index expression are both from macro expansions
11238 // within a system header.
11239 if (ASE) {
11240 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11241 ASE->getRBracketLoc());
11242 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11243 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11244 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +000011245 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011246 return;
11247 }
11248 }
11249
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011250 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011251 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011252 DiagID = diag::warn_array_index_exceeds_bounds;
11253
11254 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11255 PDiag(DiagID) << index.toString(10, true)
11256 << size.toString(10, true)
11257 << (unsigned)size.getLimitedValue(~0U)
11258 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +000011259 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011260 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011261 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011262 DiagID = diag::warn_ptr_arith_precedes_bounds;
11263 if (index.isNegative()) index = -index;
11264 }
11265
11266 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11267 PDiag(DiagID) << index.toString(10, true)
11268 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +000011269 }
Chandler Carruth1af88f12011-02-17 21:10:52 +000011270
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011271 if (!ND) {
11272 // Try harder to find a NamedDecl to point at in the note.
11273 while (const ArraySubscriptExpr *ASE =
11274 dyn_cast<ArraySubscriptExpr>(BaseExpr))
11275 BaseExpr = ASE->getBase()->IgnoreParenCasts();
11276 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011277 ND = DRE->getDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011278 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
George Burgess IV00f70bd2018-03-01 05:43:23 +000011279 ND = ME->getMemberDecl();
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +000011280 }
11281
Chandler Carruth1af88f12011-02-17 21:10:52 +000011282 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011283 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11284 PDiag(diag::note_array_index_out_of_bounds)
11285 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +000011286}
11287
Ted Kremenekdf26df72011-03-01 18:41:00 +000011288void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011289 int AllowOnePastEnd = 0;
11290 while (expr) {
11291 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +000011292 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011293 case Stmt::ArraySubscriptExprClass: {
11294 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +000011295 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011296 AllowOnePastEnd > 0);
Aaron Ballman93c6ba12018-04-24 19:21:04 +000011297 expr = ASE->getBase();
11298 break;
11299 }
11300 case Stmt::MemberExprClass: {
11301 expr = cast<MemberExpr>(expr)->getBase();
11302 break;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011303 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +000011304 case Stmt::OMPArraySectionExprClass: {
11305 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11306 if (ASE->getLowerBound())
11307 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11308 /*ASE=*/nullptr, AllowOnePastEnd > 0);
11309 return;
11310 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +000011311 case Stmt::UnaryOperatorClass: {
11312 // Only unwrap the * and & unary operators
11313 const UnaryOperator *UO = cast<UnaryOperator>(expr);
11314 expr = UO->getSubExpr();
11315 switch (UO->getOpcode()) {
11316 case UO_AddrOf:
11317 AllowOnePastEnd++;
11318 break;
11319 case UO_Deref:
11320 AllowOnePastEnd--;
11321 break;
11322 default:
11323 return;
11324 }
11325 break;
11326 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011327 case Stmt::ConditionalOperatorClass: {
11328 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11329 if (const Expr *lhs = cond->getLHS())
11330 CheckArrayAccess(lhs);
11331 if (const Expr *rhs = cond->getRHS())
11332 CheckArrayAccess(rhs);
11333 return;
11334 }
Daniel Marjamaki20a209e2017-02-28 14:53:50 +000011335 case Stmt::CXXOperatorCallExprClass: {
11336 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11337 for (const auto *Arg : OCE->arguments())
11338 CheckArrayAccess(Arg);
11339 return;
11340 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011341 default:
11342 return;
11343 }
Peter Collingbourne91147592011-04-15 00:35:48 +000011344 }
Ted Kremenekdf26df72011-03-01 18:41:00 +000011345}
John McCall31168b02011-06-15 23:02:42 +000011346
11347//===--- CHECK: Objective-C retain cycles ----------------------------------//
11348
11349namespace {
John McCall31168b02011-06-15 23:02:42 +000011350
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011351struct RetainCycleOwner {
11352 VarDecl *Variable = nullptr;
11353 SourceRange Range;
11354 SourceLocation Loc;
11355 bool Indirect = false;
11356
11357 RetainCycleOwner() = default;
11358
11359 void setLocsFrom(Expr *e) {
11360 Loc = e->getExprLoc();
11361 Range = e->getSourceRange();
11362 }
11363};
11364
11365} // namespace
John McCall31168b02011-06-15 23:02:42 +000011366
11367/// Consider whether capturing the given variable can possibly lead to
11368/// a retain cycle.
11369static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +000011370 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +000011371 // lifetime. In MRR, it's captured strongly if the variable is
11372 // __block and has an appropriate type.
11373 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11374 return false;
11375
11376 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011377 if (ref)
11378 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +000011379 return true;
11380}
11381
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011382static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +000011383 while (true) {
11384 e = e->IgnoreParens();
11385 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11386 switch (cast->getCastKind()) {
11387 case CK_BitCast:
11388 case CK_LValueBitCast:
11389 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +000011390 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +000011391 e = cast->getSubExpr();
11392 continue;
11393
John McCall31168b02011-06-15 23:02:42 +000011394 default:
11395 return false;
11396 }
11397 }
11398
11399 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11400 ObjCIvarDecl *ivar = ref->getDecl();
11401 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11402 return false;
11403
11404 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011405 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +000011406 return false;
11407
11408 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11409 owner.Indirect = true;
11410 return true;
11411 }
11412
11413 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11414 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11415 if (!var) return false;
11416 return considerVariable(var, ref, owner);
11417 }
11418
John McCall31168b02011-06-15 23:02:42 +000011419 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11420 if (member->isArrow()) return false;
11421
11422 // Don't count this as an indirect ownership.
11423 e = member->getBase();
11424 continue;
11425 }
11426
John McCallfe96e0b2011-11-06 09:01:30 +000011427 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11428 // Only pay attention to pseudo-objects on property references.
11429 ObjCPropertyRefExpr *pre
11430 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11431 ->IgnoreParens());
11432 if (!pre) return false;
11433 if (pre->isImplicitProperty()) return false;
11434 ObjCPropertyDecl *property = pre->getExplicitProperty();
11435 if (!property->isRetaining() &&
11436 !(property->getPropertyIvarDecl() &&
11437 property->getPropertyIvarDecl()->getType()
11438 .getObjCLifetime() == Qualifiers::OCL_Strong))
11439 return false;
11440
11441 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011442 if (pre->isSuperReceiver()) {
11443 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11444 if (!owner.Variable)
11445 return false;
11446 owner.Loc = pre->getLocation();
11447 owner.Range = pre->getSourceRange();
11448 return true;
11449 }
John McCallfe96e0b2011-11-06 09:01:30 +000011450 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11451 ->getSourceExpr());
11452 continue;
11453 }
11454
John McCall31168b02011-06-15 23:02:42 +000011455 // Array ivars?
11456
11457 return false;
11458 }
11459}
11460
11461namespace {
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011462
John McCall31168b02011-06-15 23:02:42 +000011463 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011464 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +000011465 VarDecl *Variable;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011466 Expr *Capturer = nullptr;
11467 bool VarWillBeReased = false;
11468
11469 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11470 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11471 Context(Context), Variable(variable) {}
John McCall31168b02011-06-15 23:02:42 +000011472
11473 void VisitDeclRefExpr(DeclRefExpr *ref) {
11474 if (ref->getDecl() == Variable && !Capturer)
11475 Capturer = ref;
11476 }
11477
John McCall31168b02011-06-15 23:02:42 +000011478 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11479 if (Capturer) return;
11480 Visit(ref->getBase());
11481 if (Capturer && ref->isFreeIvar())
11482 Capturer = ref;
11483 }
11484
11485 void VisitBlockExpr(BlockExpr *block) {
11486 // Look inside nested blocks
11487 if (block->getBlockDecl()->capturesVariable(Variable))
11488 Visit(block->getBlockDecl()->getBody());
11489 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +000011490
11491 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11492 if (Capturer) return;
11493 if (OVE->getSourceExpr())
11494 Visit(OVE->getSourceExpr());
11495 }
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011496
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011497 void VisitBinaryOperator(BinaryOperator *BinOp) {
11498 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11499 return;
11500 Expr *LHS = BinOp->getLHS();
11501 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11502 if (DRE->getDecl() != Variable)
11503 return;
11504 if (Expr *RHS = BinOp->getRHS()) {
11505 RHS = RHS->IgnoreParenCasts();
11506 llvm::APSInt Value;
11507 VarWillBeReased =
11508 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11509 }
11510 }
11511 }
John McCall31168b02011-06-15 23:02:42 +000011512 };
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011513
11514} // namespace
John McCall31168b02011-06-15 23:02:42 +000011515
11516/// Check whether the given argument is a block which captures a
11517/// variable.
11518static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11519 assert(owner.Variable && owner.Loc.isValid());
11520
11521 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +000011522
11523 // Look through [^{...} copy] and Block_copy(^{...}).
11524 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11525 Selector Cmd = ME->getSelector();
11526 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11527 e = ME->getInstanceReceiver();
11528 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +000011529 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +000011530 e = e->IgnoreParenCasts();
11531 }
11532 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11533 if (CE->getNumArgs() == 1) {
11534 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +000011535 if (Fn) {
11536 const IdentifierInfo *FnI = Fn->getIdentifier();
11537 if (FnI && FnI->isStr("_Block_copy")) {
11538 e = CE->getArg(0)->IgnoreParenCasts();
11539 }
11540 }
Jordan Rose67e887c2012-09-17 17:54:30 +000011541 }
11542 }
11543
John McCall31168b02011-06-15 23:02:42 +000011544 BlockExpr *block = dyn_cast<BlockExpr>(e);
11545 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +000011546 return nullptr;
John McCall31168b02011-06-15 23:02:42 +000011547
11548 FindCaptureVisitor visitor(S.Context, owner.Variable);
11549 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +000011550 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +000011551}
11552
11553static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11554 RetainCycleOwner &owner) {
11555 assert(capturer);
11556 assert(owner.Variable && owner.Loc.isValid());
11557
11558 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11559 << owner.Variable << capturer->getSourceRange();
11560 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11561 << owner.Indirect << owner.Range;
11562}
11563
11564/// Check for a keyword selector that starts with the word 'add' or
11565/// 'set'.
11566static bool isSetterLikeSelector(Selector sel) {
11567 if (sel.isUnarySelector()) return false;
11568
Chris Lattner0e62c1c2011-07-23 10:55:15 +000011569 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +000011570 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011571 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +000011572 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +000011573 else if (str.startswith("add")) {
11574 // Specially whitelist 'addOperationWithBlock:'.
11575 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11576 return false;
11577 str = str.substr(3);
11578 }
John McCall31168b02011-06-15 23:02:42 +000011579 else
11580 return false;
11581
11582 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +000011583 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +000011584}
11585
Benjamin Kramer3a743452015-03-09 15:03:32 +000011586static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11587 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011588 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11589 Message->getReceiverInterface(),
11590 NSAPI::ClassId_NSMutableArray);
11591 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011592 return None;
11593 }
11594
11595 Selector Sel = Message->getSelector();
11596
11597 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11598 S.NSAPIObj->getNSArrayMethodKind(Sel);
11599 if (!MKOpt) {
11600 return None;
11601 }
11602
11603 NSAPI::NSArrayMethodKind MK = *MKOpt;
11604
11605 switch (MK) {
11606 case NSAPI::NSMutableArr_addObject:
11607 case NSAPI::NSMutableArr_insertObjectAtIndex:
11608 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11609 return 0;
11610 case NSAPI::NSMutableArr_replaceObjectAtIndex:
11611 return 1;
11612
11613 default:
11614 return None;
11615 }
11616
11617 return None;
11618}
11619
11620static
11621Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11622 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011623 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11624 Message->getReceiverInterface(),
11625 NSAPI::ClassId_NSMutableDictionary);
11626 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011627 return None;
11628 }
11629
11630 Selector Sel = Message->getSelector();
11631
11632 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11633 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11634 if (!MKOpt) {
11635 return None;
11636 }
11637
11638 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11639
11640 switch (MK) {
11641 case NSAPI::NSMutableDict_setObjectForKey:
11642 case NSAPI::NSMutableDict_setValueForKey:
11643 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11644 return 0;
11645
11646 default:
11647 return None;
11648 }
11649
11650 return None;
11651}
11652
11653static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011654 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11655 Message->getReceiverInterface(),
11656 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +000011657
Alex Denisov5dfac812015-08-06 04:51:14 +000011658 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11659 Message->getReceiverInterface(),
11660 NSAPI::ClassId_NSMutableOrderedSet);
11661 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011662 return None;
11663 }
11664
11665 Selector Sel = Message->getSelector();
11666
11667 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11668 if (!MKOpt) {
11669 return None;
11670 }
11671
11672 NSAPI::NSSetMethodKind MK = *MKOpt;
11673
11674 switch (MK) {
11675 case NSAPI::NSMutableSet_addObject:
11676 case NSAPI::NSOrderedSet_setObjectAtIndex:
11677 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11678 case NSAPI::NSOrderedSet_insertObjectAtIndex:
11679 return 0;
11680 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11681 return 1;
11682 }
11683
11684 return None;
11685}
11686
11687void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11688 if (!Message->isInstanceMessage()) {
11689 return;
11690 }
11691
11692 Optional<int> ArgOpt;
11693
11694 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11695 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11696 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11697 return;
11698 }
11699
11700 int ArgIndex = *ArgOpt;
11701
Alex Denisove1d882c2015-03-04 17:55:52 +000011702 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11703 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11704 Arg = OE->getSourceExpr()->IgnoreImpCasts();
11705 }
11706
Alex Denisov5dfac812015-08-06 04:51:14 +000011707 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011708 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +000011709 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +000011710 Diag(Message->getSourceRange().getBegin(),
11711 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011712 << ArgRE->getDecl() << StringRef("'super'");
Alex Denisove1d882c2015-03-04 17:55:52 +000011713 }
11714 }
Alex Denisov5dfac812015-08-06 04:51:14 +000011715 } else {
11716 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11717
11718 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11719 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11720 }
11721
11722 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11723 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11724 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11725 ValueDecl *Decl = ReceiverRE->getDecl();
11726 Diag(Message->getSourceRange().getBegin(),
11727 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011728 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011729 if (!ArgRE->isObjCSelfExpr()) {
11730 Diag(Decl->getLocation(),
11731 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000011732 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011733 }
11734 }
11735 }
11736 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11737 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11738 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11739 ObjCIvarDecl *Decl = IvarRE->getDecl();
11740 Diag(Message->getSourceRange().getBegin(),
11741 diag::warn_objc_circular_container)
Richard Trieub4025802018-03-28 04:16:13 +000011742 << Decl << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011743 Diag(Decl->getLocation(),
11744 diag::note_objc_circular_container_declared_here)
Richard Trieub4025802018-03-28 04:16:13 +000011745 << Decl;
Alex Denisov5dfac812015-08-06 04:51:14 +000011746 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011747 }
11748 }
11749 }
Alex Denisove1d882c2015-03-04 17:55:52 +000011750}
11751
John McCall31168b02011-06-15 23:02:42 +000011752/// Check a message send to see if it's likely to cause a retain cycle.
11753void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11754 // Only check instance methods whose selector looks like a setter.
11755 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11756 return;
11757
11758 // Try to find a variable that the receiver is strongly owned by.
11759 RetainCycleOwner owner;
11760 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011761 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +000011762 return;
11763 } else {
11764 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11765 owner.Variable = getCurMethodDecl()->getSelfDecl();
11766 owner.Loc = msg->getSuperLoc();
11767 owner.Range = msg->getSuperLoc();
11768 }
11769
11770 // Check whether the receiver is captured by any of the arguments.
Alex Lorenz42a97a92017-11-17 20:44:25 +000011771 const ObjCMethodDecl *MD = msg->getMethodDecl();
11772 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11773 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11774 // noescape blocks should not be retained by the method.
11775 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11776 continue;
John McCall31168b02011-06-15 23:02:42 +000011777 return diagnoseRetainCycle(*this, capturer, owner);
Alex Lorenz42a97a92017-11-17 20:44:25 +000011778 }
11779 }
John McCall31168b02011-06-15 23:02:42 +000011780}
11781
11782/// Check a property assign to see if it's likely to cause a retain cycle.
11783void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11784 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +000011785 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +000011786 return;
11787
11788 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11789 diagnoseRetainCycle(*this, capturer, owner);
11790}
11791
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011792void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11793 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +000011794 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +000011795 return;
11796
11797 // Because we don't have an expression for the variable, we have to set the
11798 // location explicitly here.
11799 Owner.Loc = Var->getLocation();
11800 Owner.Range = Var->getSourceRange();
11801
11802 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11803 diagnoseRetainCycle(*this, Capturer, Owner);
11804}
11805
Ted Kremenek9304da92012-12-21 08:04:28 +000011806static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11807 Expr *RHS, bool isProperty) {
11808 // Check if RHS is an Objective-C object literal, which also can get
11809 // immediately zapped in a weak reference. Note that we explicitly
11810 // allow ObjCStringLiterals, since those are designed to never really die.
11811 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011812
Ted Kremenek64873352012-12-21 22:46:35 +000011813 // This enum needs to match with the 'select' in
11814 // warn_objc_arc_literal_assign (off-by-1).
11815 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11816 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11817 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011818
11819 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +000011820 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +000011821 << (isProperty ? 0 : 1)
11822 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +000011823
11824 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +000011825}
11826
Ted Kremenekc1f014a2012-12-21 19:45:30 +000011827static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11828 Qualifiers::ObjCLifetime LT,
11829 Expr *RHS, bool isProperty) {
11830 // Strip off any implicit cast added to get to the one ARC-specific.
11831 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11832 if (cast->getCastKind() == CK_ARCConsumeObject) {
11833 S.Diag(Loc, diag::warn_arc_retained_assign)
11834 << (LT == Qualifiers::OCL_ExplicitNone)
11835 << (isProperty ? 0 : 1)
11836 << RHS->getSourceRange();
11837 return true;
11838 }
11839 RHS = cast->getSubExpr();
11840 }
11841
11842 if (LT == Qualifiers::OCL_Weak &&
11843 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11844 return true;
11845
11846 return false;
11847}
11848
Ted Kremenekb36234d2012-12-21 08:04:20 +000011849bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11850 QualType LHS, Expr *RHS) {
11851 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11852
11853 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11854 return false;
11855
11856 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11857 return true;
11858
11859 return false;
11860}
11861
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011862void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11863 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011864 QualType LHSType;
11865 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +000011866 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011867 ObjCPropertyRefExpr *PRE
11868 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11869 if (PRE && !PRE->isImplicitProperty()) {
11870 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11871 if (PD)
11872 LHSType = PD->getType();
11873 }
11874
11875 if (LHSType.isNull())
11876 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +000011877
11878 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11879
11880 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000011881 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +000011882 getCurFunction()->markSafeWeakUse(LHS);
11883 }
11884
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011885 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11886 return;
Jordan Rose657b5f42012-09-28 22:21:35 +000011887
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011888 // FIXME. Check for other life times.
11889 if (LT != Qualifiers::OCL_None)
11890 return;
11891
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011892 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011893 if (PRE->isImplicitProperty())
11894 return;
11895 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11896 if (!PD)
11897 return;
11898
Bill Wendling44426052012-12-20 19:22:21 +000011899 unsigned Attributes = PD->getPropertyAttributes();
11900 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011901 // when 'assign' attribute was not explicitly specified
11902 // by user, ignore it and rely on property type itself
11903 // for lifetime info.
11904 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11905 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11906 LHSType->isObjCRetainableType())
11907 return;
11908
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011909 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +000011910 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011911 Diag(Loc, diag::warn_arc_retained_property_assign)
11912 << RHS->getSourceRange();
11913 return;
11914 }
11915 RHS = cast->getSubExpr();
11916 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +000011917 }
Bill Wendling44426052012-12-20 19:22:21 +000011918 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +000011919 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11920 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +000011921 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +000011922 }
11923}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011924
11925//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11926
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000011927static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11928 SourceLocation StmtLoc,
11929 const NullStmt *Body) {
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011930 // Do not warn if the body is a macro that expands to nothing, e.g:
11931 //
11932 // #define CALL(x)
11933 // if (condition)
11934 // CALL(0);
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011935 if (Body->hasLeadingEmptyMacro())
11936 return false;
11937
11938 // Get line numbers of statement and body.
11939 bool StmtLineInvalid;
Hans Wennborg95419752017-11-20 17:38:16 +000011940 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011941 &StmtLineInvalid);
11942 if (StmtLineInvalid)
11943 return false;
11944
11945 bool BodyLineInvalid;
11946 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11947 &BodyLineInvalid);
11948 if (BodyLineInvalid)
11949 return false;
11950
11951 // Warn if null statement and body are on the same line.
11952 if (StmtLine != BodyLine)
11953 return false;
11954
11955 return true;
11956}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000011957
11958void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11959 const Stmt *Body,
11960 unsigned DiagID) {
11961 // Since this is a syntactic check, don't emit diagnostic for template
11962 // instantiations, this just adds noise.
11963 if (CurrentInstantiationScope)
11964 return;
11965
11966 // The body should be a null statement.
11967 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11968 if (!NBody)
11969 return;
11970
11971 // Do the usual checks.
11972 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11973 return;
11974
11975 Diag(NBody->getSemiLoc(), DiagID);
11976 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11977}
11978
11979void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11980 const Stmt *PossibleBody) {
11981 assert(!CurrentInstantiationScope); // Ensured by caller
11982
11983 SourceLocation StmtLoc;
11984 const Stmt *Body;
11985 unsigned DiagID;
11986 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11987 StmtLoc = FS->getRParenLoc();
11988 Body = FS->getBody();
11989 DiagID = diag::warn_empty_for_body;
11990 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11991 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11992 Body = WS->getBody();
11993 DiagID = diag::warn_empty_while_body;
11994 } else
11995 return; // Neither `for' nor `while'.
11996
11997 // The body should be a null statement.
11998 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11999 if (!NBody)
12000 return;
12001
12002 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +000012003 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +000012004 return;
12005
12006 // Do the usual checks.
12007 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12008 return;
12009
12010 // `for(...);' and `while(...);' are popular idioms, so in order to keep
12011 // noise level low, emit diagnostics only if for/while is followed by a
12012 // CompoundStmt, e.g.:
12013 // for (int i = 0; i < n; i++);
12014 // {
12015 // a(i);
12016 // }
12017 // or if for/while is followed by a statement with more indentation
12018 // than for/while itself:
12019 // for (int i = 0; i < n; i++);
12020 // a(i);
12021 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
12022 if (!ProbableTypo) {
12023 bool BodyColInvalid;
12024 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
12025 PossibleBody->getLocStart(),
12026 &BodyColInvalid);
12027 if (BodyColInvalid)
12028 return;
12029
12030 bool StmtColInvalid;
12031 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
12032 S->getLocStart(),
12033 &StmtColInvalid);
12034 if (StmtColInvalid)
12035 return;
12036
12037 if (BodyCol > StmtCol)
12038 ProbableTypo = true;
12039 }
12040
12041 if (ProbableTypo) {
12042 Diag(NBody->getSemiLoc(), DiagID);
12043 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12044 }
12045}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012046
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012047//===--- CHECK: Warn on self move with std::move. -------------------------===//
12048
12049/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
12050void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
12051 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012052 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
12053 return;
12054
Richard Smith51ec0cf2017-02-21 01:17:38 +000012055 if (inTemplateInstantiation())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012056 return;
12057
12058 // Strip parens and casts away.
12059 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12060 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12061
12062 // Check for a call expression
12063 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
12064 if (!CE || CE->getNumArgs() != 1)
12065 return;
12066
12067 // Check for a call to std::move
Nico Weberb688d132017-09-28 16:16:39 +000012068 if (!CE->isCallToStdMove())
Richard Trieu36d0b2b2015-01-13 02:32:02 +000012069 return;
12070
12071 // Get argument from std::move
12072 RHSExpr = CE->getArg(0);
12073
12074 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12075 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12076
12077 // Two DeclRefExpr's, check that the decls are the same.
12078 if (LHSDeclRef && RHSDeclRef) {
12079 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12080 return;
12081 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12082 RHSDeclRef->getDecl()->getCanonicalDecl())
12083 return;
12084
12085 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12086 << LHSExpr->getSourceRange()
12087 << RHSExpr->getSourceRange();
12088 return;
12089 }
12090
12091 // Member variables require a different approach to check for self moves.
12092 // MemberExpr's are the same if every nested MemberExpr refers to the same
12093 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
12094 // the base Expr's are CXXThisExpr's.
12095 const Expr *LHSBase = LHSExpr;
12096 const Expr *RHSBase = RHSExpr;
12097 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
12098 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
12099 if (!LHSME || !RHSME)
12100 return;
12101
12102 while (LHSME && RHSME) {
12103 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
12104 RHSME->getMemberDecl()->getCanonicalDecl())
12105 return;
12106
12107 LHSBase = LHSME->getBase();
12108 RHSBase = RHSME->getBase();
12109 LHSME = dyn_cast<MemberExpr>(LHSBase);
12110 RHSME = dyn_cast<MemberExpr>(RHSBase);
12111 }
12112
12113 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
12114 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
12115 if (LHSDeclRef && RHSDeclRef) {
12116 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12117 return;
12118 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12119 RHSDeclRef->getDecl()->getCanonicalDecl())
12120 return;
12121
12122 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12123 << LHSExpr->getSourceRange()
12124 << RHSExpr->getSourceRange();
12125 return;
12126 }
12127
12128 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12129 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12130 << LHSExpr->getSourceRange()
12131 << RHSExpr->getSourceRange();
12132}
12133
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012134//===--- Layout compatibility ----------------------------------------------//
12135
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012136static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012137
12138/// \brief Check if two enumeration types are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012139static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012140 // C++11 [dcl.enum] p8:
12141 // Two enumeration types are layout-compatible if they have the same
12142 // underlying type.
12143 return ED1->isComplete() && ED2->isComplete() &&
12144 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12145}
12146
12147/// \brief Check if two fields are layout-compatible.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012148static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12149 FieldDecl *Field2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012150 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12151 return false;
12152
12153 if (Field1->isBitField() != Field2->isBitField())
12154 return false;
12155
12156 if (Field1->isBitField()) {
12157 // Make sure that the bit-fields are the same length.
12158 unsigned Bits1 = Field1->getBitWidthValue(C);
12159 unsigned Bits2 = Field2->getBitWidthValue(C);
12160
12161 if (Bits1 != Bits2)
12162 return false;
12163 }
12164
12165 return true;
12166}
12167
12168/// \brief Check if two standard-layout structs are layout-compatible.
12169/// (C++11 [class.mem] p17)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012170static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12171 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012172 // If both records are C++ classes, check that base classes match.
12173 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12174 // If one of records is a CXXRecordDecl we are in C++ mode,
12175 // thus the other one is a CXXRecordDecl, too.
12176 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12177 // Check number of base classes.
12178 if (D1CXX->getNumBases() != D2CXX->getNumBases())
12179 return false;
12180
12181 // Check the base classes.
12182 for (CXXRecordDecl::base_class_const_iterator
12183 Base1 = D1CXX->bases_begin(),
12184 BaseEnd1 = D1CXX->bases_end(),
12185 Base2 = D2CXX->bases_begin();
12186 Base1 != BaseEnd1;
12187 ++Base1, ++Base2) {
12188 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12189 return false;
12190 }
12191 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12192 // If only RD2 is a C++ class, it should have zero base classes.
12193 if (D2CXX->getNumBases() > 0)
12194 return false;
12195 }
12196
12197 // Check the fields.
12198 RecordDecl::field_iterator Field2 = RD2->field_begin(),
12199 Field2End = RD2->field_end(),
12200 Field1 = RD1->field_begin(),
12201 Field1End = RD1->field_end();
12202 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12203 if (!isLayoutCompatible(C, *Field1, *Field2))
12204 return false;
12205 }
12206 if (Field1 != Field1End || Field2 != Field2End)
12207 return false;
12208
12209 return true;
12210}
12211
12212/// \brief Check if two standard-layout unions are layout-compatible.
12213/// (C++11 [class.mem] p18)
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012214static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12215 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012216 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012217 for (auto *Field2 : RD2->fields())
12218 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012219
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012220 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012221 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12222 I = UnmatchedFields.begin(),
12223 E = UnmatchedFields.end();
12224
12225 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000012226 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012227 bool Result = UnmatchedFields.erase(*I);
12228 (void) Result;
12229 assert(Result);
12230 break;
12231 }
12232 }
12233 if (I == E)
12234 return false;
12235 }
12236
12237 return UnmatchedFields.empty();
12238}
12239
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012240static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12241 RecordDecl *RD2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012242 if (RD1->isUnion() != RD2->isUnion())
12243 return false;
12244
12245 if (RD1->isUnion())
12246 return isLayoutCompatibleUnion(C, RD1, RD2);
12247 else
12248 return isLayoutCompatibleStruct(C, RD1, RD2);
12249}
12250
12251/// \brief Check if two types are layout-compatible in C++11 sense.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012252static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012253 if (T1.isNull() || T2.isNull())
12254 return false;
12255
12256 // C++11 [basic.types] p11:
12257 // If two types T1 and T2 are the same type, then T1 and T2 are
12258 // layout-compatible types.
12259 if (C.hasSameType(T1, T2))
12260 return true;
12261
12262 T1 = T1.getCanonicalType().getUnqualifiedType();
12263 T2 = T2.getCanonicalType().getUnqualifiedType();
12264
12265 const Type::TypeClass TC1 = T1->getTypeClass();
12266 const Type::TypeClass TC2 = T2->getTypeClass();
12267
12268 if (TC1 != TC2)
12269 return false;
12270
12271 if (TC1 == Type::Enum) {
12272 return isLayoutCompatible(C,
12273 cast<EnumType>(T1)->getDecl(),
12274 cast<EnumType>(T2)->getDecl());
12275 } else if (TC1 == Type::Record) {
12276 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12277 return false;
12278
12279 return isLayoutCompatible(C,
12280 cast<RecordType>(T1)->getDecl(),
12281 cast<RecordType>(T2)->getDecl());
12282 }
12283
12284 return false;
12285}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012286
12287//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12288
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012289/// \brief Given a type tag expression find the type tag itself.
12290///
12291/// \param TypeExpr Type tag expression, as it appears in user's code.
12292///
12293/// \param VD Declaration of an identifier that appears in a type tag.
12294///
12295/// \param MagicValue Type tag magic value.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012296static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12297 const ValueDecl **VD, uint64_t *MagicValue) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012298 while(true) {
12299 if (!TypeExpr)
12300 return false;
12301
12302 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12303
12304 switch (TypeExpr->getStmtClass()) {
12305 case Stmt::UnaryOperatorClass: {
12306 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12307 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12308 TypeExpr = UO->getSubExpr();
12309 continue;
12310 }
12311 return false;
12312 }
12313
12314 case Stmt::DeclRefExprClass: {
12315 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12316 *VD = DRE->getDecl();
12317 return true;
12318 }
12319
12320 case Stmt::IntegerLiteralClass: {
12321 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12322 llvm::APInt MagicValueAPInt = IL->getValue();
12323 if (MagicValueAPInt.getActiveBits() <= 64) {
12324 *MagicValue = MagicValueAPInt.getZExtValue();
12325 return true;
12326 } else
12327 return false;
12328 }
12329
12330 case Stmt::BinaryConditionalOperatorClass:
12331 case Stmt::ConditionalOperatorClass: {
12332 const AbstractConditionalOperator *ACO =
12333 cast<AbstractConditionalOperator>(TypeExpr);
12334 bool Result;
12335 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12336 if (Result)
12337 TypeExpr = ACO->getTrueExpr();
12338 else
12339 TypeExpr = ACO->getFalseExpr();
12340 continue;
12341 }
12342 return false;
12343 }
12344
12345 case Stmt::BinaryOperatorClass: {
12346 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12347 if (BO->getOpcode() == BO_Comma) {
12348 TypeExpr = BO->getRHS();
12349 continue;
12350 }
12351 return false;
12352 }
12353
12354 default:
12355 return false;
12356 }
12357 }
12358}
12359
12360/// \brief Retrieve the C type corresponding to type tag TypeExpr.
12361///
12362/// \param TypeExpr Expression that specifies a type tag.
12363///
12364/// \param MagicValues Registered magic values.
12365///
12366/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12367/// kind.
12368///
12369/// \param TypeInfo Information about the corresponding C type.
12370///
12371/// \returns true if the corresponding C type was found.
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012372static bool GetMatchingCType(
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012373 const IdentifierInfo *ArgumentKind,
12374 const Expr *TypeExpr, const ASTContext &Ctx,
12375 const llvm::DenseMap<Sema::TypeTagMagicValue,
12376 Sema::TypeTagData> *MagicValues,
12377 bool &FoundWrongKind,
12378 Sema::TypeTagData &TypeInfo) {
12379 FoundWrongKind = false;
12380
12381 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000012382 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012383
12384 uint64_t MagicValue;
12385
12386 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12387 return false;
12388
12389 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000012390 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012391 if (I->getArgumentKind() != ArgumentKind) {
12392 FoundWrongKind = true;
12393 return false;
12394 }
12395 TypeInfo.Type = I->getMatchingCType();
12396 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12397 TypeInfo.MustBeNull = I->getMustBeNull();
12398 return true;
12399 }
12400 return false;
12401 }
12402
12403 if (!MagicValues)
12404 return false;
12405
12406 llvm::DenseMap<Sema::TypeTagMagicValue,
12407 Sema::TypeTagData>::const_iterator I =
12408 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12409 if (I == MagicValues->end())
12410 return false;
12411
12412 TypeInfo = I->second;
12413 return true;
12414}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012415
12416void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12417 uint64_t MagicValue, QualType Type,
12418 bool LayoutCompatible,
12419 bool MustBeNull) {
12420 if (!TypeTagForDatatypeMagicValues)
12421 TypeTagForDatatypeMagicValues.reset(
12422 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12423
12424 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12425 (*TypeTagForDatatypeMagicValues)[Magic] =
12426 TypeTagData(Type, LayoutCompatible, MustBeNull);
12427}
12428
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012429static bool IsSameCharType(QualType T1, QualType T2) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012430 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12431 if (!BT1)
12432 return false;
12433
12434 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12435 if (!BT2)
12436 return false;
12437
12438 BuiltinType::Kind T1Kind = BT1->getKind();
12439 BuiltinType::Kind T2Kind = BT2->getKind();
12440
12441 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
12442 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
12443 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12444 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12445}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012446
12447void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012448 const ArrayRef<const Expr *> ExprArgs,
12449 SourceLocation CallSiteLoc) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012450 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12451 bool IsPointerAttr = Attr->getIsPointer();
12452
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012453 // Retrieve the argument representing the 'type_tag'.
Joel E. Denny81508102018-03-13 14:51:22 +000012454 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12455 if (TypeTagIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012456 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012457 << 0 << Attr->getTypeTagIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012458 return;
12459 }
Joel E. Denny81508102018-03-13 14:51:22 +000012460 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012461 bool FoundWrongKind;
12462 TypeTagData TypeInfo;
12463 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12464 TypeTagForDatatypeMagicValues.get(),
12465 FoundWrongKind, TypeInfo)) {
12466 if (FoundWrongKind)
12467 Diag(TypeTagExpr->getExprLoc(),
12468 diag::warn_type_tag_for_datatype_wrong_kind)
12469 << TypeTagExpr->getSourceRange();
12470 return;
12471 }
12472
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012473 // Retrieve the argument representing the 'arg_idx'.
Joel E. Denny81508102018-03-13 14:51:22 +000012474 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12475 if (ArgumentIdxAST >= ExprArgs.size()) {
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012476 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
Joel E. Denny81508102018-03-13 14:51:22 +000012477 << 1 << Attr->getArgumentIdx().getSourceIndex();
Aaron Ballmand1f6dcd2017-11-29 23:10:14 +000012478 return;
12479 }
Joel E. Denny81508102018-03-13 14:51:22 +000012480 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012481 if (IsPointerAttr) {
12482 // Skip implicit cast of pointer to `void *' (as a function argument).
12483 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000012484 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000012485 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012486 ArgumentExpr = ICE->getSubExpr();
12487 }
12488 QualType ArgumentType = ArgumentExpr->getType();
12489
12490 // Passing a `void*' pointer shouldn't trigger a warning.
12491 if (IsPointerAttr && ArgumentType->isVoidPointerType())
12492 return;
12493
12494 if (TypeInfo.MustBeNull) {
12495 // Type tag with matching void type requires a null pointer.
12496 if (!ArgumentExpr->isNullPointerConstant(Context,
12497 Expr::NPC_ValueDependentIsNotNull)) {
12498 Diag(ArgumentExpr->getExprLoc(),
12499 diag::warn_type_safety_null_pointer_required)
12500 << ArgumentKind->getName()
12501 << ArgumentExpr->getSourceRange()
12502 << TypeTagExpr->getSourceRange();
12503 }
12504 return;
12505 }
12506
12507 QualType RequiredType = TypeInfo.Type;
12508 if (IsPointerAttr)
12509 RequiredType = Context.getPointerType(RequiredType);
12510
12511 bool mismatch = false;
12512 if (!TypeInfo.LayoutCompatible) {
12513 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12514
12515 // C++11 [basic.fundamental] p1:
12516 // Plain char, signed char, and unsigned char are three distinct types.
12517 //
12518 // But we treat plain `char' as equivalent to `signed char' or `unsigned
12519 // char' depending on the current char signedness mode.
12520 if (mismatch)
12521 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12522 RequiredType->getPointeeType())) ||
12523 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12524 mismatch = false;
12525 } else
12526 if (IsPointerAttr)
12527 mismatch = !isLayoutCompatible(Context,
12528 ArgumentType->getPointeeType(),
12529 RequiredType->getPointeeType());
12530 else
12531 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12532
12533 if (mismatch)
12534 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000012535 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000012536 << TypeInfo.LayoutCompatible << RequiredType
12537 << ArgumentExpr->getSourceRange()
12538 << TypeTagExpr->getSourceRange();
12539}
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012540
12541void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12542 CharUnits Alignment) {
12543 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12544}
12545
12546void Sema::DiagnoseMisalignedMembers() {
12547 for (MisalignedMember &m : MisalignedMembers) {
Alex Lorenz014181e2016-10-05 09:27:48 +000012548 const NamedDecl *ND = m.RD;
12549 if (ND->getName().empty()) {
12550 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12551 ND = TD;
12552 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012553 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
Alex Lorenz014181e2016-10-05 09:27:48 +000012554 << m.MD << ND << m.E->getSourceRange();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012555 }
12556 MisalignedMembers.clear();
12557}
12558
12559void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012560 E = E->IgnoreParens();
12561 if (!T->isPointerType() && !T->isIntegerType())
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012562 return;
12563 if (isa<UnaryOperator>(E) &&
12564 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12565 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12566 if (isa<MemberExpr>(Op)) {
12567 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12568 MisalignedMember(Op));
12569 if (MA != MisalignedMembers.end() &&
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012570 (T->isIntegerType() ||
Roger Ferrer Ibanezd80d6c52017-12-07 09:23:50 +000012571 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12572 Context.getTypeAlignInChars(
12573 T->getPointeeType()) <= MA->Alignment))))
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012574 MisalignedMembers.erase(MA);
12575 }
12576 }
12577}
12578
12579void Sema::RefersToMemberWithReducedAlignment(
12580 Expr *E,
Benjamin Kramera8c3e672016-12-12 14:41:19 +000012581 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12582 Action) {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012583 const auto *ME = dyn_cast<MemberExpr>(E);
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012584 if (!ME)
12585 return;
12586
Roger Ferrer Ibanez9f963472017-03-13 13:18:21 +000012587 // No need to check expressions with an __unaligned-qualified type.
12588 if (E->getType().getQualifiers().hasUnaligned())
12589 return;
12590
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012591 // For a chain of MemberExpr like "a.b.c.d" this list
12592 // will keep FieldDecl's like [d, c, b].
12593 SmallVector<FieldDecl *, 4> ReverseMemberChain;
12594 const MemberExpr *TopME = nullptr;
12595 bool AnyIsPacked = false;
12596 do {
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012597 QualType BaseType = ME->getBase()->getType();
12598 if (ME->isArrow())
12599 BaseType = BaseType->getPointeeType();
12600 RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
Olivier Goffart67049f02017-07-07 09:38:59 +000012601 if (RD->isInvalidDecl())
12602 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012603
12604 ValueDecl *MD = ME->getMemberDecl();
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012605 auto *FD = dyn_cast<FieldDecl>(MD);
12606 // We do not care about non-data members.
12607 if (!FD || FD->isInvalidDecl())
12608 return;
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012609
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012610 AnyIsPacked =
12611 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12612 ReverseMemberChain.push_back(FD);
12613
12614 TopME = ME;
12615 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12616 } while (ME);
12617 assert(TopME && "We did not compute a topmost MemberExpr!");
12618
12619 // Not the scope of this diagnostic.
12620 if (!AnyIsPacked)
12621 return;
12622
12623 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12624 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12625 // TODO: The innermost base of the member expression may be too complicated.
12626 // For now, just disregard these cases. This is left for future
12627 // improvement.
12628 if (!DRE && !isa<CXXThisExpr>(TopBase))
12629 return;
12630
12631 // Alignment expected by the whole expression.
12632 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12633
12634 // No need to do anything else with this case.
12635 if (ExpectedAlignment.isOne())
12636 return;
12637
12638 // Synthesize offset of the whole access.
12639 CharUnits Offset;
12640 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12641 I++) {
12642 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12643 }
12644
12645 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12646 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12647 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12648
12649 // The base expression of the innermost MemberExpr may give
12650 // stronger guarantees than the class containing the member.
12651 if (DRE && !TopME->isArrow()) {
12652 const ValueDecl *VD = DRE->getDecl();
12653 if (!VD->getType()->isReferenceType())
12654 CompleteObjectAlignment =
12655 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12656 }
12657
12658 // Check if the synthesized offset fulfills the alignment.
12659 if (Offset % ExpectedAlignment != 0 ||
12660 // It may fulfill the offset it but the effective alignment may still be
12661 // lower than the expected expression alignment.
12662 CompleteObjectAlignment < ExpectedAlignment) {
12663 // If this happens, we want to determine a sensible culprit of this.
12664 // Intuitively, watching the chain of member expressions from right to
12665 // left, we start with the required alignment (as required by the field
12666 // type) but some packed attribute in that chain has reduced the alignment.
12667 // It may happen that another packed structure increases it again. But if
12668 // we are here such increase has not been enough. So pointing the first
12669 // FieldDecl that either is packed or else its RecordDecl is,
12670 // seems reasonable.
12671 FieldDecl *FD = nullptr;
12672 CharUnits Alignment;
12673 for (FieldDecl *FDI : ReverseMemberChain) {
12674 if (FDI->hasAttr<PackedAttr>() ||
12675 FDI->getParent()->hasAttr<PackedAttr>()) {
12676 FD = FDI;
12677 Alignment = std::min(
12678 Context.getTypeAlignInChars(FD->getType()),
12679 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12680 break;
12681 }
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012682 }
Roger Ferrer Ibaneze3d80262016-11-14 08:53:27 +000012683 assert(FD && "We did not find a packed FieldDecl!");
12684 Action(E, FD->getParent(), FD, Alignment);
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012685 }
12686}
12687
12688void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12689 using namespace std::placeholders;
Eugene Zelenko11a7ef82017-11-15 22:00:04 +000012690
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +000012691 RefersToMemberWithReducedAlignment(
12692 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12693 _2, _3, _4));
12694}