blob: 4a9df07bc42301c32b502521049838328de6f443 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
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
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000024#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000039#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000041#include <limits>
Eugene Zelenko1ced5092016-02-12 22:53:10 +000042
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000044using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000045
Chris Lattnera26fb342009-02-18 17:49:48 +000046SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
47 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000048 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
49 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000050}
51
John McCallbebede42011-02-26 05:39:39 +000052/// Checks that a call expression's argument count is the desired number.
53/// This is useful when doing custom type-checking. Returns true on error.
54static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
55 unsigned argCount = call->getNumArgs();
56 if (argCount == desiredArgCount) return false;
57
58 if (argCount < desiredArgCount)
59 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
60 << 0 /*function call*/ << desiredArgCount << argCount
61 << call->getSourceRange();
62
63 // Highlight all the excess arguments.
64 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
65 call->getArg(argCount - 1)->getLocEnd());
66
67 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
68 << 0 /*function call*/ << desiredArgCount << argCount
69 << call->getArg(1)->getSourceRange();
70}
71
Julien Lerouge4a5b4442012-04-28 17:39:16 +000072/// Check that the first argument to __builtin_annotation is an integer
73/// and the second argument is a non-wide string literal.
74static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
75 if (checkArgCount(S, TheCall, 2))
76 return true;
77
78 // First argument should be an integer.
79 Expr *ValArg = TheCall->getArg(0);
80 QualType Ty = ValArg->getType();
81 if (!Ty->isIntegerType()) {
82 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
83 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000084 return true;
85 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000086
87 // Second argument should be a constant string.
88 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
89 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
90 if (!Literal || !Literal->isAscii()) {
91 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
92 << StrArg->getSourceRange();
93 return true;
94 }
95
96 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000097 return false;
98}
99
Richard Smith6cbd65d2013-07-11 02:27:57 +0000100/// Check that the argument to __builtin_addressof is a glvalue, and set the
101/// result type to the corresponding pointer type.
102static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
103 if (checkArgCount(S, TheCall, 1))
104 return true;
105
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000106 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000107 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
108 if (ResultType.isNull())
109 return true;
110
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000111 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000112 TheCall->setType(ResultType);
113 return false;
114}
115
John McCall03107a42015-10-29 20:48:01 +0000116static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
117 if (checkArgCount(S, TheCall, 3))
118 return true;
119
120 // First two arguments should be integers.
121 for (unsigned I = 0; I < 2; ++I) {
122 Expr *Arg = TheCall->getArg(I);
123 QualType Ty = Arg->getType();
124 if (!Ty->isIntegerType()) {
125 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
126 << Ty << Arg->getSourceRange();
127 return true;
128 }
129 }
130
131 // Third argument should be a pointer to a non-const integer.
132 // IRGen correctly handles volatile, restrict, and address spaces, and
133 // the other qualifiers aren't possible.
134 {
135 Expr *Arg = TheCall->getArg(2);
136 QualType Ty = Arg->getType();
137 const auto *PtrTy = Ty->getAs<PointerType>();
138 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
139 !PtrTy->getPointeeType().isConstQualified())) {
140 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
141 << Ty << Arg->getSourceRange();
142 return true;
143 }
144 }
145
146 return false;
147}
148
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000149static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
150 CallExpr *TheCall, unsigned SizeIdx,
151 unsigned DstSizeIdx) {
152 if (TheCall->getNumArgs() <= SizeIdx ||
153 TheCall->getNumArgs() <= DstSizeIdx)
154 return;
155
156 const Expr *SizeArg = TheCall->getArg(SizeIdx);
157 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
158
159 llvm::APSInt Size, DstSize;
160
161 // find out if both sizes are known at compile time
162 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
163 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
164 return;
165
166 if (Size.ule(DstSize))
167 return;
168
169 // confirmed overflow so generate the diagnostic.
170 IdentifierInfo *FnName = FDecl->getIdentifier();
171 SourceLocation SL = TheCall->getLocStart();
172 SourceRange SR = TheCall->getSourceRange();
173
174 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
175}
176
Peter Collingbournef7706832014-12-12 23:41:25 +0000177static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
178 if (checkArgCount(S, BuiltinCall, 2))
179 return true;
180
181 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
182 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
183 Expr *Call = BuiltinCall->getArg(0);
184 Expr *Chain = BuiltinCall->getArg(1);
185
186 if (Call->getStmtClass() != Stmt::CallExprClass) {
187 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
188 << Call->getSourceRange();
189 return true;
190 }
191
192 auto CE = cast<CallExpr>(Call);
193 if (CE->getCallee()->getType()->isBlockPointerType()) {
194 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
195 << Call->getSourceRange();
196 return true;
197 }
198
199 const Decl *TargetDecl = CE->getCalleeDecl();
200 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
201 if (FD->getBuiltinID()) {
202 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
203 << Call->getSourceRange();
204 return true;
205 }
206
207 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
208 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
209 << Call->getSourceRange();
210 return true;
211 }
212
213 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
214 if (ChainResult.isInvalid())
215 return true;
216 if (!ChainResult.get()->getType()->isPointerType()) {
217 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
218 << Chain->getSourceRange();
219 return true;
220 }
221
David Majnemerced8bdf2015-02-25 17:36:15 +0000222 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000223 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
224 QualType BuiltinTy = S.Context.getFunctionType(
225 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
226 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
227
228 Builtin =
229 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
230
231 BuiltinCall->setType(CE->getType());
232 BuiltinCall->setValueKind(CE->getValueKind());
233 BuiltinCall->setObjectKind(CE->getObjectKind());
234 BuiltinCall->setCallee(Builtin);
235 BuiltinCall->setArg(1, ChainResult.get());
236
237 return false;
238}
239
Reid Kleckner1d59f992015-01-22 01:36:17 +0000240static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
241 Scope::ScopeFlags NeededScopeFlags,
242 unsigned DiagID) {
243 // Scopes aren't available during instantiation. Fortunately, builtin
244 // functions cannot be template args so they cannot be formed through template
245 // instantiation. Therefore checking once during the parse is sufficient.
246 if (!SemaRef.ActiveTemplateInstantiations.empty())
247 return false;
248
249 Scope *S = SemaRef.getCurScope();
250 while (S && !S->isSEHExceptScope())
251 S = S->getParent();
252 if (!S || !(S->getFlags() & NeededScopeFlags)) {
253 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
254 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
255 << DRE->getDecl()->getIdentifier();
256 return true;
257 }
258
259 return false;
260}
261
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000262/// Returns readable name for a call.
263static StringRef getFunctionName(CallExpr *Call) {
264 return cast<FunctionDecl>(Call->getCalleeDecl())->getName();
265}
266
267/// Returns OpenCL access qual.
268// TODO: Refine OpenCLImageAccessAttr to OpenCLAccessAttr since pipe can use
269// it too
270static OpenCLImageAccessAttr *getOpenCLArgAccess(const Decl *D) {
271 if (D->hasAttr<OpenCLImageAccessAttr>())
272 return D->getAttr<OpenCLImageAccessAttr>();
273 return nullptr;
274}
275
276/// Returns true if pipe element type is different from the pointer.
277static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
278 const Expr *Arg0 = Call->getArg(0);
279 // First argument type should always be pipe.
280 if (!Arg0->getType()->isPipeType()) {
281 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
282 << getFunctionName(Call) << Arg0->getSourceRange();
283 return true;
284 }
285 OpenCLImageAccessAttr *AccessQual =
286 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
287 // Validates the access qualifier is compatible with the call.
288 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
289 // read_only and write_only, and assumed to be read_only if no qualifier is
290 // specified.
291 bool isValid = true;
292 bool ReadOnly = getFunctionName(Call).find("read") != StringRef::npos;
293 if (ReadOnly)
294 isValid = AccessQual == nullptr || AccessQual->isReadOnly();
295 else
296 isValid = AccessQual != nullptr && AccessQual->isWriteOnly();
297 if (!isValid) {
298 const char *AM = ReadOnly ? "read_only" : "write_only";
299 S.Diag(Arg0->getLocStart(),
300 diag::err_opencl_builtin_pipe_invalid_access_modifier)
301 << AM << Arg0->getSourceRange();
302 return true;
303 }
304
305 return false;
306}
307
308/// Returns true if pipe element type is different from the pointer.
309static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
310 const Expr *Arg0 = Call->getArg(0);
311 const Expr *ArgIdx = Call->getArg(Idx);
312 const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
313 const Type *EltTy = PipeTy->getElementType().getTypePtr();
314 const PointerType *ArgTy =
315 dyn_cast<PointerType>(ArgIdx->getType().getTypePtr());
316 // The Idx argument should be a pointer and the type of the pointer and
317 // the type of pipe element should also be the same.
318 if (!ArgTy || EltTy != ArgTy->getPointeeType().getTypePtr()) {
319 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
320 << getFunctionName(Call)
321 << S.Context.getPointerType(PipeTy->getElementType())
322 << ArgIdx->getSourceRange();
323 return true;
324 }
325 return false;
326}
327
328// \brief Performs semantic analysis for the read/write_pipe call.
329// \param S Reference to the semantic analyzer.
330// \param Call A pointer to the builtin call.
331// \return True if a semantic error has been found, false otherwise.
332static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
333 // Two kinds of read/write pipe
334 // From OpenCL C Specification 6.13.16.2 the built-in read/write
335 // functions have following forms.
336 switch (Call->getNumArgs()) {
337 case 2: {
338 if (checkOpenCLPipeArg(S, Call))
339 return true;
340 // The call with 2 arguments should be
341 // read/write_pipe(pipe T, T*)
342 // check packet type T
343 if (checkOpenCLPipePacketType(S, Call, 1))
344 return true;
345 } break;
346
347 case 4: {
348 if (checkOpenCLPipeArg(S, Call))
349 return true;
350 // The call with 4 arguments should be
351 // read/write_pipe(pipe T, reserve_id_t, uint, T*)
352 // check reserve_id_t
353 if (!Call->getArg(1)->getType()->isReserveIDT()) {
354 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
355 << getFunctionName(Call) << S.Context.OCLReserveIDTy
356 << Call->getArg(1)->getSourceRange();
357 return true;
358 }
359
360 // check the index
361 const Expr *Arg2 = Call->getArg(2);
362 if (!Arg2->getType()->isIntegerType() &&
363 !Arg2->getType()->isUnsignedIntegerType()) {
364 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
365 << getFunctionName(Call) << S.Context.UnsignedIntTy
366 << Arg2->getSourceRange();
367 return true;
368 }
369
370 // check packet type T
371 if (checkOpenCLPipePacketType(S, Call, 3))
372 return true;
373 } break;
374 default:
375 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
376 << getFunctionName(Call) << Call->getSourceRange();
377 return true;
378 }
379
380 return false;
381}
382
383// \brief Performs a semantic analysis on the {work_group_/sub_group_
384// /_}reserve_{read/write}_pipe
385// \param S Reference to the semantic analyzer.
386// \param Call The call to the builtin function to be analyzed.
387// \return True if a semantic error was found, false otherwise.
388static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
389 if (checkArgCount(S, Call, 2))
390 return true;
391
392 if (checkOpenCLPipeArg(S, Call))
393 return true;
394
395 // check the reserve size
396 if (!Call->getArg(1)->getType()->isIntegerType() &&
397 !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
398 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
399 << getFunctionName(Call) << S.Context.UnsignedIntTy
400 << Call->getArg(1)->getSourceRange();
401 return true;
402 }
403
404 return false;
405}
406
407// \brief Performs a semantic analysis on {work_group_/sub_group_
408// /_}commit_{read/write}_pipe
409// \param S Reference to the semantic analyzer.
410// \param Call The call to the builtin function to be analyzed.
411// \return True if a semantic error was found, false otherwise.
412static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
413 if (checkArgCount(S, Call, 2))
414 return true;
415
416 if (checkOpenCLPipeArg(S, Call))
417 return true;
418
419 // check reserve_id_t
420 if (!Call->getArg(1)->getType()->isReserveIDT()) {
421 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
422 << getFunctionName(Call) << S.Context.OCLReserveIDTy
423 << Call->getArg(1)->getSourceRange();
424 return true;
425 }
426
427 return false;
428}
429
430// \brief Performs a semantic analysis on the call to built-in Pipe
431// Query Functions.
432// \param S Reference to the semantic analyzer.
433// \param Call The call to the builtin function to be analyzed.
434// \return True if a semantic error was found, false otherwise.
435static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
436 if (checkArgCount(S, Call, 1))
437 return true;
438
439 if (!Call->getArg(0)->getType()->isPipeType()) {
440 S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
441 << getFunctionName(Call) << Call->getArg(0)->getSourceRange();
442 return true;
443 }
444
445 return false;
446}
447
John McCalldadc5752010-08-24 06:29:42 +0000448ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000449Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
450 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000451 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000452
Chris Lattner3be167f2010-10-01 23:23:24 +0000453 // Find out if any arguments are required to be integer constant expressions.
454 unsigned ICEArguments = 0;
455 ASTContext::GetBuiltinTypeError Error;
456 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
457 if (Error != ASTContext::GE_None)
458 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
459
460 // If any arguments are required to be ICE's, check and diagnose.
461 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
462 // Skip arguments not required to be ICE's.
463 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
464
465 llvm::APSInt Result;
466 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
467 return true;
468 ICEArguments &= ~(1 << ArgNo);
469 }
470
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000471 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000472 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000473 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000474 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000475 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000476 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000477 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000478 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000479 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000480 if (SemaBuiltinVAStart(TheCall))
481 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000482 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000483 case Builtin::BI__va_start: {
484 switch (Context.getTargetInfo().getTriple().getArch()) {
485 case llvm::Triple::arm:
486 case llvm::Triple::thumb:
487 if (SemaBuiltinVAStartARM(TheCall))
488 return ExprError();
489 break;
490 default:
491 if (SemaBuiltinVAStart(TheCall))
492 return ExprError();
493 break;
494 }
495 break;
496 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000497 case Builtin::BI__builtin_isgreater:
498 case Builtin::BI__builtin_isgreaterequal:
499 case Builtin::BI__builtin_isless:
500 case Builtin::BI__builtin_islessequal:
501 case Builtin::BI__builtin_islessgreater:
502 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000503 if (SemaBuiltinUnorderedCompare(TheCall))
504 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000505 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000506 case Builtin::BI__builtin_fpclassify:
507 if (SemaBuiltinFPClassification(TheCall, 6))
508 return ExprError();
509 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000510 case Builtin::BI__builtin_isfinite:
511 case Builtin::BI__builtin_isinf:
512 case Builtin::BI__builtin_isinf_sign:
513 case Builtin::BI__builtin_isnan:
514 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000515 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000516 return ExprError();
517 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000518 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000519 return SemaBuiltinShuffleVector(TheCall);
520 // TheCall will be freed by the smart pointer here, but that's fine, since
521 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000522 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000523 if (SemaBuiltinPrefetch(TheCall))
524 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000525 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000526 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000527 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000528 if (SemaBuiltinAssume(TheCall))
529 return ExprError();
530 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000531 case Builtin::BI__builtin_assume_aligned:
532 if (SemaBuiltinAssumeAligned(TheCall))
533 return ExprError();
534 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000535 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000536 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000537 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000538 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000539 case Builtin::BI__builtin_longjmp:
540 if (SemaBuiltinLongjmp(TheCall))
541 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000542 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000543 case Builtin::BI__builtin_setjmp:
544 if (SemaBuiltinSetjmp(TheCall))
545 return ExprError();
546 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000547 case Builtin::BI_setjmp:
548 case Builtin::BI_setjmpex:
549 if (checkArgCount(*this, TheCall, 1))
550 return true;
551 break;
John McCallbebede42011-02-26 05:39:39 +0000552
553 case Builtin::BI__builtin_classify_type:
554 if (checkArgCount(*this, TheCall, 1)) return true;
555 TheCall->setType(Context.IntTy);
556 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000557 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000558 if (checkArgCount(*this, TheCall, 1)) return true;
559 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000560 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000561 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000562 case Builtin::BI__sync_fetch_and_add_1:
563 case Builtin::BI__sync_fetch_and_add_2:
564 case Builtin::BI__sync_fetch_and_add_4:
565 case Builtin::BI__sync_fetch_and_add_8:
566 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000567 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000568 case Builtin::BI__sync_fetch_and_sub_1:
569 case Builtin::BI__sync_fetch_and_sub_2:
570 case Builtin::BI__sync_fetch_and_sub_4:
571 case Builtin::BI__sync_fetch_and_sub_8:
572 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000573 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000574 case Builtin::BI__sync_fetch_and_or_1:
575 case Builtin::BI__sync_fetch_and_or_2:
576 case Builtin::BI__sync_fetch_and_or_4:
577 case Builtin::BI__sync_fetch_and_or_8:
578 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000579 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000580 case Builtin::BI__sync_fetch_and_and_1:
581 case Builtin::BI__sync_fetch_and_and_2:
582 case Builtin::BI__sync_fetch_and_and_4:
583 case Builtin::BI__sync_fetch_and_and_8:
584 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000585 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000586 case Builtin::BI__sync_fetch_and_xor_1:
587 case Builtin::BI__sync_fetch_and_xor_2:
588 case Builtin::BI__sync_fetch_and_xor_4:
589 case Builtin::BI__sync_fetch_and_xor_8:
590 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000591 case Builtin::BI__sync_fetch_and_nand:
592 case Builtin::BI__sync_fetch_and_nand_1:
593 case Builtin::BI__sync_fetch_and_nand_2:
594 case Builtin::BI__sync_fetch_and_nand_4:
595 case Builtin::BI__sync_fetch_and_nand_8:
596 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000597 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000598 case Builtin::BI__sync_add_and_fetch_1:
599 case Builtin::BI__sync_add_and_fetch_2:
600 case Builtin::BI__sync_add_and_fetch_4:
601 case Builtin::BI__sync_add_and_fetch_8:
602 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000603 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000604 case Builtin::BI__sync_sub_and_fetch_1:
605 case Builtin::BI__sync_sub_and_fetch_2:
606 case Builtin::BI__sync_sub_and_fetch_4:
607 case Builtin::BI__sync_sub_and_fetch_8:
608 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000609 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000610 case Builtin::BI__sync_and_and_fetch_1:
611 case Builtin::BI__sync_and_and_fetch_2:
612 case Builtin::BI__sync_and_and_fetch_4:
613 case Builtin::BI__sync_and_and_fetch_8:
614 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000615 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000616 case Builtin::BI__sync_or_and_fetch_1:
617 case Builtin::BI__sync_or_and_fetch_2:
618 case Builtin::BI__sync_or_and_fetch_4:
619 case Builtin::BI__sync_or_and_fetch_8:
620 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000621 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000622 case Builtin::BI__sync_xor_and_fetch_1:
623 case Builtin::BI__sync_xor_and_fetch_2:
624 case Builtin::BI__sync_xor_and_fetch_4:
625 case Builtin::BI__sync_xor_and_fetch_8:
626 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000627 case Builtin::BI__sync_nand_and_fetch:
628 case Builtin::BI__sync_nand_and_fetch_1:
629 case Builtin::BI__sync_nand_and_fetch_2:
630 case Builtin::BI__sync_nand_and_fetch_4:
631 case Builtin::BI__sync_nand_and_fetch_8:
632 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000633 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000634 case Builtin::BI__sync_val_compare_and_swap_1:
635 case Builtin::BI__sync_val_compare_and_swap_2:
636 case Builtin::BI__sync_val_compare_and_swap_4:
637 case Builtin::BI__sync_val_compare_and_swap_8:
638 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000639 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000640 case Builtin::BI__sync_bool_compare_and_swap_1:
641 case Builtin::BI__sync_bool_compare_and_swap_2:
642 case Builtin::BI__sync_bool_compare_and_swap_4:
643 case Builtin::BI__sync_bool_compare_and_swap_8:
644 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000645 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000646 case Builtin::BI__sync_lock_test_and_set_1:
647 case Builtin::BI__sync_lock_test_and_set_2:
648 case Builtin::BI__sync_lock_test_and_set_4:
649 case Builtin::BI__sync_lock_test_and_set_8:
650 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000651 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000652 case Builtin::BI__sync_lock_release_1:
653 case Builtin::BI__sync_lock_release_2:
654 case Builtin::BI__sync_lock_release_4:
655 case Builtin::BI__sync_lock_release_8:
656 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000657 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000658 case Builtin::BI__sync_swap_1:
659 case Builtin::BI__sync_swap_2:
660 case Builtin::BI__sync_swap_4:
661 case Builtin::BI__sync_swap_8:
662 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000663 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000664 case Builtin::BI__builtin_nontemporal_load:
665 case Builtin::BI__builtin_nontemporal_store:
666 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000667#define BUILTIN(ID, TYPE, ATTRS)
668#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
669 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000670 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000671#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000672 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000673 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000674 return ExprError();
675 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000676 case Builtin::BI__builtin_addressof:
677 if (SemaBuiltinAddressof(*this, TheCall))
678 return ExprError();
679 break;
John McCall03107a42015-10-29 20:48:01 +0000680 case Builtin::BI__builtin_add_overflow:
681 case Builtin::BI__builtin_sub_overflow:
682 case Builtin::BI__builtin_mul_overflow:
Craig Toppera86e70d2015-11-07 06:16:14 +0000683 if (SemaBuiltinOverflow(*this, TheCall))
684 return ExprError();
685 break;
Richard Smith760520b2014-06-03 23:27:44 +0000686 case Builtin::BI__builtin_operator_new:
687 case Builtin::BI__builtin_operator_delete:
688 if (!getLangOpts().CPlusPlus) {
689 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
690 << (BuiltinID == Builtin::BI__builtin_operator_new
691 ? "__builtin_operator_new"
692 : "__builtin_operator_delete")
693 << "C++";
694 return ExprError();
695 }
696 // CodeGen assumes it can find the global new and delete to call,
697 // so ensure that they are declared.
698 DeclareGlobalNewDelete();
699 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000700
701 // check secure string manipulation functions where overflows
702 // are detectable at compile time
703 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000704 case Builtin::BI__builtin___memmove_chk:
705 case Builtin::BI__builtin___memset_chk:
706 case Builtin::BI__builtin___strlcat_chk:
707 case Builtin::BI__builtin___strlcpy_chk:
708 case Builtin::BI__builtin___strncat_chk:
709 case Builtin::BI__builtin___strncpy_chk:
710 case Builtin::BI__builtin___stpncpy_chk:
711 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
712 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000713 case Builtin::BI__builtin___memccpy_chk:
714 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
715 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000716 case Builtin::BI__builtin___snprintf_chk:
717 case Builtin::BI__builtin___vsnprintf_chk:
718 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
719 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000720 case Builtin::BI__builtin_call_with_static_chain:
721 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
722 return ExprError();
723 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000724 case Builtin::BI__exception_code:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000725 case Builtin::BI_exception_code:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000726 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
727 diag::err_seh___except_block))
728 return ExprError();
729 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000730 case Builtin::BI__exception_info:
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000731 case Builtin::BI_exception_info:
Reid Kleckner1d59f992015-01-22 01:36:17 +0000732 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
733 diag::err_seh___except_filter))
734 return ExprError();
735 break;
David Majnemerba3e5ec2015-03-13 18:26:17 +0000736 case Builtin::BI__GetExceptionInfo:
737 if (checkArgCount(*this, TheCall, 1))
738 return ExprError();
739
740 if (CheckCXXThrowOperand(
741 TheCall->getLocStart(),
742 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
743 TheCall))
744 return ExprError();
745
746 TheCall->setType(Context.VoidPtrTy);
747 break;
Xiuli Panbb4d8d32016-01-26 04:03:48 +0000748 case Builtin::BIread_pipe:
749 case Builtin::BIwrite_pipe:
750 // Since those two functions are declared with var args, we need a semantic
751 // check for the argument.
752 if (SemaBuiltinRWPipe(*this, TheCall))
753 return ExprError();
754 break;
755 case Builtin::BIreserve_read_pipe:
756 case Builtin::BIreserve_write_pipe:
757 case Builtin::BIwork_group_reserve_read_pipe:
758 case Builtin::BIwork_group_reserve_write_pipe:
759 case Builtin::BIsub_group_reserve_read_pipe:
760 case Builtin::BIsub_group_reserve_write_pipe:
761 if (SemaBuiltinReserveRWPipe(*this, TheCall))
762 return ExprError();
763 // Since return type of reserve_read/write_pipe built-in function is
764 // reserve_id_t, which is not defined in the builtin def file , we used int
765 // as return type and need to override the return type of these functions.
766 TheCall->setType(Context.OCLReserveIDTy);
767 break;
768 case Builtin::BIcommit_read_pipe:
769 case Builtin::BIcommit_write_pipe:
770 case Builtin::BIwork_group_commit_read_pipe:
771 case Builtin::BIwork_group_commit_write_pipe:
772 case Builtin::BIsub_group_commit_read_pipe:
773 case Builtin::BIsub_group_commit_write_pipe:
774 if (SemaBuiltinCommitRWPipe(*this, TheCall))
775 return ExprError();
776 break;
777 case Builtin::BIget_pipe_num_packets:
778 case Builtin::BIget_pipe_max_packets:
779 if (SemaBuiltinPipePackets(*this, TheCall))
780 return ExprError();
781 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000782 }
Richard Smith760520b2014-06-03 23:27:44 +0000783
Nate Begeman4904e322010-06-08 02:47:44 +0000784 // Since the target specific builtins for each arch overlap, only check those
785 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000786 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000787 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000788 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000789 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000790 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000791 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000792 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
793 return ExprError();
794 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000795 case llvm::Triple::aarch64:
796 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000797 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000798 return ExprError();
799 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000800 case llvm::Triple::mips:
801 case llvm::Triple::mipsel:
802 case llvm::Triple::mips64:
803 case llvm::Triple::mips64el:
804 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
805 return ExprError();
806 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000807 case llvm::Triple::systemz:
808 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
809 return ExprError();
810 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000811 case llvm::Triple::x86:
812 case llvm::Triple::x86_64:
813 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
814 return ExprError();
815 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000816 case llvm::Triple::ppc:
817 case llvm::Triple::ppc64:
818 case llvm::Triple::ppc64le:
819 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
820 return ExprError();
821 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000822 default:
823 break;
824 }
825 }
826
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000827 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000828}
829
Nate Begeman91e1fea2010-06-14 05:21:25 +0000830// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000831static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000832 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000833 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000834 switch (Type.getEltType()) {
835 case NeonTypeFlags::Int8:
836 case NeonTypeFlags::Poly8:
837 return shift ? 7 : (8 << IsQuad) - 1;
838 case NeonTypeFlags::Int16:
839 case NeonTypeFlags::Poly16:
840 return shift ? 15 : (4 << IsQuad) - 1;
841 case NeonTypeFlags::Int32:
842 return shift ? 31 : (2 << IsQuad) - 1;
843 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000844 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000845 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000846 case NeonTypeFlags::Poly128:
847 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000848 case NeonTypeFlags::Float16:
849 assert(!shift && "cannot shift float types!");
850 return (4 << IsQuad) - 1;
851 case NeonTypeFlags::Float32:
852 assert(!shift && "cannot shift float types!");
853 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000854 case NeonTypeFlags::Float64:
855 assert(!shift && "cannot shift float types!");
856 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000857 }
David Blaikie8a40f702012-01-17 06:56:22 +0000858 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000859}
860
Bob Wilsone4d77232011-11-08 05:04:11 +0000861/// getNeonEltType - Return the QualType corresponding to the elements of
862/// the vector type specified by the NeonTypeFlags. This is used to check
863/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000864static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000865 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000866 switch (Flags.getEltType()) {
867 case NeonTypeFlags::Int8:
868 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
869 case NeonTypeFlags::Int16:
870 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
871 case NeonTypeFlags::Int32:
872 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
873 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000874 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000875 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
876 else
877 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
878 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000879 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000880 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000881 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000882 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000883 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000884 if (IsInt64Long)
885 return Context.UnsignedLongTy;
886 else
887 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000888 case NeonTypeFlags::Poly128:
889 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000890 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000891 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000892 case NeonTypeFlags::Float32:
893 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000894 case NeonTypeFlags::Float64:
895 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000896 }
David Blaikie8a40f702012-01-17 06:56:22 +0000897 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000898}
899
Tim Northover12670412014-02-19 10:37:05 +0000900bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000901 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000902 uint64_t mask = 0;
903 unsigned TV = 0;
904 int PtrArgNum = -1;
905 bool HasConstPtr = false;
906 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000907#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000908#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000909#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000910 }
911
912 // For NEON intrinsics which are overloaded on vector element type, validate
913 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000914 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000915 if (mask) {
916 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
917 return true;
918
919 TV = Result.getLimitedValue(64);
920 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
921 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000922 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000923 }
924
925 if (PtrArgNum >= 0) {
926 // Check that pointer arguments have the specified type.
927 Expr *Arg = TheCall->getArg(PtrArgNum);
928 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
929 Arg = ICE->getSubExpr();
930 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
931 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000932
Tim Northovera2ee4332014-03-29 15:09:45 +0000933 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000934 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000935 bool IsInt64Long =
936 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
937 QualType EltTy =
938 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000939 if (HasConstPtr)
940 EltTy = EltTy.withConst();
941 QualType LHSTy = Context.getPointerType(EltTy);
942 AssignConvertType ConvTy;
943 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
944 if (RHS.isInvalid())
945 return true;
946 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
947 RHS.get(), AA_Assigning))
948 return true;
949 }
950
951 // For NEON intrinsics which take an immediate value as part of the
952 // instruction, range check them here.
953 unsigned i = 0, l = 0, u = 0;
954 switch (BuiltinID) {
955 default:
956 return false;
Tim Northover12670412014-02-19 10:37:05 +0000957#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000958#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000959#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000960 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000961
Richard Sandiford28940af2014-04-16 08:47:51 +0000962 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000963}
964
Tim Northovera2ee4332014-03-29 15:09:45 +0000965bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
966 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000967 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000968 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000969 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000970 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000971 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000972 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
973 BuiltinID == AArch64::BI__builtin_arm_strex ||
974 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000975 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000976 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000977 BuiltinID == ARM::BI__builtin_arm_ldaex ||
978 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
979 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000980
981 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
982
983 // Ensure that we have the proper number of arguments.
984 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
985 return true;
986
987 // Inspect the pointer argument of the atomic builtin. This should always be
988 // a pointer type, whose element is an integral scalar or pointer type.
989 // Because it is a pointer type, we don't have to worry about any implicit
990 // casts here.
991 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
992 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
993 if (PointerArgRes.isInvalid())
994 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000995 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000996
997 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
998 if (!pointerType) {
999 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1000 << PointerArg->getType() << PointerArg->getSourceRange();
1001 return true;
1002 }
1003
1004 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1005 // task is to insert the appropriate casts into the AST. First work out just
1006 // what the appropriate type is.
1007 QualType ValType = pointerType->getPointeeType();
1008 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1009 if (IsLdrex)
1010 AddrType.addConst();
1011
1012 // Issue a warning if the cast is dodgy.
1013 CastKind CastNeeded = CK_NoOp;
1014 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1015 CastNeeded = CK_BitCast;
1016 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1017 << PointerArg->getType()
1018 << Context.getPointerType(AddrType)
1019 << AA_Passing << PointerArg->getSourceRange();
1020 }
1021
1022 // Finally, do the cast and replace the argument with the corrected version.
1023 AddrType = Context.getPointerType(AddrType);
1024 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1025 if (PointerArgRes.isInvalid())
1026 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001027 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +00001028
1029 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1030
1031 // In general, we allow ints, floats and pointers to be loaded and stored.
1032 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1033 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1034 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1035 << PointerArg->getType() << PointerArg->getSourceRange();
1036 return true;
1037 }
1038
1039 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +00001040 if (Context.getTypeSize(ValType) > MaxWidth) {
1041 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +00001042 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1043 << PointerArg->getType() << PointerArg->getSourceRange();
1044 return true;
1045 }
1046
1047 switch (ValType.getObjCLifetime()) {
1048 case Qualifiers::OCL_None:
1049 case Qualifiers::OCL_ExplicitNone:
1050 // okay
1051 break;
1052
1053 case Qualifiers::OCL_Weak:
1054 case Qualifiers::OCL_Strong:
1055 case Qualifiers::OCL_Autoreleasing:
1056 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1057 << ValType << PointerArg->getSourceRange();
1058 return true;
1059 }
1060
Tim Northover6aacd492013-07-16 09:47:53 +00001061 if (IsLdrex) {
1062 TheCall->setType(ValType);
1063 return false;
1064 }
1065
1066 // Initialize the argument to be stored.
1067 ExprResult ValArg = TheCall->getArg(0);
1068 InitializedEntity Entity = InitializedEntity::InitializeParameter(
1069 Context, ValType, /*consume*/ false);
1070 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1071 if (ValArg.isInvalid())
1072 return true;
Tim Northover6aacd492013-07-16 09:47:53 +00001073 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +00001074
1075 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1076 // but the custom checker bypasses all default analysis.
1077 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +00001078 return false;
1079}
1080
Nate Begeman4904e322010-06-08 02:47:44 +00001081bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +00001082 llvm::APSInt Result;
1083
Tim Northover6aacd492013-07-16 09:47:53 +00001084 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001085 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1086 BuiltinID == ARM::BI__builtin_arm_strex ||
1087 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001088 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +00001089 }
1090
Yi Kong26d104a2014-08-13 19:18:14 +00001091 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1092 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1093 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1094 }
1095
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001096 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1097 BuiltinID == ARM::BI__builtin_arm_wsr64)
1098 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1099
1100 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1101 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1102 BuiltinID == ARM::BI__builtin_arm_wsr ||
1103 BuiltinID == ARM::BI__builtin_arm_wsrp)
1104 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1105
Tim Northover12670412014-02-19 10:37:05 +00001106 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1107 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +00001108
Yi Kong4efadfb2014-07-03 16:01:25 +00001109 // For intrinsics which take an immediate value as part of the instruction,
1110 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +00001111 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +00001112 switch (BuiltinID) {
1113 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +00001114 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1115 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +00001116 case ARM::BI__builtin_arm_vcvtr_f:
1117 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +00001118 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +00001119 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +00001120 case ARM::BI__builtin_arm_isb:
1121 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001122 }
Nate Begemand773fe62010-06-13 04:47:52 +00001123
Nate Begemanf568b072010-08-03 21:32:34 +00001124 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +00001125 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001126}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001127
Tim Northover573cbee2014-05-24 12:52:07 +00001128bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +00001129 CallExpr *TheCall) {
1130 llvm::APSInt Result;
1131
Tim Northover573cbee2014-05-24 12:52:07 +00001132 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +00001133 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1134 BuiltinID == AArch64::BI__builtin_arm_strex ||
1135 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +00001136 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1137 }
1138
Yi Konga5548432014-08-13 19:18:20 +00001139 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1140 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1141 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1142 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1143 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1144 }
1145
Luke Cheeseman59b2d832015-06-15 17:51:01 +00001146 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1147 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1148 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
1149
1150 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1151 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1152 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1153 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1154 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1155
Tim Northovera2ee4332014-03-29 15:09:45 +00001156 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1157 return true;
1158
Yi Kong19a29ac2014-07-17 10:52:06 +00001159 // For intrinsics which take an immediate value as part of the instruction,
1160 // range check them here.
1161 unsigned i = 0, l = 0, u = 0;
1162 switch (BuiltinID) {
1163 default: return false;
1164 case AArch64::BI__builtin_arm_dmb:
1165 case AArch64::BI__builtin_arm_dsb:
1166 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1167 }
1168
Yi Kong19a29ac2014-07-17 10:52:06 +00001169 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +00001170}
1171
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001172bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1173 unsigned i = 0, l = 0, u = 0;
1174 switch (BuiltinID) {
1175 default: return false;
1176 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1177 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +00001178 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1179 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1180 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1181 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1182 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +00001183 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001184
Richard Sandiford28940af2014-04-16 08:47:51 +00001185 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +00001186}
1187
Kit Bartone50adcb2015-03-30 19:40:59 +00001188bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1189 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +00001190 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1191 BuiltinID == PPC::BI__builtin_divdeu ||
1192 BuiltinID == PPC::BI__builtin_bpermd;
1193 bool IsTarget64Bit = Context.getTargetInfo()
1194 .getTypeWidth(Context
1195 .getTargetInfo()
1196 .getIntPtrType()) == 64;
1197 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1198 BuiltinID == PPC::BI__builtin_divweu ||
1199 BuiltinID == PPC::BI__builtin_divde ||
1200 BuiltinID == PPC::BI__builtin_divdeu;
1201
1202 if (Is64BitBltin && !IsTarget64Bit)
1203 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1204 << TheCall->getSourceRange();
1205
1206 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1207 (BuiltinID == PPC::BI__builtin_bpermd &&
1208 !Context.getTargetInfo().hasFeature("bpermd")))
1209 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1210 << TheCall->getSourceRange();
1211
Kit Bartone50adcb2015-03-30 19:40:59 +00001212 switch (BuiltinID) {
1213 default: return false;
1214 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1215 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1216 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1217 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1218 case PPC::BI__builtin_tbegin:
1219 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1220 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1221 case PPC::BI__builtin_tabortwc:
1222 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1223 case PPC::BI__builtin_tabortwci:
1224 case PPC::BI__builtin_tabortdci:
1225 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1226 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1227 }
1228 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1229}
1230
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001231bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1232 CallExpr *TheCall) {
1233 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1234 Expr *Arg = TheCall->getArg(0);
1235 llvm::APSInt AbortCode(32);
1236 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1237 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1238 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1239 << Arg->getSourceRange();
1240 }
1241
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001242 // For intrinsics which take an immediate value as part of the instruction,
1243 // range check them here.
1244 unsigned i = 0, l = 0, u = 0;
1245 switch (BuiltinID) {
1246 default: return false;
1247 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1248 case SystemZ::BI__builtin_s390_verimb:
1249 case SystemZ::BI__builtin_s390_verimh:
1250 case SystemZ::BI__builtin_s390_verimf:
1251 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1252 case SystemZ::BI__builtin_s390_vfaeb:
1253 case SystemZ::BI__builtin_s390_vfaeh:
1254 case SystemZ::BI__builtin_s390_vfaef:
1255 case SystemZ::BI__builtin_s390_vfaebs:
1256 case SystemZ::BI__builtin_s390_vfaehs:
1257 case SystemZ::BI__builtin_s390_vfaefs:
1258 case SystemZ::BI__builtin_s390_vfaezb:
1259 case SystemZ::BI__builtin_s390_vfaezh:
1260 case SystemZ::BI__builtin_s390_vfaezf:
1261 case SystemZ::BI__builtin_s390_vfaezbs:
1262 case SystemZ::BI__builtin_s390_vfaezhs:
1263 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1264 case SystemZ::BI__builtin_s390_vfidb:
1265 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1266 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1267 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1268 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1269 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1270 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1271 case SystemZ::BI__builtin_s390_vstrcb:
1272 case SystemZ::BI__builtin_s390_vstrch:
1273 case SystemZ::BI__builtin_s390_vstrcf:
1274 case SystemZ::BI__builtin_s390_vstrczb:
1275 case SystemZ::BI__builtin_s390_vstrczh:
1276 case SystemZ::BI__builtin_s390_vstrczf:
1277 case SystemZ::BI__builtin_s390_vstrcbs:
1278 case SystemZ::BI__builtin_s390_vstrchs:
1279 case SystemZ::BI__builtin_s390_vstrcfs:
1280 case SystemZ::BI__builtin_s390_vstrczbs:
1281 case SystemZ::BI__builtin_s390_vstrczhs:
1282 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1283 }
1284 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001285}
1286
Craig Topper5ba2c502015-11-07 08:08:31 +00001287/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1288/// This checks that the target supports __builtin_cpu_supports and
1289/// that the string argument is constant and valid.
1290static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1291 Expr *Arg = TheCall->getArg(0);
1292
1293 // Check if the argument is a string literal.
1294 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1295 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1296 << Arg->getSourceRange();
1297
1298 // Check the contents of the string.
1299 StringRef Feature =
1300 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1301 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1302 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1303 << Arg->getSourceRange();
1304 return false;
1305}
1306
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001307bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001308 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001309 switch (BuiltinID) {
Richard Trieucc3949d2016-02-18 22:34:54 +00001310 default:
1311 return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001312 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001313 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001314 case X86::BI__builtin_ms_va_start:
1315 return SemaBuiltinMSVAStart(TheCall);
Richard Trieucc3949d2016-02-18 22:34:54 +00001316 case X86::BI_mm_prefetch:
1317 i = 1;
1318 l = 0;
1319 u = 3;
1320 break;
1321 case X86::BI__builtin_ia32_sha1rnds4:
1322 i = 2;
1323 l = 0;
1324 u = 3;
1325 break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001326 case X86::BI__builtin_ia32_vpermil2pd:
1327 case X86::BI__builtin_ia32_vpermil2pd256:
1328 case X86::BI__builtin_ia32_vpermil2ps:
Richard Trieucc3949d2016-02-18 22:34:54 +00001329 case X86::BI__builtin_ia32_vpermil2ps256:
1330 i = 3;
1331 l = 0;
1332 u = 3;
1333 break;
Craig Topper95b0d732015-01-25 23:30:05 +00001334 case X86::BI__builtin_ia32_cmpb128_mask:
1335 case X86::BI__builtin_ia32_cmpw128_mask:
1336 case X86::BI__builtin_ia32_cmpd128_mask:
1337 case X86::BI__builtin_ia32_cmpq128_mask:
1338 case X86::BI__builtin_ia32_cmpb256_mask:
1339 case X86::BI__builtin_ia32_cmpw256_mask:
1340 case X86::BI__builtin_ia32_cmpd256_mask:
1341 case X86::BI__builtin_ia32_cmpq256_mask:
1342 case X86::BI__builtin_ia32_cmpb512_mask:
1343 case X86::BI__builtin_ia32_cmpw512_mask:
1344 case X86::BI__builtin_ia32_cmpd512_mask:
1345 case X86::BI__builtin_ia32_cmpq512_mask:
1346 case X86::BI__builtin_ia32_ucmpb128_mask:
1347 case X86::BI__builtin_ia32_ucmpw128_mask:
1348 case X86::BI__builtin_ia32_ucmpd128_mask:
1349 case X86::BI__builtin_ia32_ucmpq128_mask:
1350 case X86::BI__builtin_ia32_ucmpb256_mask:
1351 case X86::BI__builtin_ia32_ucmpw256_mask:
1352 case X86::BI__builtin_ia32_ucmpd256_mask:
1353 case X86::BI__builtin_ia32_ucmpq256_mask:
1354 case X86::BI__builtin_ia32_ucmpb512_mask:
1355 case X86::BI__builtin_ia32_ucmpw512_mask:
1356 case X86::BI__builtin_ia32_ucmpd512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001357 case X86::BI__builtin_ia32_ucmpq512_mask:
1358 i = 2;
1359 l = 0;
1360 u = 7;
1361 break;
Craig Topper16015252015-01-31 06:31:23 +00001362 case X86::BI__builtin_ia32_roundps:
1363 case X86::BI__builtin_ia32_roundpd:
1364 case X86::BI__builtin_ia32_roundps256:
Richard Trieucc3949d2016-02-18 22:34:54 +00001365 case X86::BI__builtin_ia32_roundpd256:
1366 i = 1;
1367 l = 0;
1368 u = 15;
1369 break;
Craig Topper16015252015-01-31 06:31:23 +00001370 case X86::BI__builtin_ia32_roundss:
Richard Trieucc3949d2016-02-18 22:34:54 +00001371 case X86::BI__builtin_ia32_roundsd:
1372 i = 2;
1373 l = 0;
1374 u = 15;
1375 break;
Craig Topper16015252015-01-31 06:31:23 +00001376 case X86::BI__builtin_ia32_cmpps:
1377 case X86::BI__builtin_ia32_cmpss:
1378 case X86::BI__builtin_ia32_cmppd:
1379 case X86::BI__builtin_ia32_cmpsd:
1380 case X86::BI__builtin_ia32_cmpps256:
1381 case X86::BI__builtin_ia32_cmppd256:
1382 case X86::BI__builtin_ia32_cmpps512_mask:
Richard Trieucc3949d2016-02-18 22:34:54 +00001383 case X86::BI__builtin_ia32_cmppd512_mask:
1384 i = 2;
1385 l = 0;
1386 u = 31;
1387 break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001388 case X86::BI__builtin_ia32_vpcomub:
1389 case X86::BI__builtin_ia32_vpcomuw:
1390 case X86::BI__builtin_ia32_vpcomud:
1391 case X86::BI__builtin_ia32_vpcomuq:
1392 case X86::BI__builtin_ia32_vpcomb:
1393 case X86::BI__builtin_ia32_vpcomw:
1394 case X86::BI__builtin_ia32_vpcomd:
Richard Trieucc3949d2016-02-18 22:34:54 +00001395 case X86::BI__builtin_ia32_vpcomq:
1396 i = 2;
1397 l = 0;
1398 u = 7;
1399 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001400 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001401 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001402}
1403
Richard Smith55ce3522012-06-25 20:30:08 +00001404/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1405/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1406/// Returns true when the format fits the function and the FormatStringInfo has
1407/// been populated.
1408bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1409 FormatStringInfo *FSI) {
1410 FSI->HasVAListArg = Format->getFirstArg() == 0;
1411 FSI->FormatIdx = Format->getFormatIdx() - 1;
1412 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001413
Richard Smith55ce3522012-06-25 20:30:08 +00001414 // The way the format attribute works in GCC, the implicit this argument
1415 // of member functions is counted. However, it doesn't appear in our own
1416 // lists, so decrement format_idx in that case.
1417 if (IsCXXMember) {
1418 if(FSI->FormatIdx == 0)
1419 return false;
1420 --FSI->FormatIdx;
1421 if (FSI->FirstDataArg != 0)
1422 --FSI->FirstDataArg;
1423 }
1424 return true;
1425}
Mike Stump11289f42009-09-09 15:08:12 +00001426
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001427/// Checks if a the given expression evaluates to null.
1428///
1429/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001430static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001431 // If the expression has non-null type, it doesn't evaluate to null.
1432 if (auto nullability
1433 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1434 if (*nullability == NullabilityKind::NonNull)
1435 return false;
1436 }
1437
Ted Kremeneka146db32014-01-17 06:24:47 +00001438 // As a special case, transparent unions initialized with zero are
1439 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001440 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001441 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1442 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001443 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001444 if (const InitListExpr *ILE =
1445 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001446 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001447 }
1448
1449 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001450 return (!Expr->isValueDependent() &&
1451 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1452 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001453}
1454
1455static void CheckNonNullArgument(Sema &S,
1456 const Expr *ArgExpr,
1457 SourceLocation CallSiteLoc) {
1458 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001459 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1460 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001461}
1462
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001463bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1464 FormatStringInfo FSI;
1465 if ((GetFormatStringType(Format) == FST_NSString) &&
1466 getFormatStringInfo(Format, false, &FSI)) {
1467 Idx = FSI.FormatIdx;
1468 return true;
1469 }
1470 return false;
1471}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001472/// \brief Diagnose use of %s directive in an NSString which is being passed
1473/// as formatting string to formatting method.
1474static void
1475DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1476 const NamedDecl *FDecl,
1477 Expr **Args,
1478 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001479 unsigned Idx = 0;
1480 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001481 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1482 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001483 Idx = 2;
1484 Format = true;
1485 }
1486 else
1487 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1488 if (S.GetFormatNSStringIdx(I, Idx)) {
1489 Format = true;
1490 break;
1491 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001492 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001493 if (!Format || NumArgs <= Idx)
1494 return;
1495 const Expr *FormatExpr = Args[Idx];
1496 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1497 FormatExpr = CSCE->getSubExpr();
1498 const StringLiteral *FormatString;
1499 if (const ObjCStringLiteral *OSL =
1500 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1501 FormatString = OSL->getString();
1502 else
1503 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1504 if (!FormatString)
1505 return;
1506 if (S.FormatStringHasSArg(FormatString)) {
1507 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1508 << "%s" << 1 << 1;
1509 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1510 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001511 }
1512}
1513
Douglas Gregorb4866e82015-06-19 18:13:19 +00001514/// Determine whether the given type has a non-null nullability annotation.
1515static bool isNonNullType(ASTContext &ctx, QualType type) {
1516 if (auto nullability = type->getNullability(ctx))
1517 return *nullability == NullabilityKind::NonNull;
1518
1519 return false;
1520}
1521
Ted Kremenek2bc73332014-01-17 06:24:43 +00001522static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001523 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001524 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001525 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001526 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001527 assert((FDecl || Proto) && "Need a function declaration or prototype");
1528
Ted Kremenek9aedc152014-01-17 06:24:56 +00001529 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001530 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001531 if (FDecl) {
1532 // Handle the nonnull attribute on the function/method declaration itself.
1533 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1534 if (!NonNull->args_size()) {
1535 // Easy case: all pointer arguments are nonnull.
1536 for (const auto *Arg : Args)
1537 if (S.isValidPointerAttrType(Arg->getType()))
1538 CheckNonNullArgument(S, Arg, CallSiteLoc);
1539 return;
1540 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001541
Douglas Gregorb4866e82015-06-19 18:13:19 +00001542 for (unsigned Val : NonNull->args()) {
1543 if (Val >= Args.size())
1544 continue;
1545 if (NonNullArgs.empty())
1546 NonNullArgs.resize(Args.size());
1547 NonNullArgs.set(Val);
1548 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001549 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001550 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001551
Douglas Gregorb4866e82015-06-19 18:13:19 +00001552 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1553 // Handle the nonnull attribute on the parameters of the
1554 // function/method.
1555 ArrayRef<ParmVarDecl*> parms;
1556 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1557 parms = FD->parameters();
1558 else
1559 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1560
1561 unsigned ParamIndex = 0;
1562 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1563 I != E; ++I, ++ParamIndex) {
1564 const ParmVarDecl *PVD = *I;
1565 if (PVD->hasAttr<NonNullAttr>() ||
1566 isNonNullType(S.Context, PVD->getType())) {
1567 if (NonNullArgs.empty())
1568 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001569
Douglas Gregorb4866e82015-06-19 18:13:19 +00001570 NonNullArgs.set(ParamIndex);
1571 }
1572 }
1573 } else {
1574 // If we have a non-function, non-method declaration but no
1575 // function prototype, try to dig out the function prototype.
1576 if (!Proto) {
1577 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1578 QualType type = VD->getType().getNonReferenceType();
1579 if (auto pointerType = type->getAs<PointerType>())
1580 type = pointerType->getPointeeType();
1581 else if (auto blockType = type->getAs<BlockPointerType>())
1582 type = blockType->getPointeeType();
1583 // FIXME: data member pointers?
1584
1585 // Dig out the function prototype, if there is one.
1586 Proto = type->getAs<FunctionProtoType>();
1587 }
1588 }
1589
1590 // Fill in non-null argument information from the nullability
1591 // information on the parameter types (if we have them).
1592 if (Proto) {
1593 unsigned Index = 0;
1594 for (auto paramType : Proto->getParamTypes()) {
1595 if (isNonNullType(S.Context, paramType)) {
1596 if (NonNullArgs.empty())
1597 NonNullArgs.resize(Args.size());
1598
1599 NonNullArgs.set(Index);
1600 }
1601
1602 ++Index;
1603 }
1604 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001605 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001606
Douglas Gregorb4866e82015-06-19 18:13:19 +00001607 // Check for non-null arguments.
1608 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1609 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001610 if (NonNullArgs[ArgIndex])
1611 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001612 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001613}
1614
Richard Smith55ce3522012-06-25 20:30:08 +00001615/// Handles the checks for format strings, non-POD arguments to vararg
1616/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001617void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1618 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001619 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001620 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001621 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001622 if (CurContext->isDependentContext())
1623 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001624
Ted Kremenekb8176da2010-09-09 04:33:05 +00001625 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001626 llvm::SmallBitVector CheckedVarArgs;
1627 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001628 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001629 // Only create vector if there are format attributes.
1630 CheckedVarArgs.resize(Args.size());
1631
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001632 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001633 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001634 }
Richard Smithd7293d72013-08-05 18:49:43 +00001635 }
Richard Smith55ce3522012-06-25 20:30:08 +00001636
1637 // Refuse POD arguments that weren't caught by the format string
1638 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001639 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001640 unsigned NumParams = Proto ? Proto->getNumParams()
1641 : FDecl && isa<FunctionDecl>(FDecl)
1642 ? cast<FunctionDecl>(FDecl)->getNumParams()
1643 : FDecl && isa<ObjCMethodDecl>(FDecl)
1644 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1645 : 0;
1646
Alp Toker9cacbab2014-01-20 20:26:09 +00001647 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001648 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001649 if (const Expr *Arg = Args[ArgIdx]) {
1650 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1651 checkVariadicArgument(Arg, CallType);
1652 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001653 }
Richard Smithd7293d72013-08-05 18:49:43 +00001654 }
Mike Stump11289f42009-09-09 15:08:12 +00001655
Douglas Gregorb4866e82015-06-19 18:13:19 +00001656 if (FDecl || Proto) {
1657 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001658
Richard Trieu41bc0992013-06-22 00:20:41 +00001659 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001660 if (FDecl) {
1661 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1662 CheckArgumentWithTypeTag(I, Args.data());
1663 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001664 }
Richard Smith55ce3522012-06-25 20:30:08 +00001665}
1666
1667/// CheckConstructorCall - Check a constructor call for correctness and safety
1668/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001669void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1670 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001671 const FunctionProtoType *Proto,
1672 SourceLocation Loc) {
1673 VariadicCallType CallType =
1674 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001675 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1676 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001677}
1678
1679/// CheckFunctionCall - Check a direct function call for various correctness
1680/// and safety properties not strictly enforced by the C type system.
1681bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1682 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001683 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1684 isa<CXXMethodDecl>(FDecl);
1685 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1686 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001687 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1688 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001689 Expr** Args = TheCall->getArgs();
1690 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001691 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001692 // If this is a call to a member operator, hide the first argument
1693 // from checkCall.
1694 // FIXME: Our choice of AST representation here is less than ideal.
1695 ++Args;
1696 --NumArgs;
1697 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001698 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001699 IsMemberFunction, TheCall->getRParenLoc(),
1700 TheCall->getCallee()->getSourceRange(), CallType);
1701
1702 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1703 // None of the checks below are needed for functions that don't have
1704 // simple names (e.g., C++ conversion functions).
1705 if (!FnInfo)
1706 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001707
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001708 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001709 if (getLangOpts().ObjC1)
1710 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001711
Anna Zaks22122702012-01-17 00:37:07 +00001712 unsigned CMId = FDecl->getMemoryFunctionKind();
1713 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001714 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001715
Anna Zaks201d4892012-01-13 21:52:01 +00001716 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001717 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001718 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001719 else if (CMId == Builtin::BIstrncat)
1720 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001721 else
Anna Zaks22122702012-01-17 00:37:07 +00001722 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001723
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001724 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001725}
1726
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001727bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001728 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001729 VariadicCallType CallType =
1730 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001731
Douglas Gregorb4866e82015-06-19 18:13:19 +00001732 checkCall(Method, nullptr, Args,
1733 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1734 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001735
1736 return false;
1737}
1738
Richard Trieu664c4c62013-06-20 21:03:13 +00001739bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1740 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001741 QualType Ty;
1742 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001743 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001744 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001745 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001746 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001747 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001748
Douglas Gregorb4866e82015-06-19 18:13:19 +00001749 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1750 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001751 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001752
Richard Trieu664c4c62013-06-20 21:03:13 +00001753 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001754 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001755 CallType = VariadicDoesNotApply;
1756 } else if (Ty->isBlockPointerType()) {
1757 CallType = VariadicBlock;
1758 } else { // Ty->isFunctionPointerType()
1759 CallType = VariadicFunction;
1760 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001761
Douglas Gregorb4866e82015-06-19 18:13:19 +00001762 checkCall(NDecl, Proto,
1763 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1764 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001765 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001766
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001767 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001768}
1769
Richard Trieu41bc0992013-06-22 00:20:41 +00001770/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1771/// such as function pointers returned from functions.
1772bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001773 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001774 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001775 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001776 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001777 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001778 TheCall->getCallee()->getSourceRange(), CallType);
1779
1780 return false;
1781}
1782
Tim Northovere94a34c2014-03-11 10:49:14 +00001783static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1784 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1785 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1786 return false;
1787
1788 switch (Op) {
1789 case AtomicExpr::AO__c11_atomic_init:
1790 llvm_unreachable("There is no ordering argument for an init");
1791
1792 case AtomicExpr::AO__c11_atomic_load:
1793 case AtomicExpr::AO__atomic_load_n:
1794 case AtomicExpr::AO__atomic_load:
1795 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1796 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1797
1798 case AtomicExpr::AO__c11_atomic_store:
1799 case AtomicExpr::AO__atomic_store:
1800 case AtomicExpr::AO__atomic_store_n:
1801 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1802 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1803 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1804
1805 default:
1806 return true;
1807 }
1808}
1809
Richard Smithfeea8832012-04-12 05:08:17 +00001810ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1811 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001812 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1813 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001814
Richard Smithfeea8832012-04-12 05:08:17 +00001815 // All these operations take one of the following forms:
1816 enum {
1817 // C __c11_atomic_init(A *, C)
1818 Init,
1819 // C __c11_atomic_load(A *, int)
1820 Load,
1821 // void __atomic_load(A *, CP, int)
1822 Copy,
1823 // C __c11_atomic_add(A *, M, int)
1824 Arithmetic,
1825 // C __atomic_exchange_n(A *, CP, int)
1826 Xchg,
1827 // void __atomic_exchange(A *, C *, CP, int)
1828 GNUXchg,
1829 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1830 C11CmpXchg,
1831 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1832 GNUCmpXchg
1833 } Form = Init;
1834 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1835 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1836 // where:
1837 // C is an appropriate type,
1838 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1839 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1840 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1841 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001842
Gabor Horvath98bd0982015-03-16 09:59:54 +00001843 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1844 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1845 AtomicExpr::AO__atomic_load,
1846 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001847 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1848 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1849 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1850 Op == AtomicExpr::AO__atomic_store_n ||
1851 Op == AtomicExpr::AO__atomic_exchange_n ||
1852 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1853 bool IsAddSub = false;
1854
1855 switch (Op) {
1856 case AtomicExpr::AO__c11_atomic_init:
1857 Form = Init;
1858 break;
1859
1860 case AtomicExpr::AO__c11_atomic_load:
1861 case AtomicExpr::AO__atomic_load_n:
1862 Form = Load;
1863 break;
1864
1865 case AtomicExpr::AO__c11_atomic_store:
1866 case AtomicExpr::AO__atomic_load:
1867 case AtomicExpr::AO__atomic_store:
1868 case AtomicExpr::AO__atomic_store_n:
1869 Form = Copy;
1870 break;
1871
1872 case AtomicExpr::AO__c11_atomic_fetch_add:
1873 case AtomicExpr::AO__c11_atomic_fetch_sub:
1874 case AtomicExpr::AO__atomic_fetch_add:
1875 case AtomicExpr::AO__atomic_fetch_sub:
1876 case AtomicExpr::AO__atomic_add_fetch:
1877 case AtomicExpr::AO__atomic_sub_fetch:
1878 IsAddSub = true;
1879 // Fall through.
1880 case AtomicExpr::AO__c11_atomic_fetch_and:
1881 case AtomicExpr::AO__c11_atomic_fetch_or:
1882 case AtomicExpr::AO__c11_atomic_fetch_xor:
1883 case AtomicExpr::AO__atomic_fetch_and:
1884 case AtomicExpr::AO__atomic_fetch_or:
1885 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001886 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001887 case AtomicExpr::AO__atomic_and_fetch:
1888 case AtomicExpr::AO__atomic_or_fetch:
1889 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001890 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001891 Form = Arithmetic;
1892 break;
1893
1894 case AtomicExpr::AO__c11_atomic_exchange:
1895 case AtomicExpr::AO__atomic_exchange_n:
1896 Form = Xchg;
1897 break;
1898
1899 case AtomicExpr::AO__atomic_exchange:
1900 Form = GNUXchg;
1901 break;
1902
1903 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1904 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1905 Form = C11CmpXchg;
1906 break;
1907
1908 case AtomicExpr::AO__atomic_compare_exchange:
1909 case AtomicExpr::AO__atomic_compare_exchange_n:
1910 Form = GNUCmpXchg;
1911 break;
1912 }
1913
1914 // Check we have the right number of arguments.
1915 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001916 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001917 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001918 << TheCall->getCallee()->getSourceRange();
1919 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001920 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1921 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001922 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001923 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001924 << TheCall->getCallee()->getSourceRange();
1925 return ExprError();
1926 }
1927
Richard Smithfeea8832012-04-12 05:08:17 +00001928 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001929 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001930 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1931 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1932 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001933 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001934 << Ptr->getType() << Ptr->getSourceRange();
1935 return ExprError();
1936 }
1937
Richard Smithfeea8832012-04-12 05:08:17 +00001938 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1939 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1940 QualType ValType = AtomTy; // 'C'
1941 if (IsC11) {
1942 if (!AtomTy->isAtomicType()) {
1943 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1944 << Ptr->getType() << Ptr->getSourceRange();
1945 return ExprError();
1946 }
Richard Smithe00921a2012-09-15 06:09:58 +00001947 if (AtomTy.isConstQualified()) {
1948 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1949 << Ptr->getType() << Ptr->getSourceRange();
1950 return ExprError();
1951 }
Richard Smithfeea8832012-04-12 05:08:17 +00001952 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001953 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1954 if (ValType.isConstQualified()) {
1955 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1956 << Ptr->getType() << Ptr->getSourceRange();
1957 return ExprError();
1958 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001959 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001960
Richard Smithfeea8832012-04-12 05:08:17 +00001961 // For an arithmetic operation, the implied arithmetic must be well-formed.
1962 if (Form == Arithmetic) {
1963 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1964 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1965 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1966 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1967 return ExprError();
1968 }
1969 if (!IsAddSub && !ValType->isIntegerType()) {
1970 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1971 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1972 return ExprError();
1973 }
David Majnemere85cff82015-01-28 05:48:06 +00001974 if (IsC11 && ValType->isPointerType() &&
1975 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1976 diag::err_incomplete_type)) {
1977 return ExprError();
1978 }
Richard Smithfeea8832012-04-12 05:08:17 +00001979 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1980 // For __atomic_*_n operations, the value type must be a scalar integral or
1981 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001982 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001983 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1984 return ExprError();
1985 }
1986
Eli Friedmanaa769812013-09-11 03:49:34 +00001987 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1988 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001989 // For GNU atomics, require a trivially-copyable type. This is not part of
1990 // the GNU atomics specification, but we enforce it for sanity.
1991 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001992 << Ptr->getType() << Ptr->getSourceRange();
1993 return ExprError();
1994 }
1995
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001996 switch (ValType.getObjCLifetime()) {
1997 case Qualifiers::OCL_None:
1998 case Qualifiers::OCL_ExplicitNone:
1999 // okay
2000 break;
2001
2002 case Qualifiers::OCL_Weak:
2003 case Qualifiers::OCL_Strong:
2004 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00002005 // FIXME: Can this happen? By this point, ValType should be known
2006 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002007 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2008 << ValType << Ptr->getSourceRange();
2009 return ExprError();
2010 }
2011
David Majnemerc6eb6502015-06-03 00:26:35 +00002012 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
2013 // volatile-ness of the pointee-type inject itself into the result or the
2014 // other operands.
2015 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002016 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00002017 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002018 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00002019 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002020 ResultType = Context.BoolTy;
2021
Richard Smithfeea8832012-04-12 05:08:17 +00002022 // The type of a parameter passed 'by value'. In the GNU atomics, such
2023 // arguments are actually passed as pointers.
2024 QualType ByValType = ValType; // 'CP'
2025 if (!IsC11 && !IsN)
2026 ByValType = Ptr->getType();
2027
Eric Fiseliera3a7c562015-10-04 00:11:02 +00002028 // FIXME: __atomic_load allows the first argument to be a a pointer to const
2029 // but not the second argument. We need to manually remove possible const
2030 // qualifiers.
2031
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002032 // The first argument --- the pointer --- has a fixed type; we
2033 // deduce the types of the rest of the arguments accordingly. Walk
2034 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00002035 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002036 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00002037 if (i < NumVals[Form] + 1) {
2038 switch (i) {
2039 case 1:
2040 // The second argument is the non-atomic operand. For arithmetic, this
2041 // is always passed by value, and for a compare_exchange it is always
2042 // passed by address. For the rest, GNU uses by-address and C11 uses
2043 // by-value.
2044 assert(Form != Load);
2045 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2046 Ty = ValType;
2047 else if (Form == Copy || Form == Xchg)
2048 Ty = ByValType;
2049 else if (Form == Arithmetic)
2050 Ty = Context.getPointerDiffType();
Anastasia Stulova76fd1052015-12-22 15:14:54 +00002051 else {
2052 Expr *ValArg = TheCall->getArg(i);
2053 unsigned AS = 0;
2054 // Keep address space of non-atomic pointer type.
2055 if (const PointerType *PtrTy =
2056 ValArg->getType()->getAs<PointerType>()) {
2057 AS = PtrTy->getPointeeType().getAddressSpace();
2058 }
2059 Ty = Context.getPointerType(
2060 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2061 }
Richard Smithfeea8832012-04-12 05:08:17 +00002062 break;
2063 case 2:
2064 // The third argument to compare_exchange / GNU exchange is a
2065 // (pointer to a) desired value.
2066 Ty = ByValType;
2067 break;
2068 case 3:
2069 // The fourth argument to GNU compare_exchange is a 'weak' flag.
2070 Ty = Context.BoolTy;
2071 break;
2072 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002073 } else {
2074 // The order(s) are always converted to int.
2075 Ty = Context.IntTy;
2076 }
Richard Smithfeea8832012-04-12 05:08:17 +00002077
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002078 InitializedEntity Entity =
2079 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00002080 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002081 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2082 if (Arg.isInvalid())
2083 return true;
2084 TheCall->setArg(i, Arg.get());
2085 }
2086
Richard Smithfeea8832012-04-12 05:08:17 +00002087 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002088 SmallVector<Expr*, 5> SubExprs;
2089 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00002090 switch (Form) {
2091 case Init:
2092 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00002093 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002094 break;
2095 case Load:
2096 SubExprs.push_back(TheCall->getArg(1)); // Order
2097 break;
2098 case Copy:
2099 case Arithmetic:
2100 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002101 SubExprs.push_back(TheCall->getArg(2)); // Order
2102 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00002103 break;
2104 case GNUXchg:
2105 // Note, AtomicExpr::getVal2() has a special case for this atomic.
2106 SubExprs.push_back(TheCall->getArg(3)); // Order
2107 SubExprs.push_back(TheCall->getArg(1)); // Val1
2108 SubExprs.push_back(TheCall->getArg(2)); // Val2
2109 break;
2110 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002111 SubExprs.push_back(TheCall->getArg(3)); // Order
2112 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002113 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00002114 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00002115 break;
2116 case GNUCmpXchg:
2117 SubExprs.push_back(TheCall->getArg(4)); // Order
2118 SubExprs.push_back(TheCall->getArg(1)); // Val1
2119 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2120 SubExprs.push_back(TheCall->getArg(2)); // Val2
2121 SubExprs.push_back(TheCall->getArg(3)); // Weak
2122 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002123 }
Tim Northovere94a34c2014-03-11 10:49:14 +00002124
2125 if (SubExprs.size() >= 2 && Form != Init) {
2126 llvm::APSInt Result(32);
2127 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2128 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00002129 Diag(SubExprs[1]->getLocStart(),
2130 diag::warn_atomic_op_has_invalid_memory_order)
2131 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00002132 }
2133
Fariborz Jahanian615de762013-05-28 17:37:39 +00002134 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2135 SubExprs, ResultType, Op,
2136 TheCall->getRParenLoc());
2137
2138 if ((Op == AtomicExpr::AO__c11_atomic_load ||
2139 (Op == AtomicExpr::AO__c11_atomic_store)) &&
2140 Context.AtomicUsesUnsupportedLibcall(AE))
2141 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2142 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00002143
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002144 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002145}
2146
John McCall29ad95b2011-08-27 01:09:30 +00002147/// checkBuiltinArgument - Given a call to a builtin function, perform
2148/// normal type-checking on the given argument, updating the call in
2149/// place. This is useful when a builtin function requires custom
2150/// type-checking for some of its arguments but not necessarily all of
2151/// them.
2152///
2153/// Returns true on error.
2154static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2155 FunctionDecl *Fn = E->getDirectCallee();
2156 assert(Fn && "builtin call without direct callee!");
2157
2158 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2159 InitializedEntity Entity =
2160 InitializedEntity::InitializeParameter(S.Context, Param);
2161
2162 ExprResult Arg = E->getArg(0);
2163 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2164 if (Arg.isInvalid())
2165 return true;
2166
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002167 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00002168 return false;
2169}
2170
Chris Lattnerdc046542009-05-08 06:58:22 +00002171/// SemaBuiltinAtomicOverloaded - We have a call to a function like
2172/// __sync_fetch_and_add, which is an overloaded function based on the pointer
2173/// type of its first argument. The main ActOnCallExpr routines have already
2174/// promoted the types of arguments because all of these calls are prototyped as
2175/// void(...).
2176///
2177/// This function goes through and does final semantic checking for these
2178/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00002179ExprResult
2180Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002181 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00002182 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2183 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2184
2185 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002186 if (TheCall->getNumArgs() < 1) {
2187 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2188 << 0 << 1 << TheCall->getNumArgs()
2189 << TheCall->getCallee()->getSourceRange();
2190 return ExprError();
2191 }
Mike Stump11289f42009-09-09 15:08:12 +00002192
Chris Lattnerdc046542009-05-08 06:58:22 +00002193 // Inspect the first argument of the atomic builtin. This should always be
2194 // a pointer type, whose element is an integral scalar or pointer type.
2195 // Because it is a pointer type, we don't have to worry about any implicit
2196 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002197 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00002198 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00002199 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2200 if (FirstArgResult.isInvalid())
2201 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002202 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00002203 TheCall->setArg(0, FirstArg);
2204
John McCall31168b02011-06-15 23:02:42 +00002205 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2206 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002207 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2208 << FirstArg->getType() << FirstArg->getSourceRange();
2209 return ExprError();
2210 }
Mike Stump11289f42009-09-09 15:08:12 +00002211
John McCall31168b02011-06-15 23:02:42 +00002212 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00002213 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002214 !ValType->isBlockPointerType()) {
2215 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2216 << FirstArg->getType() << FirstArg->getSourceRange();
2217 return ExprError();
2218 }
Chris Lattnerdc046542009-05-08 06:58:22 +00002219
John McCall31168b02011-06-15 23:02:42 +00002220 switch (ValType.getObjCLifetime()) {
2221 case Qualifiers::OCL_None:
2222 case Qualifiers::OCL_ExplicitNone:
2223 // okay
2224 break;
2225
2226 case Qualifiers::OCL_Weak:
2227 case Qualifiers::OCL_Strong:
2228 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002229 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00002230 << ValType << FirstArg->getSourceRange();
2231 return ExprError();
2232 }
2233
John McCallb50451a2011-10-05 07:41:44 +00002234 // Strip any qualifiers off ValType.
2235 ValType = ValType.getUnqualifiedType();
2236
Chandler Carruth3973af72010-07-18 20:54:12 +00002237 // The majority of builtins return a value, but a few have special return
2238 // types, so allow them to override appropriately below.
2239 QualType ResultType = ValType;
2240
Chris Lattnerdc046542009-05-08 06:58:22 +00002241 // We need to figure out which concrete builtin this maps onto. For example,
2242 // __sync_fetch_and_add with a 2 byte object turns into
2243 // __sync_fetch_and_add_2.
2244#define BUILTIN_ROW(x) \
2245 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2246 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00002247
Chris Lattnerdc046542009-05-08 06:58:22 +00002248 static const unsigned BuiltinIndices[][5] = {
2249 BUILTIN_ROW(__sync_fetch_and_add),
2250 BUILTIN_ROW(__sync_fetch_and_sub),
2251 BUILTIN_ROW(__sync_fetch_and_or),
2252 BUILTIN_ROW(__sync_fetch_and_and),
2253 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002254 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002255
Chris Lattnerdc046542009-05-08 06:58:22 +00002256 BUILTIN_ROW(__sync_add_and_fetch),
2257 BUILTIN_ROW(__sync_sub_and_fetch),
2258 BUILTIN_ROW(__sync_and_and_fetch),
2259 BUILTIN_ROW(__sync_or_and_fetch),
2260 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002261 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002262
Chris Lattnerdc046542009-05-08 06:58:22 +00002263 BUILTIN_ROW(__sync_val_compare_and_swap),
2264 BUILTIN_ROW(__sync_bool_compare_and_swap),
2265 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002266 BUILTIN_ROW(__sync_lock_release),
2267 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002268 };
Mike Stump11289f42009-09-09 15:08:12 +00002269#undef BUILTIN_ROW
2270
Chris Lattnerdc046542009-05-08 06:58:22 +00002271 // Determine the index of the size.
2272 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002273 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002274 case 1: SizeIndex = 0; break;
2275 case 2: SizeIndex = 1; break;
2276 case 4: SizeIndex = 2; break;
2277 case 8: SizeIndex = 3; break;
2278 case 16: SizeIndex = 4; break;
2279 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002280 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2281 << FirstArg->getType() << FirstArg->getSourceRange();
2282 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002283 }
Mike Stump11289f42009-09-09 15:08:12 +00002284
Chris Lattnerdc046542009-05-08 06:58:22 +00002285 // Each of these builtins has one pointer argument, followed by some number of
2286 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2287 // that we ignore. Find out which row of BuiltinIndices to read from as well
2288 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002289 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002290 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002291 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002292 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002293 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002294 case Builtin::BI__sync_fetch_and_add:
2295 case Builtin::BI__sync_fetch_and_add_1:
2296 case Builtin::BI__sync_fetch_and_add_2:
2297 case Builtin::BI__sync_fetch_and_add_4:
2298 case Builtin::BI__sync_fetch_and_add_8:
2299 case Builtin::BI__sync_fetch_and_add_16:
2300 BuiltinIndex = 0;
2301 break;
2302
2303 case Builtin::BI__sync_fetch_and_sub:
2304 case Builtin::BI__sync_fetch_and_sub_1:
2305 case Builtin::BI__sync_fetch_and_sub_2:
2306 case Builtin::BI__sync_fetch_and_sub_4:
2307 case Builtin::BI__sync_fetch_and_sub_8:
2308 case Builtin::BI__sync_fetch_and_sub_16:
2309 BuiltinIndex = 1;
2310 break;
2311
2312 case Builtin::BI__sync_fetch_and_or:
2313 case Builtin::BI__sync_fetch_and_or_1:
2314 case Builtin::BI__sync_fetch_and_or_2:
2315 case Builtin::BI__sync_fetch_and_or_4:
2316 case Builtin::BI__sync_fetch_and_or_8:
2317 case Builtin::BI__sync_fetch_and_or_16:
2318 BuiltinIndex = 2;
2319 break;
2320
2321 case Builtin::BI__sync_fetch_and_and:
2322 case Builtin::BI__sync_fetch_and_and_1:
2323 case Builtin::BI__sync_fetch_and_and_2:
2324 case Builtin::BI__sync_fetch_and_and_4:
2325 case Builtin::BI__sync_fetch_and_and_8:
2326 case Builtin::BI__sync_fetch_and_and_16:
2327 BuiltinIndex = 3;
2328 break;
Mike Stump11289f42009-09-09 15:08:12 +00002329
Douglas Gregor73722482011-11-28 16:30:08 +00002330 case Builtin::BI__sync_fetch_and_xor:
2331 case Builtin::BI__sync_fetch_and_xor_1:
2332 case Builtin::BI__sync_fetch_and_xor_2:
2333 case Builtin::BI__sync_fetch_and_xor_4:
2334 case Builtin::BI__sync_fetch_and_xor_8:
2335 case Builtin::BI__sync_fetch_and_xor_16:
2336 BuiltinIndex = 4;
2337 break;
2338
Hal Finkeld2208b52014-10-02 20:53:50 +00002339 case Builtin::BI__sync_fetch_and_nand:
2340 case Builtin::BI__sync_fetch_and_nand_1:
2341 case Builtin::BI__sync_fetch_and_nand_2:
2342 case Builtin::BI__sync_fetch_and_nand_4:
2343 case Builtin::BI__sync_fetch_and_nand_8:
2344 case Builtin::BI__sync_fetch_and_nand_16:
2345 BuiltinIndex = 5;
2346 WarnAboutSemanticsChange = true;
2347 break;
2348
Douglas Gregor73722482011-11-28 16:30:08 +00002349 case Builtin::BI__sync_add_and_fetch:
2350 case Builtin::BI__sync_add_and_fetch_1:
2351 case Builtin::BI__sync_add_and_fetch_2:
2352 case Builtin::BI__sync_add_and_fetch_4:
2353 case Builtin::BI__sync_add_and_fetch_8:
2354 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002355 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002356 break;
2357
2358 case Builtin::BI__sync_sub_and_fetch:
2359 case Builtin::BI__sync_sub_and_fetch_1:
2360 case Builtin::BI__sync_sub_and_fetch_2:
2361 case Builtin::BI__sync_sub_and_fetch_4:
2362 case Builtin::BI__sync_sub_and_fetch_8:
2363 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002364 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002365 break;
2366
2367 case Builtin::BI__sync_and_and_fetch:
2368 case Builtin::BI__sync_and_and_fetch_1:
2369 case Builtin::BI__sync_and_and_fetch_2:
2370 case Builtin::BI__sync_and_and_fetch_4:
2371 case Builtin::BI__sync_and_and_fetch_8:
2372 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002373 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002374 break;
2375
2376 case Builtin::BI__sync_or_and_fetch:
2377 case Builtin::BI__sync_or_and_fetch_1:
2378 case Builtin::BI__sync_or_and_fetch_2:
2379 case Builtin::BI__sync_or_and_fetch_4:
2380 case Builtin::BI__sync_or_and_fetch_8:
2381 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002382 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002383 break;
2384
2385 case Builtin::BI__sync_xor_and_fetch:
2386 case Builtin::BI__sync_xor_and_fetch_1:
2387 case Builtin::BI__sync_xor_and_fetch_2:
2388 case Builtin::BI__sync_xor_and_fetch_4:
2389 case Builtin::BI__sync_xor_and_fetch_8:
2390 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002391 BuiltinIndex = 10;
2392 break;
2393
2394 case Builtin::BI__sync_nand_and_fetch:
2395 case Builtin::BI__sync_nand_and_fetch_1:
2396 case Builtin::BI__sync_nand_and_fetch_2:
2397 case Builtin::BI__sync_nand_and_fetch_4:
2398 case Builtin::BI__sync_nand_and_fetch_8:
2399 case Builtin::BI__sync_nand_and_fetch_16:
2400 BuiltinIndex = 11;
2401 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002402 break;
Mike Stump11289f42009-09-09 15:08:12 +00002403
Chris Lattnerdc046542009-05-08 06:58:22 +00002404 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002405 case Builtin::BI__sync_val_compare_and_swap_1:
2406 case Builtin::BI__sync_val_compare_and_swap_2:
2407 case Builtin::BI__sync_val_compare_and_swap_4:
2408 case Builtin::BI__sync_val_compare_and_swap_8:
2409 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002410 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002411 NumFixed = 2;
2412 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002413
Chris Lattnerdc046542009-05-08 06:58:22 +00002414 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002415 case Builtin::BI__sync_bool_compare_and_swap_1:
2416 case Builtin::BI__sync_bool_compare_and_swap_2:
2417 case Builtin::BI__sync_bool_compare_and_swap_4:
2418 case Builtin::BI__sync_bool_compare_and_swap_8:
2419 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002420 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002421 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002422 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002423 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002424
2425 case Builtin::BI__sync_lock_test_and_set:
2426 case Builtin::BI__sync_lock_test_and_set_1:
2427 case Builtin::BI__sync_lock_test_and_set_2:
2428 case Builtin::BI__sync_lock_test_and_set_4:
2429 case Builtin::BI__sync_lock_test_and_set_8:
2430 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002431 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002432 break;
2433
Chris Lattnerdc046542009-05-08 06:58:22 +00002434 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002435 case Builtin::BI__sync_lock_release_1:
2436 case Builtin::BI__sync_lock_release_2:
2437 case Builtin::BI__sync_lock_release_4:
2438 case Builtin::BI__sync_lock_release_8:
2439 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002440 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002441 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002442 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002443 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002444
2445 case Builtin::BI__sync_swap:
2446 case Builtin::BI__sync_swap_1:
2447 case Builtin::BI__sync_swap_2:
2448 case Builtin::BI__sync_swap_4:
2449 case Builtin::BI__sync_swap_8:
2450 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002451 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002452 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002453 }
Mike Stump11289f42009-09-09 15:08:12 +00002454
Chris Lattnerdc046542009-05-08 06:58:22 +00002455 // Now that we know how many fixed arguments we expect, first check that we
2456 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002457 if (TheCall->getNumArgs() < 1+NumFixed) {
2458 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2459 << 0 << 1+NumFixed << TheCall->getNumArgs()
2460 << TheCall->getCallee()->getSourceRange();
2461 return ExprError();
2462 }
Mike Stump11289f42009-09-09 15:08:12 +00002463
Hal Finkeld2208b52014-10-02 20:53:50 +00002464 if (WarnAboutSemanticsChange) {
2465 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2466 << TheCall->getCallee()->getSourceRange();
2467 }
2468
Chris Lattner5b9241b2009-05-08 15:36:58 +00002469 // Get the decl for the concrete builtin from this, we can tell what the
2470 // concrete integer type we should convert to is.
2471 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002472 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002473 FunctionDecl *NewBuiltinDecl;
2474 if (NewBuiltinID == BuiltinID)
2475 NewBuiltinDecl = FDecl;
2476 else {
2477 // Perform builtin lookup to avoid redeclaring it.
2478 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2479 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2480 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2481 assert(Res.getFoundDecl());
2482 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002483 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002484 return ExprError();
2485 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002486
John McCallcf142162010-08-07 06:22:56 +00002487 // The first argument --- the pointer --- has a fixed type; we
2488 // deduce the types of the rest of the arguments accordingly. Walk
2489 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002490 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002491 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002492
Chris Lattnerdc046542009-05-08 06:58:22 +00002493 // GCC does an implicit conversion to the pointer or integer ValType. This
2494 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002495 // Initialize the argument.
2496 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2497 ValType, /*consume*/ false);
2498 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002499 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002500 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattnerdc046542009-05-08 06:58:22 +00002502 // Okay, we have something that *can* be converted to the right type. Check
2503 // to see if there is a potentially weird extension going on here. This can
2504 // happen when you do an atomic operation on something like an char* and
2505 // pass in 42. The 42 gets converted to char. This is even more strange
2506 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002507 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002508 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002509 }
Mike Stump11289f42009-09-09 15:08:12 +00002510
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002511 ASTContext& Context = this->getASTContext();
2512
2513 // Create a new DeclRefExpr to refer to the new decl.
2514 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2515 Context,
2516 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002517 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002518 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002519 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002520 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002521 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002522 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002523
Chris Lattnerdc046542009-05-08 06:58:22 +00002524 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002525 // FIXME: This loses syntactic information.
2526 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2527 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2528 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002529 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002530
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002531 // Change the result type of the call to match the original value type. This
2532 // is arbitrary, but the codegen for these builtins ins design to handle it
2533 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002534 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002535
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002536 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002537}
2538
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002539/// SemaBuiltinNontemporalOverloaded - We have a call to
2540/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2541/// overloaded function based on the pointer type of its last argument.
2542///
2543/// This function goes through and does final semantic checking for these
2544/// builtins.
2545ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2546 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2547 DeclRefExpr *DRE =
2548 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2549 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2550 unsigned BuiltinID = FDecl->getBuiltinID();
2551 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2552 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2553 "Unexpected nontemporal load/store builtin!");
2554 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2555 unsigned numArgs = isStore ? 2 : 1;
2556
2557 // Ensure that we have the proper number of arguments.
2558 if (checkArgCount(*this, TheCall, numArgs))
2559 return ExprError();
2560
2561 // Inspect the last argument of the nontemporal builtin. This should always
2562 // be a pointer type, from which we imply the type of the memory access.
2563 // Because it is a pointer type, we don't have to worry about any implicit
2564 // casts here.
2565 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2566 ExprResult PointerArgResult =
2567 DefaultFunctionArrayLvalueConversion(PointerArg);
2568
2569 if (PointerArgResult.isInvalid())
2570 return ExprError();
2571 PointerArg = PointerArgResult.get();
2572 TheCall->setArg(numArgs - 1, PointerArg);
2573
2574 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2575 if (!pointerType) {
2576 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2577 << PointerArg->getType() << PointerArg->getSourceRange();
2578 return ExprError();
2579 }
2580
2581 QualType ValType = pointerType->getPointeeType();
2582
2583 // Strip any qualifiers off ValType.
2584 ValType = ValType.getUnqualifiedType();
2585 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2586 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2587 !ValType->isVectorType()) {
2588 Diag(DRE->getLocStart(),
2589 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2590 << PointerArg->getType() << PointerArg->getSourceRange();
2591 return ExprError();
2592 }
2593
2594 if (!isStore) {
2595 TheCall->setType(ValType);
2596 return TheCallResult;
2597 }
2598
2599 ExprResult ValArg = TheCall->getArg(0);
2600 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2601 Context, ValType, /*consume*/ false);
2602 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2603 if (ValArg.isInvalid())
2604 return ExprError();
2605
2606 TheCall->setArg(0, ValArg.get());
2607 TheCall->setType(Context.VoidTy);
2608 return TheCallResult;
2609}
2610
Chris Lattner6436fb62009-02-18 06:01:06 +00002611/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002612/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002613/// Note: It might also make sense to do the UTF-16 conversion here (would
2614/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002615bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002616 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002617 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2618
Douglas Gregorfb65e592011-07-27 05:40:30 +00002619 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002620 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2621 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002622 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002623 }
Mike Stump11289f42009-09-09 15:08:12 +00002624
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002625 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002626 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002627 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002628 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002629 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002630 UTF16 *ToPtr = &ToBuf[0];
2631
2632 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2633 &ToPtr, ToPtr + NumBytes,
2634 strictConversion);
2635 // Check for conversion failure.
2636 if (Result != conversionOK)
2637 Diag(Arg->getLocStart(),
2638 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2639 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002640 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002641}
2642
Charles Davisc7d5c942015-09-17 20:55:33 +00002643/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2644/// for validity. Emit an error and return true on failure; return false
2645/// on success.
2646bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002647 Expr *Fn = TheCall->getCallee();
2648 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002649 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002650 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002651 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2652 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002653 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002654 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002655 return true;
2656 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002657
2658 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002659 return Diag(TheCall->getLocEnd(),
2660 diag::err_typecheck_call_too_few_args_at_least)
2661 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002662 }
2663
John McCall29ad95b2011-08-27 01:09:30 +00002664 // Type-check the first argument normally.
2665 if (checkBuiltinArgument(*this, TheCall, 0))
2666 return true;
2667
Chris Lattnere202e6a2007-12-20 00:05:45 +00002668 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002669 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002670 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002671 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002672 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002673 else if (FunctionDecl *FD = getCurFunctionDecl())
2674 isVariadic = FD->isVariadic();
2675 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002676 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002677
Chris Lattnere202e6a2007-12-20 00:05:45 +00002678 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002679 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2680 return true;
2681 }
Mike Stump11289f42009-09-09 15:08:12 +00002682
Chris Lattner43be2e62007-12-19 23:59:04 +00002683 // Verify that the second argument to the builtin is the last argument of the
2684 // current function or method.
2685 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002686 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002687
Nico Weber9eea7642013-05-24 23:31:57 +00002688 // These are valid if SecondArgIsLastNamedArgument is false after the next
2689 // block.
2690 QualType Type;
2691 SourceLocation ParamLoc;
2692
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002693 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2694 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002695 // FIXME: This isn't correct for methods (results in bogus warning).
2696 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002697 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002698 if (CurBlock)
2699 LastArg = *(CurBlock->TheDecl->param_end()-1);
2700 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002701 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002702 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002703 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002704 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002705
2706 Type = PV->getType();
2707 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002708 }
2709 }
Mike Stump11289f42009-09-09 15:08:12 +00002710
Chris Lattner43be2e62007-12-19 23:59:04 +00002711 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002712 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002713 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002714 else if (Type->isReferenceType()) {
2715 Diag(Arg->getLocStart(),
2716 diag::warn_va_start_of_reference_type_is_undefined);
2717 Diag(ParamLoc, diag::note_parameter_type) << Type;
2718 }
2719
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002720 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002721 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002722}
Chris Lattner43be2e62007-12-19 23:59:04 +00002723
Charles Davisc7d5c942015-09-17 20:55:33 +00002724/// Check the arguments to '__builtin_va_start' for validity, and that
2725/// it was called from a function of the native ABI.
2726/// Emit an error and return true on failure; return false on success.
2727bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2728 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2729 // On x64 Windows, don't allow this in System V ABI functions.
2730 // (Yes, that means there's no corresponding way to support variadic
2731 // System V ABI functions on Windows.)
2732 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2733 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2734 clang::CallingConv CC = CC_C;
2735 if (const FunctionDecl *FD = getCurFunctionDecl())
2736 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2737 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2738 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2739 return Diag(TheCall->getCallee()->getLocStart(),
2740 diag::err_va_start_used_in_wrong_abi_function)
2741 << (OS != llvm::Triple::Win32);
2742 }
2743 return SemaBuiltinVAStartImpl(TheCall);
2744}
2745
2746/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2747/// it was called from a Win64 ABI function.
2748/// Emit an error and return true on failure; return false on success.
2749bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2750 // This only makes sense for x86-64.
2751 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2752 Expr *Callee = TheCall->getCallee();
2753 if (TT.getArch() != llvm::Triple::x86_64)
2754 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2755 // Don't allow this in System V ABI functions.
2756 clang::CallingConv CC = CC_C;
2757 if (const FunctionDecl *FD = getCurFunctionDecl())
2758 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2759 if (CC == CC_X86_64SysV ||
2760 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2761 return Diag(Callee->getLocStart(),
2762 diag::err_ms_va_start_used_in_sysv_function);
2763 return SemaBuiltinVAStartImpl(TheCall);
2764}
2765
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002766bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2767 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2768 // const char *named_addr);
2769
2770 Expr *Func = Call->getCallee();
2771
2772 if (Call->getNumArgs() < 3)
2773 return Diag(Call->getLocEnd(),
2774 diag::err_typecheck_call_too_few_args_at_least)
2775 << 0 /*function call*/ << 3 << Call->getNumArgs();
2776
2777 // Determine whether the current function is variadic or not.
2778 bool IsVariadic;
2779 if (BlockScopeInfo *CurBlock = getCurBlock())
2780 IsVariadic = CurBlock->TheDecl->isVariadic();
2781 else if (FunctionDecl *FD = getCurFunctionDecl())
2782 IsVariadic = FD->isVariadic();
2783 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2784 IsVariadic = MD->isVariadic();
2785 else
2786 llvm_unreachable("unexpected statement type");
2787
2788 if (!IsVariadic) {
2789 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2790 return true;
2791 }
2792
2793 // Type-check the first argument normally.
2794 if (checkBuiltinArgument(*this, Call, 0))
2795 return true;
2796
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002797 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002798 unsigned ArgNo;
2799 QualType Type;
2800 } ArgumentTypes[] = {
2801 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2802 { 2, Context.getSizeType() },
2803 };
2804
2805 for (const auto &AT : ArgumentTypes) {
2806 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2807 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2808 continue;
2809 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2810 << Arg->getType() << AT.Type << 1 /* different class */
2811 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2812 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2813 }
2814
2815 return false;
2816}
2817
Chris Lattner2da14fb2007-12-20 00:26:33 +00002818/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2819/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002820bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2821 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002822 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002823 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002824 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002825 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002826 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002827 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002828 << SourceRange(TheCall->getArg(2)->getLocStart(),
2829 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002830
John Wiegley01296292011-04-08 18:41:53 +00002831 ExprResult OrigArg0 = TheCall->getArg(0);
2832 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002833
Chris Lattner2da14fb2007-12-20 00:26:33 +00002834 // Do standard promotions between the two arguments, returning their common
2835 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002836 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002837 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2838 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002839
2840 // Make sure any conversions are pushed back into the call; this is
2841 // type safe since unordered compare builtins are declared as "_Bool
2842 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002843 TheCall->setArg(0, OrigArg0.get());
2844 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002845
John Wiegley01296292011-04-08 18:41:53 +00002846 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002847 return false;
2848
Chris Lattner2da14fb2007-12-20 00:26:33 +00002849 // If the common type isn't a real floating type, then the arguments were
2850 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002851 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002852 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002853 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002854 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2855 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002856
Chris Lattner2da14fb2007-12-20 00:26:33 +00002857 return false;
2858}
2859
Benjamin Kramer634fc102010-02-15 22:42:31 +00002860/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2861/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002862/// to check everything. We expect the last argument to be a floating point
2863/// value.
2864bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2865 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002866 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002867 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002868 if (TheCall->getNumArgs() > NumArgs)
2869 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002870 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002871 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002872 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002873 (*(TheCall->arg_end()-1))->getLocEnd());
2874
Benjamin Kramer64aae502010-02-16 10:07:31 +00002875 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002876
Eli Friedman7e4faac2009-08-31 20:06:00 +00002877 if (OrigArg->isTypeDependent())
2878 return false;
2879
Chris Lattner68784ef2010-05-06 05:50:07 +00002880 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002881 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002882 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002883 diag::err_typecheck_call_invalid_unary_fp)
2884 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002885
Chris Lattner68784ef2010-05-06 05:50:07 +00002886 // If this is an implicit conversion from float -> double, remove it.
2887 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2888 Expr *CastArg = Cast->getSubExpr();
2889 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2890 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2891 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002892 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002893 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002894 }
2895 }
2896
Eli Friedman7e4faac2009-08-31 20:06:00 +00002897 return false;
2898}
2899
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002900/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2901// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002902ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002903 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002904 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002905 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002906 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2907 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002908
Nate Begemana0110022010-06-08 00:16:34 +00002909 // Determine which of the following types of shufflevector we're checking:
2910 // 1) unary, vector mask: (lhs, mask)
2911 // 2) binary, vector mask: (lhs, rhs, mask)
2912 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2913 QualType resType = TheCall->getArg(0)->getType();
2914 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002915
Douglas Gregorc25f7662009-05-19 22:10:17 +00002916 if (!TheCall->getArg(0)->isTypeDependent() &&
2917 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002918 QualType LHSType = TheCall->getArg(0)->getType();
2919 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002920
Craig Topperbaca3892013-07-29 06:47:04 +00002921 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2922 return ExprError(Diag(TheCall->getLocStart(),
2923 diag::err_shufflevector_non_vector)
2924 << SourceRange(TheCall->getArg(0)->getLocStart(),
2925 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002926
Nate Begemana0110022010-06-08 00:16:34 +00002927 numElements = LHSType->getAs<VectorType>()->getNumElements();
2928 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002929
Nate Begemana0110022010-06-08 00:16:34 +00002930 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2931 // with mask. If so, verify that RHS is an integer vector type with the
2932 // same number of elts as lhs.
2933 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002934 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002935 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002936 return ExprError(Diag(TheCall->getLocStart(),
2937 diag::err_shufflevector_incompatible_vector)
2938 << SourceRange(TheCall->getArg(1)->getLocStart(),
2939 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002940 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002941 return ExprError(Diag(TheCall->getLocStart(),
2942 diag::err_shufflevector_incompatible_vector)
2943 << SourceRange(TheCall->getArg(0)->getLocStart(),
2944 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002945 } else if (numElements != numResElements) {
2946 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002947 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002948 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002949 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002950 }
2951
2952 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002953 if (TheCall->getArg(i)->isTypeDependent() ||
2954 TheCall->getArg(i)->isValueDependent())
2955 continue;
2956
Nate Begemana0110022010-06-08 00:16:34 +00002957 llvm::APSInt Result(32);
2958 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2959 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002960 diag::err_shufflevector_nonconstant_argument)
2961 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002962
Craig Topper50ad5b72013-08-03 17:40:38 +00002963 // Allow -1 which will be translated to undef in the IR.
2964 if (Result.isSigned() && Result.isAllOnesValue())
2965 continue;
2966
Chris Lattner7ab824e2008-08-10 02:05:13 +00002967 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002968 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002969 diag::err_shufflevector_argument_too_large)
2970 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002971 }
2972
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002973 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002974
Chris Lattner7ab824e2008-08-10 02:05:13 +00002975 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002976 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002977 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002978 }
2979
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002980 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2981 TheCall->getCallee()->getLocStart(),
2982 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002983}
Chris Lattner43be2e62007-12-19 23:59:04 +00002984
Hal Finkelc4d7c822013-09-18 03:29:45 +00002985/// SemaConvertVectorExpr - Handle __builtin_convertvector
2986ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2987 SourceLocation BuiltinLoc,
2988 SourceLocation RParenLoc) {
2989 ExprValueKind VK = VK_RValue;
2990 ExprObjectKind OK = OK_Ordinary;
2991 QualType DstTy = TInfo->getType();
2992 QualType SrcTy = E->getType();
2993
2994 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2995 return ExprError(Diag(BuiltinLoc,
2996 diag::err_convertvector_non_vector)
2997 << E->getSourceRange());
2998 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2999 return ExprError(Diag(BuiltinLoc,
3000 diag::err_convertvector_non_vector_type));
3001
3002 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3003 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3004 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3005 if (SrcElts != DstElts)
3006 return ExprError(Diag(BuiltinLoc,
3007 diag::err_convertvector_incompatible_vector)
3008 << E->getSourceRange());
3009 }
3010
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003011 return new (Context)
3012 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00003013}
3014
Daniel Dunbarb7257262008-07-21 22:59:13 +00003015/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3016// This is declared to take (const void*, ...) and can take two
3017// optional constant int args.
3018bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00003019 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003020
Chris Lattner3b054132008-11-19 05:08:23 +00003021 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003022 return Diag(TheCall->getLocEnd(),
3023 diag::err_typecheck_call_too_many_args_at_most)
3024 << 0 /*function call*/ << 3 << NumArgs
3025 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00003026
3027 // Argument 0 is checked for us and the remaining arguments must be
3028 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00003029 for (unsigned i = 1; i != NumArgs; ++i)
3030 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003031 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003032
Warren Hunt20e4a5d2014-02-21 23:08:53 +00003033 return false;
3034}
3035
Hal Finkelf0417332014-07-17 14:25:55 +00003036/// SemaBuiltinAssume - Handle __assume (MS Extension).
3037// __assume does not evaluate its arguments, and should warn if its argument
3038// has side effects.
3039bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3040 Expr *Arg = TheCall->getArg(0);
3041 if (Arg->isInstantiationDependent()) return false;
3042
3043 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00003044 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00003045 << Arg->getSourceRange()
3046 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3047
3048 return false;
3049}
3050
3051/// Handle __builtin_assume_aligned. This is declared
3052/// as (const void*, size_t, ...) and can take one optional constant int arg.
3053bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3054 unsigned NumArgs = TheCall->getNumArgs();
3055
3056 if (NumArgs > 3)
3057 return Diag(TheCall->getLocEnd(),
3058 diag::err_typecheck_call_too_many_args_at_most)
3059 << 0 /*function call*/ << 3 << NumArgs
3060 << TheCall->getSourceRange();
3061
3062 // The alignment must be a constant integer.
3063 Expr *Arg = TheCall->getArg(1);
3064
3065 // We can't check the value of a dependent argument.
3066 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3067 llvm::APSInt Result;
3068 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3069 return true;
3070
3071 if (!Result.isPowerOf2())
3072 return Diag(TheCall->getLocStart(),
3073 diag::err_alignment_not_power_of_two)
3074 << Arg->getSourceRange();
3075 }
3076
3077 if (NumArgs > 2) {
3078 ExprResult Arg(TheCall->getArg(2));
3079 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3080 Context.getSizeType(), false);
3081 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3082 if (Arg.isInvalid()) return true;
3083 TheCall->setArg(2, Arg.get());
3084 }
Hal Finkelf0417332014-07-17 14:25:55 +00003085
3086 return false;
3087}
3088
Eric Christopher8d0c6212010-04-17 02:26:23 +00003089/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3090/// TheCall is a constant expression.
3091bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3092 llvm::APSInt &Result) {
3093 Expr *Arg = TheCall->getArg(ArgNum);
3094 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3095 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3096
3097 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3098
3099 if (!Arg->isIntegerConstantExpr(Result, Context))
3100 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00003101 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00003102
Chris Lattnerd545ad12009-09-23 06:06:36 +00003103 return false;
3104}
3105
Richard Sandiford28940af2014-04-16 08:47:51 +00003106/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3107/// TheCall is a constant expression in the range [Low, High].
3108bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3109 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00003110 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003111
3112 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00003113 Expr *Arg = TheCall->getArg(ArgNum);
3114 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00003115 return false;
3116
Eric Christopher8d0c6212010-04-17 02:26:23 +00003117 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00003118 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00003119 return true;
3120
Richard Sandiford28940af2014-04-16 08:47:51 +00003121 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00003122 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00003123 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00003124
3125 return false;
3126}
3127
Luke Cheeseman59b2d832015-06-15 17:51:01 +00003128/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3129/// TheCall is an ARM/AArch64 special register string literal.
3130bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3131 int ArgNum, unsigned ExpectedFieldNum,
3132 bool AllowName) {
3133 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3134 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3135 BuiltinID == ARM::BI__builtin_arm_rsr ||
3136 BuiltinID == ARM::BI__builtin_arm_rsrp ||
3137 BuiltinID == ARM::BI__builtin_arm_wsr ||
3138 BuiltinID == ARM::BI__builtin_arm_wsrp;
3139 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3140 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3141 BuiltinID == AArch64::BI__builtin_arm_rsr ||
3142 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3143 BuiltinID == AArch64::BI__builtin_arm_wsr ||
3144 BuiltinID == AArch64::BI__builtin_arm_wsrp;
3145 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3146
3147 // We can't check the value of a dependent argument.
3148 Expr *Arg = TheCall->getArg(ArgNum);
3149 if (Arg->isTypeDependent() || Arg->isValueDependent())
3150 return false;
3151
3152 // Check if the argument is a string literal.
3153 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3154 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3155 << Arg->getSourceRange();
3156
3157 // Check the type of special register given.
3158 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3159 SmallVector<StringRef, 6> Fields;
3160 Reg.split(Fields, ":");
3161
3162 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3163 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3164 << Arg->getSourceRange();
3165
3166 // If the string is the name of a register then we cannot check that it is
3167 // valid here but if the string is of one the forms described in ACLE then we
3168 // can check that the supplied fields are integers and within the valid
3169 // ranges.
3170 if (Fields.size() > 1) {
3171 bool FiveFields = Fields.size() == 5;
3172
3173 bool ValidString = true;
3174 if (IsARMBuiltin) {
3175 ValidString &= Fields[0].startswith_lower("cp") ||
3176 Fields[0].startswith_lower("p");
3177 if (ValidString)
3178 Fields[0] =
3179 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3180
3181 ValidString &= Fields[2].startswith_lower("c");
3182 if (ValidString)
3183 Fields[2] = Fields[2].drop_front(1);
3184
3185 if (FiveFields) {
3186 ValidString &= Fields[3].startswith_lower("c");
3187 if (ValidString)
3188 Fields[3] = Fields[3].drop_front(1);
3189 }
3190 }
3191
3192 SmallVector<int, 5> Ranges;
3193 if (FiveFields)
3194 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3195 else
3196 Ranges.append({15, 7, 15});
3197
3198 for (unsigned i=0; i<Fields.size(); ++i) {
3199 int IntField;
3200 ValidString &= !Fields[i].getAsInteger(10, IntField);
3201 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3202 }
3203
3204 if (!ValidString)
3205 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3206 << Arg->getSourceRange();
3207
3208 } else if (IsAArch64Builtin && Fields.size() == 1) {
3209 // If the register name is one of those that appear in the condition below
3210 // and the special register builtin being used is one of the write builtins,
3211 // then we require that the argument provided for writing to the register
3212 // is an integer constant expression. This is because it will be lowered to
3213 // an MSR (immediate) instruction, so we need to know the immediate at
3214 // compile time.
3215 if (TheCall->getNumArgs() != 2)
3216 return false;
3217
3218 std::string RegLower = Reg.lower();
3219 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3220 RegLower != "pan" && RegLower != "uao")
3221 return false;
3222
3223 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3224 }
3225
3226 return false;
3227}
3228
Eli Friedmanc97d0142009-05-03 06:04:26 +00003229/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003230/// This checks that the target supports __builtin_longjmp and
3231/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003232bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003233 if (!Context.getTargetInfo().hasSjLjLowering())
3234 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3235 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3236
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003237 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00003238 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00003239
Eric Christopher8d0c6212010-04-17 02:26:23 +00003240 // TODO: This is less than ideal. Overload this to take a value.
3241 if (SemaBuiltinConstantArg(TheCall, 1, Result))
3242 return true;
3243
3244 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00003245 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3246 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3247
3248 return false;
3249}
3250
Joerg Sonnenberger27173282015-03-11 23:46:32 +00003251/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3252/// This checks that the target supports __builtin_setjmp.
3253bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3254 if (!Context.getTargetInfo().hasSjLjLowering())
3255 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3256 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3257 return false;
3258}
3259
Richard Smithd7293d72013-08-05 18:49:43 +00003260namespace {
3261enum StringLiteralCheckType {
3262 SLCT_NotALiteral,
3263 SLCT_UncheckedLiteral,
3264 SLCT_CheckedLiteral
3265};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003266} // end anonymous namespace
Richard Smithd7293d72013-08-05 18:49:43 +00003267
Richard Smith55ce3522012-06-25 20:30:08 +00003268// Determine if an expression is a string literal or constant string.
3269// If this function returns false on the arguments to a function expecting a
3270// format string, we will usually need to emit a warning.
3271// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003272static StringLiteralCheckType
3273checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3274 bool HasVAListArg, unsigned format_idx,
3275 unsigned firstDataArg, Sema::FormatStringType Type,
3276 Sema::VariadicCallType CallType, bool InFunctionCall,
3277 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00003278 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003279 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003280 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003281
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003282 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003283
Richard Smithd7293d72013-08-05 18:49:43 +00003284 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003285 // Technically -Wformat-nonliteral does not warn about this case.
3286 // The behavior of printf and friends in this case is implementation
3287 // dependent. Ideally if the format string cannot be null then
3288 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003289 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003290
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003291 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003292 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003293 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003294 // The expression is a literal if both sub-expressions were, and it was
3295 // completely checked only if both sub-expressions were checked.
3296 const AbstractConditionalOperator *C =
3297 cast<AbstractConditionalOperator>(E);
3298 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003299 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003300 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003301 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003302 if (Left == SLCT_NotALiteral)
3303 return SLCT_NotALiteral;
3304 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003305 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003306 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003307 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003308 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003309 }
3310
3311 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003312 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3313 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003314 }
3315
John McCallc07a0c72011-02-17 10:25:35 +00003316 case Stmt::OpaqueValueExprClass:
3317 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3318 E = src;
3319 goto tryAgain;
3320 }
Richard Smith55ce3522012-06-25 20:30:08 +00003321 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003322
Ted Kremeneka8890832011-02-24 23:03:04 +00003323 case Stmt::PredefinedExprClass:
3324 // While __func__, etc., are technically not string literals, they
3325 // cannot contain format specifiers and thus are not a security
3326 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003327 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003328
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003329 case Stmt::DeclRefExprClass: {
3330 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003331
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003332 // As an exception, do not flag errors for variables binding to
3333 // const string literals.
3334 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3335 bool isConstant = false;
3336 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003337
Richard Smithd7293d72013-08-05 18:49:43 +00003338 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3339 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003340 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003341 isConstant = T.isConstant(S.Context) &&
3342 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003343 } else if (T->isObjCObjectPointerType()) {
3344 // In ObjC, there is usually no "const ObjectPointer" type,
3345 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003346 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003347 }
Mike Stump11289f42009-09-09 15:08:12 +00003348
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003349 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003350 if (const Expr *Init = VD->getAnyInitializer()) {
3351 // Look through initializers like const char c[] = { "foo" }
3352 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3353 if (InitList->isStringLiteralInit())
3354 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3355 }
Richard Smithd7293d72013-08-05 18:49:43 +00003356 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003357 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003358 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003359 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003360 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003361 }
Mike Stump11289f42009-09-09 15:08:12 +00003362
Anders Carlssonb012ca92009-06-28 19:55:58 +00003363 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3364 // special check to see if the format string is a function parameter
3365 // of the function calling the printf function. If the function
3366 // has an attribute indicating it is a printf-like function, then we
3367 // should suppress warnings concerning non-literals being used in a call
3368 // to a vprintf function. For example:
3369 //
3370 // void
3371 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3372 // va_list ap;
3373 // va_start(ap, fmt);
3374 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3375 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003376 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003377 if (HasVAListArg) {
3378 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3379 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3380 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003381 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003382 // adjust for implicit parameter
3383 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3384 if (MD->isInstance())
3385 ++PVIndex;
3386 // We also check if the formats are compatible.
3387 // We can't pass a 'scanf' string to a 'printf' function.
3388 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003389 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003390 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003391 }
3392 }
3393 }
3394 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003395 }
Mike Stump11289f42009-09-09 15:08:12 +00003396
Richard Smith55ce3522012-06-25 20:30:08 +00003397 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003398 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003399
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003400 case Stmt::CallExprClass:
3401 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003402 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003403 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3404 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3405 unsigned ArgIndex = FA->getFormatIdx();
3406 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3407 if (MD->isInstance())
3408 --ArgIndex;
3409 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003410
Richard Smithd7293d72013-08-05 18:49:43 +00003411 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003412 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003413 Type, CallType, InFunctionCall,
3414 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003415 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3416 unsigned BuiltinID = FD->getBuiltinID();
3417 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3418 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3419 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003420 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003421 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003422 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003423 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003424 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003425 }
3426 }
Mike Stump11289f42009-09-09 15:08:12 +00003427
Richard Smith55ce3522012-06-25 20:30:08 +00003428 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003429 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003430 case Stmt::ObjCStringLiteralClass:
3431 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003432 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003433
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003434 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003435 StrE = ObjCFExpr->getString();
3436 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003437 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003438
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003439 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003440 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3441 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003442 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003443 }
Mike Stump11289f42009-09-09 15:08:12 +00003444
Richard Smith55ce3522012-06-25 20:30:08 +00003445 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003446 }
Mike Stump11289f42009-09-09 15:08:12 +00003447
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003448 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003449 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003450 }
3451}
3452
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003453Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003454 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003455 .Case("scanf", FST_Scanf)
3456 .Cases("printf", "printf0", FST_Printf)
3457 .Cases("NSString", "CFString", FST_NSString)
3458 .Case("strftime", FST_Strftime)
3459 .Case("strfmon", FST_Strfmon)
3460 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003461 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003462 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003463 .Default(FST_Unknown);
3464}
3465
Jordan Rose3e0ec582012-07-19 18:10:23 +00003466/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003467/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003468/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003469bool Sema::CheckFormatArguments(const FormatAttr *Format,
3470 ArrayRef<const Expr *> Args,
3471 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003472 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003473 SourceLocation Loc, SourceRange Range,
3474 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003475 FormatStringInfo FSI;
3476 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003477 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003478 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003479 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003480 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003481}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003482
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003483bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003484 bool HasVAListArg, unsigned format_idx,
3485 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003486 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003487 SourceLocation Loc, SourceRange Range,
3488 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003489 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003490 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003491 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003492 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003493 }
Mike Stump11289f42009-09-09 15:08:12 +00003494
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003495 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003496
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003497 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003498 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003499 // Dynamically generated format strings are difficult to
3500 // automatically vet at compile time. Requiring that format strings
3501 // are string literals: (1) permits the checking of format strings by
3502 // the compiler and thereby (2) can practically remove the source of
3503 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003504
Mike Stump11289f42009-09-09 15:08:12 +00003505 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003506 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003507 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003508 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003509 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003510 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3511 format_idx, firstDataArg, Type, CallType,
3512 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003513 if (CT != SLCT_NotALiteral)
3514 // Literal format string found, check done!
3515 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003516
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003517 // Strftime is particular as it always uses a single 'time' argument,
3518 // so it is safe to pass a non-literal string.
3519 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003520 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003521
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003522 // Do not emit diag when the string param is a macro expansion and the
3523 // format is either NSString or CFString. This is a hack to prevent
3524 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3525 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003526 if (Type == FST_NSString &&
3527 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003528 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003529
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003530 // If there are no arguments specified, warn with -Wformat-security, otherwise
3531 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003532 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003533 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003534 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003535 << OrigFormatExpr->getSourceRange();
3536 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003537 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003538 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003539 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003540 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003541}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003542
Ted Kremenekab278de2010-01-28 23:39:18 +00003543namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003544class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3545protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003546 Sema &S;
3547 const StringLiteral *FExpr;
3548 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003549 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003550 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003551 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003552 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003553 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003554 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003555 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003556 bool usesPositionalArgs;
3557 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003558 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003559 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003560 llvm::SmallBitVector &CheckedVarArgs;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003561
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003562public:
Ted Kremenek02087932010-07-16 02:11:22 +00003563 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003564 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003565 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003566 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003567 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003568 Sema::VariadicCallType callType,
3569 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003570 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003571 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3572 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003573 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003574 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003575 inFunctionCall(inFunctionCall), CallType(callType),
3576 CheckedVarArgs(CheckedVarArgs) {
3577 CoveredArgs.resize(numDataArgs);
3578 CoveredArgs.reset();
3579 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003580
Ted Kremenek019d2242010-01-29 01:50:07 +00003581 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003582
Ted Kremenek02087932010-07-16 02:11:22 +00003583 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003584 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003585
Jordan Rose92303592012-09-08 04:00:03 +00003586 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003587 const analyze_format_string::FormatSpecifier &FS,
3588 const analyze_format_string::ConversionSpecifier &CS,
3589 const char *startSpecifier, unsigned specifierLen,
3590 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003591
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003592 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003593 const analyze_format_string::FormatSpecifier &FS,
3594 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003595
3596 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003597 const analyze_format_string::ConversionSpecifier &CS,
3598 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003599
Craig Toppere14c0f82014-03-12 04:55:44 +00003600 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003601
Craig Toppere14c0f82014-03-12 04:55:44 +00003602 void HandleInvalidPosition(const char *startSpecifier,
3603 unsigned specifierLen,
3604 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003605
Craig Toppere14c0f82014-03-12 04:55:44 +00003606 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003607
Craig Toppere14c0f82014-03-12 04:55:44 +00003608 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003609
Richard Trieu03cf7b72011-10-28 00:41:25 +00003610 template <typename Range>
3611 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3612 const Expr *ArgumentExpr,
3613 PartialDiagnostic PDiag,
3614 SourceLocation StringLoc,
3615 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003616 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003617
Ted Kremenek02087932010-07-16 02:11:22 +00003618protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003619 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3620 const char *startSpec,
3621 unsigned specifierLen,
3622 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003623
3624 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3625 const char *startSpec,
3626 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003627
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003628 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003629 CharSourceRange getSpecifierRange(const char *startSpecifier,
3630 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003631 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003632
Ted Kremenek5739de72010-01-29 01:06:55 +00003633 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003634
3635 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3636 const analyze_format_string::ConversionSpecifier &CS,
3637 const char *startSpecifier, unsigned specifierLen,
3638 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003639
3640 template <typename Range>
3641 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3642 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003643 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003644};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003645} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00003646
Ted Kremenek02087932010-07-16 02:11:22 +00003647SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003648 return OrigFormatExpr->getSourceRange();
3649}
3650
Ted Kremenek02087932010-07-16 02:11:22 +00003651CharSourceRange CheckFormatHandler::
3652getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003653 SourceLocation Start = getLocationOfByte(startSpecifier);
3654 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3655
3656 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003657 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003658
3659 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003660}
3661
Ted Kremenek02087932010-07-16 02:11:22 +00003662SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003663 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003664}
3665
Ted Kremenek02087932010-07-16 02:11:22 +00003666void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3667 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003668 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3669 getLocationOfByte(startSpecifier),
3670 /*IsStringLocation*/true,
3671 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003672}
3673
Jordan Rose92303592012-09-08 04:00:03 +00003674void CheckFormatHandler::HandleInvalidLengthModifier(
3675 const analyze_format_string::FormatSpecifier &FS,
3676 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003677 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003678 using namespace analyze_format_string;
3679
3680 const LengthModifier &LM = FS.getLengthModifier();
3681 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3682
3683 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003684 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003685 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003686 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003687 getLocationOfByte(LM.getStart()),
3688 /*IsStringLocation*/true,
3689 getSpecifierRange(startSpecifier, specifierLen));
3690
3691 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3692 << FixedLM->toString()
3693 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3694
3695 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003696 FixItHint Hint;
3697 if (DiagID == diag::warn_format_nonsensical_length)
3698 Hint = FixItHint::CreateRemoval(LMRange);
3699
3700 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003701 getLocationOfByte(LM.getStart()),
3702 /*IsStringLocation*/true,
3703 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003704 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003705 }
3706}
3707
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003708void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003709 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003710 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003711 using namespace analyze_format_string;
3712
3713 const LengthModifier &LM = FS.getLengthModifier();
3714 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3715
3716 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003717 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003718 if (FixedLM) {
3719 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3720 << LM.toString() << 0,
3721 getLocationOfByte(LM.getStart()),
3722 /*IsStringLocation*/true,
3723 getSpecifierRange(startSpecifier, specifierLen));
3724
3725 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3726 << FixedLM->toString()
3727 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3728
3729 } else {
3730 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3731 << LM.toString() << 0,
3732 getLocationOfByte(LM.getStart()),
3733 /*IsStringLocation*/true,
3734 getSpecifierRange(startSpecifier, specifierLen));
3735 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003736}
3737
3738void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3739 const analyze_format_string::ConversionSpecifier &CS,
3740 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003741 using namespace analyze_format_string;
3742
3743 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003744 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003745 if (FixedCS) {
3746 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3747 << CS.toString() << /*conversion specifier*/1,
3748 getLocationOfByte(CS.getStart()),
3749 /*IsStringLocation*/true,
3750 getSpecifierRange(startSpecifier, specifierLen));
3751
3752 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3753 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3754 << FixedCS->toString()
3755 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3756 } else {
3757 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3758 << CS.toString() << /*conversion specifier*/1,
3759 getLocationOfByte(CS.getStart()),
3760 /*IsStringLocation*/true,
3761 getSpecifierRange(startSpecifier, specifierLen));
3762 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003763}
3764
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003765void CheckFormatHandler::HandlePosition(const char *startPos,
3766 unsigned posLen) {
3767 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3768 getLocationOfByte(startPos),
3769 /*IsStringLocation*/true,
3770 getSpecifierRange(startPos, posLen));
3771}
3772
Ted Kremenekd1668192010-02-27 01:41:03 +00003773void
Ted Kremenek02087932010-07-16 02:11:22 +00003774CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3775 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003776 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3777 << (unsigned) p,
3778 getLocationOfByte(startPos), /*IsStringLocation*/true,
3779 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003780}
3781
Ted Kremenek02087932010-07-16 02:11:22 +00003782void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003783 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003784 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3785 getLocationOfByte(startPos),
3786 /*IsStringLocation*/true,
3787 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003788}
3789
Ted Kremenek02087932010-07-16 02:11:22 +00003790void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003791 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003792 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003793 EmitFormatDiagnostic(
3794 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3795 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3796 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003797 }
Ted Kremenek02087932010-07-16 02:11:22 +00003798}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003799
Jordan Rose58bbe422012-07-19 18:10:08 +00003800// Note that this may return NULL if there was an error parsing or building
3801// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003802const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003803 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003804}
3805
3806void CheckFormatHandler::DoneProcessing() {
3807 // Does the number of data arguments exceed the number of
3808 // format conversions in the format string?
3809 if (!HasVAListArg) {
3810 // Find any arguments that weren't covered.
3811 CoveredArgs.flip();
3812 signed notCoveredArg = CoveredArgs.find_first();
3813 if (notCoveredArg >= 0) {
3814 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003815 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3816 SourceLocation Loc = E->getLocStart();
3817 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3818 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3819 Loc, /*IsStringLocation*/false,
3820 getFormatStringRange());
3821 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003822 }
Ted Kremenek02087932010-07-16 02:11:22 +00003823 }
3824 }
3825}
3826
Ted Kremenekce815422010-07-19 21:25:57 +00003827bool
3828CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3829 SourceLocation Loc,
3830 const char *startSpec,
3831 unsigned specifierLen,
3832 const char *csStart,
3833 unsigned csLen) {
Ted Kremenekce815422010-07-19 21:25:57 +00003834 bool keepGoing = true;
3835 if (argIndex < NumDataArgs) {
3836 // Consider the argument coverered, even though the specifier doesn't
3837 // make sense.
3838 CoveredArgs.set(argIndex);
3839 }
3840 else {
3841 // If argIndex exceeds the number of data arguments we
3842 // don't issue a warning because that is just a cascade of warnings (and
3843 // they may have intended '%%' anyway). We don't want to continue processing
3844 // the format string after this point, however, as we will like just get
3845 // gibberish when trying to match arguments.
3846 keepGoing = false;
3847 }
3848
Richard Trieu03cf7b72011-10-28 00:41:25 +00003849 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3850 << StringRef(csStart, csLen),
3851 Loc, /*IsStringLocation*/true,
3852 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003853
3854 return keepGoing;
3855}
3856
Richard Trieu03cf7b72011-10-28 00:41:25 +00003857void
3858CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3859 const char *startSpec,
3860 unsigned specifierLen) {
3861 EmitFormatDiagnostic(
3862 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3863 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3864}
3865
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003866bool
3867CheckFormatHandler::CheckNumArgs(
3868 const analyze_format_string::FormatSpecifier &FS,
3869 const analyze_format_string::ConversionSpecifier &CS,
3870 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3871
3872 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003873 PartialDiagnostic PDiag = FS.usesPositionalArg()
3874 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3875 << (argIndex+1) << NumDataArgs)
3876 : S.PDiag(diag::warn_printf_insufficient_data_args);
3877 EmitFormatDiagnostic(
3878 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3879 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003880 return false;
3881 }
3882 return true;
3883}
3884
Richard Trieu03cf7b72011-10-28 00:41:25 +00003885template<typename Range>
3886void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3887 SourceLocation Loc,
3888 bool IsStringLocation,
3889 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003890 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003891 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003892 Loc, IsStringLocation, StringRange, FixIt);
3893}
3894
3895/// \brief If the format string is not within the funcion call, emit a note
3896/// so that the function call and string are in diagnostic messages.
3897///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003898/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003899/// call and only one diagnostic message will be produced. Otherwise, an
3900/// extra note will be emitted pointing to location of the format string.
3901///
3902/// \param ArgumentExpr the expression that is passed as the format string
3903/// argument in the function call. Used for getting locations when two
3904/// diagnostics are emitted.
3905///
3906/// \param PDiag the callee should already have provided any strings for the
3907/// diagnostic message. This function only adds locations and fixits
3908/// to diagnostics.
3909///
3910/// \param Loc primary location for diagnostic. If two diagnostics are
3911/// required, one will be at Loc and a new SourceLocation will be created for
3912/// the other one.
3913///
3914/// \param IsStringLocation if true, Loc points to the format string should be
3915/// used for the note. Otherwise, Loc points to the argument list and will
3916/// be used with PDiag.
3917///
3918/// \param StringRange some or all of the string to highlight. This is
3919/// templated so it can accept either a CharSourceRange or a SourceRange.
3920///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003921/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003922template<typename Range>
3923void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3924 const Expr *ArgumentExpr,
3925 PartialDiagnostic PDiag,
3926 SourceLocation Loc,
3927 bool IsStringLocation,
3928 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003929 ArrayRef<FixItHint> FixIt) {
3930 if (InFunctionCall) {
3931 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3932 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003933 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003934 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003935 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3936 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003937
3938 const Sema::SemaDiagnosticBuilder &Note =
3939 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3940 diag::note_format_string_defined);
3941
3942 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003943 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003944 }
3945}
3946
Ted Kremenek02087932010-07-16 02:11:22 +00003947//===--- CHECK: Printf format string checking ------------------------------===//
3948
3949namespace {
3950class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003951 bool ObjCContext;
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003952
Ted Kremenek02087932010-07-16 02:11:22 +00003953public:
3954 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3955 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003956 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003957 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003958 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003959 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003960 Sema::VariadicCallType CallType,
3961 llvm::SmallBitVector &CheckedVarArgs)
3962 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3963 numDataArgs, beg, hasVAListArg, Args,
3964 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3965 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003966 {}
3967
Ted Kremenek02087932010-07-16 02:11:22 +00003968 bool HandleInvalidPrintfConversionSpecifier(
3969 const analyze_printf::PrintfSpecifier &FS,
3970 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003971 unsigned specifierLen) override;
3972
Ted Kremenek02087932010-07-16 02:11:22 +00003973 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3974 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003975 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003976 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3977 const char *StartSpecifier,
3978 unsigned SpecifierLen,
3979 const Expr *E);
3980
Ted Kremenek02087932010-07-16 02:11:22 +00003981 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3982 const char *startSpecifier, unsigned specifierLen);
3983 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3984 const analyze_printf::OptionalAmount &Amt,
3985 unsigned type,
3986 const char *startSpecifier, unsigned specifierLen);
3987 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3988 const analyze_printf::OptionalFlag &flag,
3989 const char *startSpecifier, unsigned specifierLen);
3990 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3991 const analyze_printf::OptionalFlag &ignoredFlag,
3992 const analyze_printf::OptionalFlag &flag,
3993 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003994 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003995 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003996
3997 void HandleEmptyObjCModifierFlag(const char *startFlag,
3998 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003999
Ted Kremenek2b417712015-07-02 05:39:16 +00004000 void HandleInvalidObjCModifierFlag(const char *startFlag,
4001 unsigned flagLen) override;
4002
4003 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4004 const char *flagsEnd,
4005 const char *conversionPosition)
4006 override;
4007};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004008} // end anonymous namespace
Ted Kremenek02087932010-07-16 02:11:22 +00004009
4010bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4011 const analyze_printf::PrintfSpecifier &FS,
4012 const char *startSpecifier,
4013 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004014 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004015 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004016
Ted Kremenekce815422010-07-19 21:25:57 +00004017 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4018 getLocationOfByte(CS.getStart()),
4019 startSpecifier, specifierLen,
4020 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00004021}
4022
Ted Kremenek02087932010-07-16 02:11:22 +00004023bool CheckPrintfHandler::HandleAmount(
4024 const analyze_format_string::OptionalAmount &Amt,
4025 unsigned k, const char *startSpecifier,
4026 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004027 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004028 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00004029 unsigned argIndex = Amt.getArgIndex();
4030 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004031 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4032 << k,
4033 getLocationOfByte(Amt.getStart()),
4034 /*IsStringLocation*/true,
4035 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004036 // Don't do any more checking. We will just emit
4037 // spurious errors.
4038 return false;
4039 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004040
Ted Kremenek5739de72010-01-29 01:06:55 +00004041 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00004042 // Although not in conformance with C99, we also allow the argument to be
4043 // an 'unsigned int' as that is a reasonably safe case. GCC also
4044 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00004045 CoveredArgs.set(argIndex);
4046 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004047 if (!Arg)
4048 return false;
4049
Ted Kremenek5739de72010-01-29 01:06:55 +00004050 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004051
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004052 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4053 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004054
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004055 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004056 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004057 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00004058 << T << Arg->getSourceRange(),
4059 getLocationOfByte(Amt.getStart()),
4060 /*IsStringLocation*/true,
4061 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00004062 // Don't do any more checking. We will just emit
4063 // spurious errors.
4064 return false;
4065 }
4066 }
4067 }
4068 return true;
4069}
Ted Kremenek5739de72010-01-29 01:06:55 +00004070
Tom Careb49ec692010-06-17 19:00:27 +00004071void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00004072 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004073 const analyze_printf::OptionalAmount &Amt,
4074 unsigned type,
4075 const char *startSpecifier,
4076 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004077 const analyze_printf::PrintfConversionSpecifier &CS =
4078 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00004079
Richard Trieu03cf7b72011-10-28 00:41:25 +00004080 FixItHint fixit =
4081 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4082 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4083 Amt.getConstantLength()))
4084 : FixItHint();
4085
4086 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4087 << type << CS.toString(),
4088 getLocationOfByte(Amt.getStart()),
4089 /*IsStringLocation*/true,
4090 getSpecifierRange(startSpecifier, specifierLen),
4091 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00004092}
4093
Ted Kremenek02087932010-07-16 02:11:22 +00004094void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004095 const analyze_printf::OptionalFlag &flag,
4096 const char *startSpecifier,
4097 unsigned specifierLen) {
4098 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004099 const analyze_printf::PrintfConversionSpecifier &CS =
4100 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00004101 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4102 << flag.toString() << CS.toString(),
4103 getLocationOfByte(flag.getPosition()),
4104 /*IsStringLocation*/true,
4105 getSpecifierRange(startSpecifier, specifierLen),
4106 FixItHint::CreateRemoval(
4107 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004108}
4109
4110void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00004111 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00004112 const analyze_printf::OptionalFlag &ignoredFlag,
4113 const analyze_printf::OptionalFlag &flag,
4114 const char *startSpecifier,
4115 unsigned specifierLen) {
4116 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00004117 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4118 << ignoredFlag.toString() << flag.toString(),
4119 getLocationOfByte(ignoredFlag.getPosition()),
4120 /*IsStringLocation*/true,
4121 getSpecifierRange(startSpecifier, specifierLen),
4122 FixItHint::CreateRemoval(
4123 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00004124}
4125
Ted Kremenek2b417712015-07-02 05:39:16 +00004126// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4127// bool IsStringLocation, Range StringRange,
4128// ArrayRef<FixItHint> Fixit = None);
4129
4130void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4131 unsigned flagLen) {
4132 // Warn about an empty flag.
4133 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4134 getLocationOfByte(startFlag),
4135 /*IsStringLocation*/true,
4136 getSpecifierRange(startFlag, flagLen));
4137}
4138
4139void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4140 unsigned flagLen) {
4141 // Warn about an invalid flag.
4142 auto Range = getSpecifierRange(startFlag, flagLen);
4143 StringRef flag(startFlag, flagLen);
4144 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4145 getLocationOfByte(startFlag),
4146 /*IsStringLocation*/true,
4147 Range, FixItHint::CreateRemoval(Range));
4148}
4149
4150void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4151 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4152 // Warn about using '[...]' without a '@' conversion.
4153 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4154 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4155 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4156 getLocationOfByte(conversionPosition),
4157 /*IsStringLocation*/true,
4158 Range, FixItHint::CreateRemoval(Range));
4159}
4160
Richard Smith55ce3522012-06-25 20:30:08 +00004161// Determines if the specified is a C++ class or struct containing
4162// a member with the specified name and kind (e.g. a CXXMethodDecl named
4163// "c_str()").
4164template<typename MemberKind>
4165static llvm::SmallPtrSet<MemberKind*, 1>
4166CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4167 const RecordType *RT = Ty->getAs<RecordType>();
4168 llvm::SmallPtrSet<MemberKind*, 1> Results;
4169
4170 if (!RT)
4171 return Results;
4172 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00004173 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00004174 return Results;
4175
Alp Tokerb6cc5922014-05-03 03:45:55 +00004176 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00004177 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00004178 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00004179
4180 // We just need to include all members of the right kind turned up by the
4181 // filter, at this point.
4182 if (S.LookupQualifiedName(R, RT->getDecl()))
4183 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4184 NamedDecl *decl = (*I)->getUnderlyingDecl();
4185 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4186 Results.insert(FK);
4187 }
4188 return Results;
4189}
4190
Richard Smith2868a732014-02-28 01:36:39 +00004191/// Check if we could call '.c_str()' on an object.
4192///
4193/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4194/// allow the call, or if it would be ambiguous).
4195bool Sema::hasCStrMethod(const Expr *E) {
4196 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4197 MethodSet Results =
4198 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4199 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4200 MI != ME; ++MI)
4201 if ((*MI)->getMinRequiredArguments() == 0)
4202 return true;
4203 return false;
4204}
4205
Richard Smith55ce3522012-06-25 20:30:08 +00004206// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004207// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00004208// Returns true when a c_str() conversion method is found.
4209bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00004210 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00004211 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4212
4213 MethodSet Results =
4214 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4215
4216 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4217 MI != ME; ++MI) {
4218 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00004219 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00004220 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00004221 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00004222 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00004223 S.Diag(E->getLocStart(), diag::note_printf_c_str)
4224 << "c_str()"
4225 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4226 return true;
4227 }
4228 }
4229
4230 return false;
4231}
4232
Ted Kremenekab278de2010-01-28 23:39:18 +00004233bool
Ted Kremenek02087932010-07-16 02:11:22 +00004234CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00004235 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00004236 const char *startSpecifier,
4237 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004238 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00004239 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004240 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00004241
Ted Kremenek6cd69422010-07-19 22:01:06 +00004242 if (FS.consumesDataArgument()) {
4243 if (atFirstArg) {
4244 atFirstArg = false;
4245 usesPositionalArgs = FS.usesPositionalArg();
4246 }
4247 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004248 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4249 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004250 return false;
4251 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004252 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004253
Ted Kremenekd1668192010-02-27 01:41:03 +00004254 // First check if the field width, precision, and conversion specifier
4255 // have matching data arguments.
4256 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4257 startSpecifier, specifierLen)) {
4258 return false;
4259 }
4260
4261 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4262 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004263 return false;
4264 }
4265
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004266 if (!CS.consumesDataArgument()) {
4267 // FIXME: Technically specifying a precision or field width here
4268 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004269 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004270 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004271
Ted Kremenek4a49d982010-02-26 19:18:41 +00004272 // Consume the argument.
4273 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004274 if (argIndex < NumDataArgs) {
4275 // The check to see if the argIndex is valid will come later.
4276 // We set the bit here because we may exit early from this
4277 // function if we encounter some other error.
4278 CoveredArgs.set(argIndex);
4279 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004280
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004281 // FreeBSD kernel extensions.
4282 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4283 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4284 // We need at least two arguments.
4285 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4286 return false;
4287
4288 // Claim the second argument.
4289 CoveredArgs.set(argIndex + 1);
4290
4291 // Type check the first argument (int for %b, pointer for %D)
4292 const Expr *Ex = getDataArg(argIndex);
4293 const analyze_printf::ArgType &AT =
4294 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4295 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4296 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4297 EmitFormatDiagnostic(
4298 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4299 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4300 << false << Ex->getSourceRange(),
4301 Ex->getLocStart(), /*IsStringLocation*/false,
4302 getSpecifierRange(startSpecifier, specifierLen));
4303
4304 // Type check the second argument (char * for both %b and %D)
4305 Ex = getDataArg(argIndex + 1);
4306 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4307 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4308 EmitFormatDiagnostic(
4309 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4310 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4311 << false << Ex->getSourceRange(),
4312 Ex->getLocStart(), /*IsStringLocation*/false,
4313 getSpecifierRange(startSpecifier, specifierLen));
4314
4315 return true;
4316 }
4317
Ted Kremenek4a49d982010-02-26 19:18:41 +00004318 // Check for using an Objective-C specific conversion specifier
4319 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004320 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004321 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4322 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004323 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004324
Tom Careb49ec692010-06-17 19:00:27 +00004325 // Check for invalid use of field width
4326 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004327 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004328 startSpecifier, specifierLen);
4329 }
4330
4331 // Check for invalid use of precision
4332 if (!FS.hasValidPrecision()) {
4333 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4334 startSpecifier, specifierLen);
4335 }
4336
4337 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004338 if (!FS.hasValidThousandsGroupingPrefix())
4339 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004340 if (!FS.hasValidLeadingZeros())
4341 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4342 if (!FS.hasValidPlusPrefix())
4343 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004344 if (!FS.hasValidSpacePrefix())
4345 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004346 if (!FS.hasValidAlternativeForm())
4347 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4348 if (!FS.hasValidLeftJustified())
4349 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4350
4351 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004352 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4353 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4354 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004355 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4356 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4357 startSpecifier, specifierLen);
4358
4359 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004360 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004361 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4362 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004363 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004364 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004365 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004366 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4367 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004368
Jordan Rose92303592012-09-08 04:00:03 +00004369 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4370 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4371
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004372 // The remaining checks depend on the data arguments.
4373 if (HasVAListArg)
4374 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004375
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004376 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004377 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004378
Jordan Rose58bbe422012-07-19 18:10:08 +00004379 const Expr *Arg = getDataArg(argIndex);
4380 if (!Arg)
4381 return true;
4382
4383 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004384}
4385
Jordan Roseaee34382012-09-05 22:56:26 +00004386static bool requiresParensToAddCast(const Expr *E) {
4387 // FIXME: We should have a general way to reason about operator
4388 // precedence and whether parens are actually needed here.
4389 // Take care of a few common cases where they aren't.
4390 const Expr *Inside = E->IgnoreImpCasts();
4391 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4392 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4393
4394 switch (Inside->getStmtClass()) {
4395 case Stmt::ArraySubscriptExprClass:
4396 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004397 case Stmt::CharacterLiteralClass:
4398 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004399 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004400 case Stmt::FloatingLiteralClass:
4401 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004402 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004403 case Stmt::ObjCArrayLiteralClass:
4404 case Stmt::ObjCBoolLiteralExprClass:
4405 case Stmt::ObjCBoxedExprClass:
4406 case Stmt::ObjCDictionaryLiteralClass:
4407 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004408 case Stmt::ObjCIvarRefExprClass:
4409 case Stmt::ObjCMessageExprClass:
4410 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004411 case Stmt::ObjCStringLiteralClass:
4412 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004413 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004414 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004415 case Stmt::UnaryOperatorClass:
4416 return false;
4417 default:
4418 return true;
4419 }
4420}
4421
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004422static std::pair<QualType, StringRef>
4423shouldNotPrintDirectly(const ASTContext &Context,
4424 QualType IntendedTy,
4425 const Expr *E) {
4426 // Use a 'while' to peel off layers of typedefs.
4427 QualType TyTy = IntendedTy;
4428 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4429 StringRef Name = UserTy->getDecl()->getName();
4430 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4431 .Case("NSInteger", Context.LongTy)
4432 .Case("NSUInteger", Context.UnsignedLongTy)
4433 .Case("SInt32", Context.IntTy)
4434 .Case("UInt32", Context.UnsignedIntTy)
4435 .Default(QualType());
4436
4437 if (!CastTy.isNull())
4438 return std::make_pair(CastTy, Name);
4439
4440 TyTy = UserTy->desugar();
4441 }
4442
4443 // Strip parens if necessary.
4444 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4445 return shouldNotPrintDirectly(Context,
4446 PE->getSubExpr()->getType(),
4447 PE->getSubExpr());
4448
4449 // If this is a conditional expression, then its result type is constructed
4450 // via usual arithmetic conversions and thus there might be no necessary
4451 // typedef sugar there. Recurse to operands to check for NSInteger &
4452 // Co. usage condition.
4453 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4454 QualType TrueTy, FalseTy;
4455 StringRef TrueName, FalseName;
4456
4457 std::tie(TrueTy, TrueName) =
4458 shouldNotPrintDirectly(Context,
4459 CO->getTrueExpr()->getType(),
4460 CO->getTrueExpr());
4461 std::tie(FalseTy, FalseName) =
4462 shouldNotPrintDirectly(Context,
4463 CO->getFalseExpr()->getType(),
4464 CO->getFalseExpr());
4465
4466 if (TrueTy == FalseTy)
4467 return std::make_pair(TrueTy, TrueName);
4468 else if (TrueTy.isNull())
4469 return std::make_pair(FalseTy, FalseName);
4470 else if (FalseTy.isNull())
4471 return std::make_pair(TrueTy, TrueName);
4472 }
4473
4474 return std::make_pair(QualType(), StringRef());
4475}
4476
Richard Smith55ce3522012-06-25 20:30:08 +00004477bool
4478CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4479 const char *StartSpecifier,
4480 unsigned SpecifierLen,
4481 const Expr *E) {
4482 using namespace analyze_format_string;
4483 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004484 // Now type check the data expression that matches the
4485 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004486 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4487 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004488 if (!AT.isValid())
4489 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004490
Jordan Rose598ec092012-12-05 18:44:40 +00004491 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004492 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4493 ExprTy = TET->getUnderlyingExpr()->getType();
4494 }
4495
Seth Cantrellb4802962015-03-04 03:12:10 +00004496 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4497
4498 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004499 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004500 }
Jordan Rose98709982012-06-04 22:48:57 +00004501
Jordan Rose22b74712012-09-05 22:56:19 +00004502 // Look through argument promotions for our error message's reported type.
4503 // This includes the integral and floating promotions, but excludes array
4504 // and function pointer decay; seeing that an argument intended to be a
4505 // string has type 'char [6]' is probably more confusing than 'char *'.
4506 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4507 if (ICE->getCastKind() == CK_IntegralCast ||
4508 ICE->getCastKind() == CK_FloatingCast) {
4509 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004510 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004511
4512 // Check if we didn't match because of an implicit cast from a 'char'
4513 // or 'short' to an 'int'. This is done because printf is a varargs
4514 // function.
4515 if (ICE->getType() == S.Context.IntTy ||
4516 ICE->getType() == S.Context.UnsignedIntTy) {
4517 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004518 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004519 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004520 }
Jordan Rose98709982012-06-04 22:48:57 +00004521 }
Jordan Rose598ec092012-12-05 18:44:40 +00004522 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4523 // Special case for 'a', which has type 'int' in C.
4524 // Note, however, that we do /not/ want to treat multibyte constants like
4525 // 'MooV' as characters! This form is deprecated but still exists.
4526 if (ExprTy == S.Context.IntTy)
4527 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4528 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004529 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004530
Jordan Rosebc53ed12014-05-31 04:12:14 +00004531 // Look through enums to their underlying type.
4532 bool IsEnum = false;
4533 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4534 ExprTy = EnumTy->getDecl()->getIntegerType();
4535 IsEnum = true;
4536 }
4537
Jordan Rose0e5badd2012-12-05 18:44:49 +00004538 // %C in an Objective-C context prints a unichar, not a wchar_t.
4539 // If the argument is an integer of some kind, believe the %C and suggest
4540 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004541 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004542 if (ObjCContext &&
4543 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4544 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4545 !ExprTy->isCharType()) {
4546 // 'unichar' is defined as a typedef of unsigned short, but we should
4547 // prefer using the typedef if it is visible.
4548 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004549
4550 // While we are here, check if the value is an IntegerLiteral that happens
4551 // to be within the valid range.
4552 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4553 const llvm::APInt &V = IL->getValue();
4554 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4555 return true;
4556 }
4557
Jordan Rose0e5badd2012-12-05 18:44:49 +00004558 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4559 Sema::LookupOrdinaryName);
4560 if (S.LookupName(Result, S.getCurScope())) {
4561 NamedDecl *ND = Result.getFoundDecl();
4562 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4563 if (TD->getUnderlyingType() == IntendedTy)
4564 IntendedTy = S.Context.getTypedefType(TD);
4565 }
4566 }
4567 }
4568
4569 // Special-case some of Darwin's platform-independence types by suggesting
4570 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004571 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004572 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004573 QualType CastTy;
4574 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4575 if (!CastTy.isNull()) {
4576 IntendedTy = CastTy;
4577 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004578 }
4579 }
4580
Jordan Rose22b74712012-09-05 22:56:19 +00004581 // We may be able to offer a FixItHint if it is a supported type.
4582 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004583 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004584 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004585
Jordan Rose22b74712012-09-05 22:56:19 +00004586 if (success) {
4587 // Get the fix string from the fixed format specifier
4588 SmallString<16> buf;
4589 llvm::raw_svector_ostream os(buf);
4590 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004591
Jordan Roseaee34382012-09-05 22:56:26 +00004592 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4593
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004594 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004595 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4596 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4597 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4598 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004599 // In this case, the specifier is wrong and should be changed to match
4600 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004601 EmitFormatDiagnostic(S.PDiag(diag)
4602 << AT.getRepresentativeTypeName(S.Context)
4603 << IntendedTy << IsEnum << E->getSourceRange(),
4604 E->getLocStart(),
4605 /*IsStringLocation*/ false, SpecRange,
4606 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004607 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004608 // The canonical type for formatting this value is different from the
4609 // actual type of the expression. (This occurs, for example, with Darwin's
4610 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4611 // should be printed as 'long' for 64-bit compatibility.)
4612 // Rather than emitting a normal format/argument mismatch, we want to
4613 // add a cast to the recommended type (and correct the format string
4614 // if necessary).
4615 SmallString<16> CastBuf;
4616 llvm::raw_svector_ostream CastFix(CastBuf);
4617 CastFix << "(";
4618 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4619 CastFix << ")";
4620
4621 SmallVector<FixItHint,4> Hints;
4622 if (!AT.matchesType(S.Context, IntendedTy))
4623 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4624
4625 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4626 // If there's already a cast present, just replace it.
4627 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4628 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4629
4630 } else if (!requiresParensToAddCast(E)) {
4631 // If the expression has high enough precedence,
4632 // just write the C-style cast.
4633 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4634 CastFix.str()));
4635 } else {
4636 // Otherwise, add parens around the expression as well as the cast.
4637 CastFix << "(";
4638 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4639 CastFix.str()));
4640
Alp Tokerb6cc5922014-05-03 03:45:55 +00004641 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004642 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4643 }
4644
Jordan Rose0e5badd2012-12-05 18:44:49 +00004645 if (ShouldNotPrintDirectly) {
4646 // The expression has a type that should not be printed directly.
4647 // We extract the name from the typedef because we don't want to show
4648 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004649 StringRef Name;
4650 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4651 Name = TypedefTy->getDecl()->getName();
4652 else
4653 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004654 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004655 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004656 << E->getSourceRange(),
4657 E->getLocStart(), /*IsStringLocation=*/false,
4658 SpecRange, Hints);
4659 } else {
4660 // In this case, the expression could be printed using a different
4661 // specifier, but we've decided that the specifier is probably correct
4662 // and we should cast instead. Just use the normal warning message.
4663 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004664 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4665 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004666 << E->getSourceRange(),
4667 E->getLocStart(), /*IsStringLocation*/false,
4668 SpecRange, Hints);
4669 }
Jordan Roseaee34382012-09-05 22:56:26 +00004670 }
Jordan Rose22b74712012-09-05 22:56:19 +00004671 } else {
4672 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4673 SpecifierLen);
4674 // Since the warning for passing non-POD types to variadic functions
4675 // was deferred until now, we emit a warning for non-POD
4676 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004677 switch (S.isValidVarArgType(ExprTy)) {
4678 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004679 case Sema::VAK_ValidInCXX11: {
4680 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4681 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4682 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4683 }
Richard Smithd7293d72013-08-05 18:49:43 +00004684
Seth Cantrellb4802962015-03-04 03:12:10 +00004685 EmitFormatDiagnostic(
4686 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4687 << IsEnum << CSR << E->getSourceRange(),
4688 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4689 break;
4690 }
Richard Smithd7293d72013-08-05 18:49:43 +00004691 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004692 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004693 EmitFormatDiagnostic(
4694 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004695 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004696 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004697 << CallType
4698 << AT.getRepresentativeTypeName(S.Context)
4699 << CSR
4700 << E->getSourceRange(),
4701 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004702 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004703 break;
4704
4705 case Sema::VAK_Invalid:
4706 if (ExprTy->isObjCObjectType())
4707 EmitFormatDiagnostic(
4708 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4709 << S.getLangOpts().CPlusPlus11
4710 << ExprTy
4711 << CallType
4712 << AT.getRepresentativeTypeName(S.Context)
4713 << CSR
4714 << E->getSourceRange(),
4715 E->getLocStart(), /*IsStringLocation*/false, CSR);
4716 else
4717 // FIXME: If this is an initializer list, suggest removing the braces
4718 // or inserting a cast to the target type.
4719 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4720 << isa<InitListExpr>(E) << ExprTy << CallType
4721 << AT.getRepresentativeTypeName(S.Context)
4722 << E->getSourceRange();
4723 break;
4724 }
4725
4726 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4727 "format string specifier index out of range");
4728 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004729 }
4730
Ted Kremenekab278de2010-01-28 23:39:18 +00004731 return true;
4732}
4733
Ted Kremenek02087932010-07-16 02:11:22 +00004734//===--- CHECK: Scanf format string checking ------------------------------===//
4735
4736namespace {
4737class CheckScanfHandler : public CheckFormatHandler {
4738public:
4739 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4740 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004741 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004742 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004743 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004744 Sema::VariadicCallType CallType,
4745 llvm::SmallBitVector &CheckedVarArgs)
4746 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4747 numDataArgs, beg, hasVAListArg,
4748 Args, formatIdx, inFunctionCall, CallType,
4749 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004750 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004751
4752 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4753 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004754 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004755
4756 bool HandleInvalidScanfConversionSpecifier(
4757 const analyze_scanf::ScanfSpecifier &FS,
4758 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004759 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004760
Craig Toppere14c0f82014-03-12 04:55:44 +00004761 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004762};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004763} // end anonymous namespace
Ted Kremenekab278de2010-01-28 23:39:18 +00004764
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004765void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4766 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004767 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4768 getLocationOfByte(end), /*IsStringLocation*/true,
4769 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004770}
4771
Ted Kremenekce815422010-07-19 21:25:57 +00004772bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4773 const analyze_scanf::ScanfSpecifier &FS,
4774 const char *startSpecifier,
4775 unsigned specifierLen) {
4776
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004777 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004778 FS.getConversionSpecifier();
4779
4780 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4781 getLocationOfByte(CS.getStart()),
4782 startSpecifier, specifierLen,
4783 CS.getStart(), CS.getLength());
4784}
4785
Ted Kremenek02087932010-07-16 02:11:22 +00004786bool CheckScanfHandler::HandleScanfSpecifier(
4787 const analyze_scanf::ScanfSpecifier &FS,
4788 const char *startSpecifier,
4789 unsigned specifierLen) {
Ted Kremenek02087932010-07-16 02:11:22 +00004790 using namespace analyze_scanf;
4791 using namespace analyze_format_string;
4792
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004793 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004794
Ted Kremenek6cd69422010-07-19 22:01:06 +00004795 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4796 // be used to decide if we are using positional arguments consistently.
4797 if (FS.consumesDataArgument()) {
4798 if (atFirstArg) {
4799 atFirstArg = false;
4800 usesPositionalArgs = FS.usesPositionalArg();
4801 }
4802 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004803 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4804 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004805 return false;
4806 }
Ted Kremenek02087932010-07-16 02:11:22 +00004807 }
4808
4809 // Check if the field with is non-zero.
4810 const OptionalAmount &Amt = FS.getFieldWidth();
4811 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4812 if (Amt.getConstantAmount() == 0) {
4813 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4814 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004815 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4816 getLocationOfByte(Amt.getStart()),
4817 /*IsStringLocation*/true, R,
4818 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004819 }
4820 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004821
Ted Kremenek02087932010-07-16 02:11:22 +00004822 if (!FS.consumesDataArgument()) {
4823 // FIXME: Technically specifying a precision or field width here
4824 // makes no sense. Worth issuing a warning at some point.
4825 return true;
4826 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004827
Ted Kremenek02087932010-07-16 02:11:22 +00004828 // Consume the argument.
4829 unsigned argIndex = FS.getArgIndex();
4830 if (argIndex < NumDataArgs) {
4831 // The check to see if the argIndex is valid will come later.
4832 // We set the bit here because we may exit early from this
4833 // function if we encounter some other error.
4834 CoveredArgs.set(argIndex);
4835 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004836
Ted Kremenek4407ea42010-07-20 20:04:47 +00004837 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004838 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004839 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4840 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004841 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004842 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004843 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004844 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4845 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004846
Jordan Rose92303592012-09-08 04:00:03 +00004847 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4848 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4849
Ted Kremenek02087932010-07-16 02:11:22 +00004850 // The remaining checks depend on the data arguments.
4851 if (HasVAListArg)
4852 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004853
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004854 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004855 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004856
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004857 // Check that the argument type matches the format specifier.
4858 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004859 if (!Ex)
4860 return true;
4861
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004862 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004863
4864 if (!AT.isValid()) {
4865 return true;
4866 }
4867
Seth Cantrellb4802962015-03-04 03:12:10 +00004868 analyze_format_string::ArgType::MatchKind match =
4869 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004870 if (match == analyze_format_string::ArgType::Match) {
4871 return true;
4872 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004873
Seth Cantrell79340072015-03-04 05:58:08 +00004874 ScanfSpecifier fixedFS = FS;
4875 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4876 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004877
Seth Cantrell79340072015-03-04 05:58:08 +00004878 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4879 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4880 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4881 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004882
Seth Cantrell79340072015-03-04 05:58:08 +00004883 if (success) {
4884 // Get the fix string from the fixed format specifier.
4885 SmallString<128> buf;
4886 llvm::raw_svector_ostream os(buf);
4887 fixedFS.toString(os);
4888
4889 EmitFormatDiagnostic(
4890 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4891 << Ex->getType() << false << Ex->getSourceRange(),
4892 Ex->getLocStart(),
4893 /*IsStringLocation*/ false,
4894 getSpecifierRange(startSpecifier, specifierLen),
4895 FixItHint::CreateReplacement(
4896 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4897 } else {
4898 EmitFormatDiagnostic(S.PDiag(diag)
4899 << AT.getRepresentativeTypeName(S.Context)
4900 << Ex->getType() << false << Ex->getSourceRange(),
4901 Ex->getLocStart(),
4902 /*IsStringLocation*/ false,
4903 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004904 }
4905
Ted Kremenek02087932010-07-16 02:11:22 +00004906 return true;
4907}
4908
4909void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004910 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004911 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004912 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004913 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004914 bool inFunctionCall, VariadicCallType CallType,
4915 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenekab278de2010-01-28 23:39:18 +00004916 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004917 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004918 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004919 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004920 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4921 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004922 return;
4923 }
Ted Kremenek02087932010-07-16 02:11:22 +00004924
Ted Kremenekab278de2010-01-28 23:39:18 +00004925 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004926 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004927 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004928 // Account for cases where the string literal is truncated in a declaration.
4929 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4930 assert(T && "String literal not of constant array type!");
4931 size_t TypeSize = T->getSize().getZExtValue();
4932 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004933 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004934
4935 // Emit a warning if the string literal is truncated and does not contain an
4936 // embedded null character.
4937 if (TypeSize <= StrRef.size() &&
4938 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4939 CheckFormatHandler::EmitFormatDiagnostic(
4940 *this, inFunctionCall, Args[format_idx],
4941 PDiag(diag::warn_printf_format_string_not_null_terminated),
4942 FExpr->getLocStart(),
4943 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4944 return;
4945 }
4946
Ted Kremenekab278de2010-01-28 23:39:18 +00004947 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004948 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004949 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004950 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004951 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4952 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004953 return;
4954 }
Ted Kremenek02087932010-07-16 02:11:22 +00004955
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004956 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004957 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004958 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004959 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004960 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004961 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004962
Hans Wennborg23926bd2011-12-15 10:25:47 +00004963 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004964 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004965 Context.getTargetInfo(),
4966 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004967 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004968 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004969 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004970 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004971 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004972
Hans Wennborg23926bd2011-12-15 10:25:47 +00004973 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004974 getLangOpts(),
4975 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004976 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004977 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004978}
4979
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004980bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4981 // Str - The format string. NOTE: this is NOT null-terminated!
4982 StringRef StrRef = FExpr->getString();
4983 const char *Str = StrRef.data();
4984 // Account for cases where the string literal is truncated in a declaration.
4985 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4986 assert(T && "String literal not of constant array type!");
4987 size_t TypeSize = T->getSize().getZExtValue();
4988 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4989 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4990 getLangOpts(),
4991 Context.getTargetInfo());
4992}
4993
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004994//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4995
4996// Returns the related absolute value function that is larger, of 0 if one
4997// does not exist.
4998static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4999 switch (AbsFunction) {
5000 default:
5001 return 0;
5002
5003 case Builtin::BI__builtin_abs:
5004 return Builtin::BI__builtin_labs;
5005 case Builtin::BI__builtin_labs:
5006 return Builtin::BI__builtin_llabs;
5007 case Builtin::BI__builtin_llabs:
5008 return 0;
5009
5010 case Builtin::BI__builtin_fabsf:
5011 return Builtin::BI__builtin_fabs;
5012 case Builtin::BI__builtin_fabs:
5013 return Builtin::BI__builtin_fabsl;
5014 case Builtin::BI__builtin_fabsl:
5015 return 0;
5016
5017 case Builtin::BI__builtin_cabsf:
5018 return Builtin::BI__builtin_cabs;
5019 case Builtin::BI__builtin_cabs:
5020 return Builtin::BI__builtin_cabsl;
5021 case Builtin::BI__builtin_cabsl:
5022 return 0;
5023
5024 case Builtin::BIabs:
5025 return Builtin::BIlabs;
5026 case Builtin::BIlabs:
5027 return Builtin::BIllabs;
5028 case Builtin::BIllabs:
5029 return 0;
5030
5031 case Builtin::BIfabsf:
5032 return Builtin::BIfabs;
5033 case Builtin::BIfabs:
5034 return Builtin::BIfabsl;
5035 case Builtin::BIfabsl:
5036 return 0;
5037
5038 case Builtin::BIcabsf:
5039 return Builtin::BIcabs;
5040 case Builtin::BIcabs:
5041 return Builtin::BIcabsl;
5042 case Builtin::BIcabsl:
5043 return 0;
5044 }
5045}
5046
5047// Returns the argument type of the absolute value function.
5048static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5049 unsigned AbsType) {
5050 if (AbsType == 0)
5051 return QualType();
5052
5053 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5054 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5055 if (Error != ASTContext::GE_None)
5056 return QualType();
5057
5058 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5059 if (!FT)
5060 return QualType();
5061
5062 if (FT->getNumParams() != 1)
5063 return QualType();
5064
5065 return FT->getParamType(0);
5066}
5067
5068// Returns the best absolute value function, or zero, based on type and
5069// current absolute value function.
5070static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5071 unsigned AbsFunctionKind) {
5072 unsigned BestKind = 0;
5073 uint64_t ArgSize = Context.getTypeSize(ArgType);
5074 for (unsigned Kind = AbsFunctionKind; Kind != 0;
5075 Kind = getLargerAbsoluteValueFunction(Kind)) {
5076 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5077 if (Context.getTypeSize(ParamType) >= ArgSize) {
5078 if (BestKind == 0)
5079 BestKind = Kind;
5080 else if (Context.hasSameType(ParamType, ArgType)) {
5081 BestKind = Kind;
5082 break;
5083 }
5084 }
5085 }
5086 return BestKind;
5087}
5088
5089enum AbsoluteValueKind {
5090 AVK_Integer,
5091 AVK_Floating,
5092 AVK_Complex
5093};
5094
5095static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5096 if (T->isIntegralOrEnumerationType())
5097 return AVK_Integer;
5098 if (T->isRealFloatingType())
5099 return AVK_Floating;
5100 if (T->isAnyComplexType())
5101 return AVK_Complex;
5102
5103 llvm_unreachable("Type not integer, floating, or complex");
5104}
5105
5106// Changes the absolute value function to a different type. Preserves whether
5107// the function is a builtin.
5108static unsigned changeAbsFunction(unsigned AbsKind,
5109 AbsoluteValueKind ValueKind) {
5110 switch (ValueKind) {
5111 case AVK_Integer:
5112 switch (AbsKind) {
5113 default:
5114 return 0;
5115 case Builtin::BI__builtin_fabsf:
5116 case Builtin::BI__builtin_fabs:
5117 case Builtin::BI__builtin_fabsl:
5118 case Builtin::BI__builtin_cabsf:
5119 case Builtin::BI__builtin_cabs:
5120 case Builtin::BI__builtin_cabsl:
5121 return Builtin::BI__builtin_abs;
5122 case Builtin::BIfabsf:
5123 case Builtin::BIfabs:
5124 case Builtin::BIfabsl:
5125 case Builtin::BIcabsf:
5126 case Builtin::BIcabs:
5127 case Builtin::BIcabsl:
5128 return Builtin::BIabs;
5129 }
5130 case AVK_Floating:
5131 switch (AbsKind) {
5132 default:
5133 return 0;
5134 case Builtin::BI__builtin_abs:
5135 case Builtin::BI__builtin_labs:
5136 case Builtin::BI__builtin_llabs:
5137 case Builtin::BI__builtin_cabsf:
5138 case Builtin::BI__builtin_cabs:
5139 case Builtin::BI__builtin_cabsl:
5140 return Builtin::BI__builtin_fabsf;
5141 case Builtin::BIabs:
5142 case Builtin::BIlabs:
5143 case Builtin::BIllabs:
5144 case Builtin::BIcabsf:
5145 case Builtin::BIcabs:
5146 case Builtin::BIcabsl:
5147 return Builtin::BIfabsf;
5148 }
5149 case AVK_Complex:
5150 switch (AbsKind) {
5151 default:
5152 return 0;
5153 case Builtin::BI__builtin_abs:
5154 case Builtin::BI__builtin_labs:
5155 case Builtin::BI__builtin_llabs:
5156 case Builtin::BI__builtin_fabsf:
5157 case Builtin::BI__builtin_fabs:
5158 case Builtin::BI__builtin_fabsl:
5159 return Builtin::BI__builtin_cabsf;
5160 case Builtin::BIabs:
5161 case Builtin::BIlabs:
5162 case Builtin::BIllabs:
5163 case Builtin::BIfabsf:
5164 case Builtin::BIfabs:
5165 case Builtin::BIfabsl:
5166 return Builtin::BIcabsf;
5167 }
5168 }
5169 llvm_unreachable("Unable to convert function");
5170}
5171
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00005172static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005173 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5174 if (!FnInfo)
5175 return 0;
5176
5177 switch (FDecl->getBuiltinID()) {
5178 default:
5179 return 0;
5180 case Builtin::BI__builtin_abs:
5181 case Builtin::BI__builtin_fabs:
5182 case Builtin::BI__builtin_fabsf:
5183 case Builtin::BI__builtin_fabsl:
5184 case Builtin::BI__builtin_labs:
5185 case Builtin::BI__builtin_llabs:
5186 case Builtin::BI__builtin_cabs:
5187 case Builtin::BI__builtin_cabsf:
5188 case Builtin::BI__builtin_cabsl:
5189 case Builtin::BIabs:
5190 case Builtin::BIlabs:
5191 case Builtin::BIllabs:
5192 case Builtin::BIfabs:
5193 case Builtin::BIfabsf:
5194 case Builtin::BIfabsl:
5195 case Builtin::BIcabs:
5196 case Builtin::BIcabsf:
5197 case Builtin::BIcabsl:
5198 return FDecl->getBuiltinID();
5199 }
5200 llvm_unreachable("Unknown Builtin type");
5201}
5202
5203// If the replacement is valid, emit a note with replacement function.
5204// Additionally, suggest including the proper header if not already included.
5205static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00005206 unsigned AbsKind, QualType ArgType) {
5207 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00005208 const char *HeaderName = nullptr;
5209 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005210 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5211 FunctionName = "std::abs";
5212 if (ArgType->isIntegralOrEnumerationType()) {
5213 HeaderName = "cstdlib";
5214 } else if (ArgType->isRealFloatingType()) {
5215 HeaderName = "cmath";
5216 } else {
5217 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005218 }
Richard Trieubeffb832014-04-15 23:47:53 +00005219
5220 // Lookup all std::abs
5221 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00005222 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00005223 R.suppressDiagnostics();
5224 S.LookupQualifiedName(R, Std);
5225
5226 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005227 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00005228 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5229 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5230 } else {
5231 FDecl = dyn_cast<FunctionDecl>(I);
5232 }
5233 if (!FDecl)
5234 continue;
5235
5236 // Found std::abs(), check that they are the right ones.
5237 if (FDecl->getNumParams() != 1)
5238 continue;
5239
5240 // Check that the parameter type can handle the argument.
5241 QualType ParamType = FDecl->getParamDecl(0)->getType();
5242 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5243 S.Context.getTypeSize(ArgType) <=
5244 S.Context.getTypeSize(ParamType)) {
5245 // Found a function, don't need the header hint.
5246 EmitHeaderHint = false;
5247 break;
5248 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005249 }
Richard Trieubeffb832014-04-15 23:47:53 +00005250 }
5251 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005252 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005253 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5254
5255 if (HeaderName) {
5256 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5257 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5258 R.suppressDiagnostics();
5259 S.LookupName(R, S.getCurScope());
5260
5261 if (R.isSingleResult()) {
5262 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5263 if (FD && FD->getBuiltinID() == AbsKind) {
5264 EmitHeaderHint = false;
5265 } else {
5266 return;
5267 }
5268 } else if (!R.empty()) {
5269 return;
5270 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005271 }
5272 }
5273
5274 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005275 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005276
Richard Trieubeffb832014-04-15 23:47:53 +00005277 if (!HeaderName)
5278 return;
5279
5280 if (!EmitHeaderHint)
5281 return;
5282
Alp Toker5d96e0a2014-07-11 20:53:51 +00005283 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5284 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005285}
5286
5287static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5288 if (!FDecl)
5289 return false;
5290
5291 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5292 return false;
5293
5294 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5295
5296 while (ND && ND->isInlineNamespace()) {
5297 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005298 }
Richard Trieubeffb832014-04-15 23:47:53 +00005299
5300 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5301 return false;
5302
5303 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5304 return false;
5305
5306 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005307}
5308
5309// Warn when using the wrong abs() function.
5310void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5311 const FunctionDecl *FDecl,
5312 IdentifierInfo *FnInfo) {
5313 if (Call->getNumArgs() != 1)
5314 return;
5315
5316 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005317 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5318 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005319 return;
5320
5321 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5322 QualType ParamType = Call->getArg(0)->getType();
5323
Alp Toker5d96e0a2014-07-11 20:53:51 +00005324 // Unsigned types cannot be negative. Suggest removing the absolute value
5325 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005326 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005327 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005328 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005329 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5330 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005331 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005332 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5333 return;
5334 }
5335
David Majnemer7f77eb92015-11-15 03:04:34 +00005336 // Taking the absolute value of a pointer is very suspicious, they probably
5337 // wanted to index into an array, dereference a pointer, call a function, etc.
5338 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5339 unsigned DiagType = 0;
5340 if (ArgType->isFunctionType())
5341 DiagType = 1;
5342 else if (ArgType->isArrayType())
5343 DiagType = 2;
5344
5345 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5346 return;
5347 }
5348
Richard Trieubeffb832014-04-15 23:47:53 +00005349 // std::abs has overloads which prevent most of the absolute value problems
5350 // from occurring.
5351 if (IsStdAbs)
5352 return;
5353
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005354 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5355 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5356
5357 // The argument and parameter are the same kind. Check if they are the right
5358 // size.
5359 if (ArgValueKind == ParamValueKind) {
5360 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5361 return;
5362
5363 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5364 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5365 << FDecl << ArgType << ParamType;
5366
5367 if (NewAbsKind == 0)
5368 return;
5369
5370 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005371 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005372 return;
5373 }
5374
5375 // ArgValueKind != ParamValueKind
5376 // The wrong type of absolute value function was used. Attempt to find the
5377 // proper one.
5378 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5379 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5380 if (NewAbsKind == 0)
5381 return;
5382
5383 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5384 << FDecl << ParamValueKind << ArgValueKind;
5385
5386 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005387 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005388}
5389
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005390//===--- CHECK: Standard memory functions ---------------------------------===//
5391
Nico Weber0e6daef2013-12-26 23:38:39 +00005392/// \brief Takes the expression passed to the size_t parameter of functions
5393/// such as memcmp, strncat, etc and warns if it's a comparison.
5394///
5395/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5396static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5397 IdentifierInfo *FnName,
5398 SourceLocation FnLoc,
5399 SourceLocation RParenLoc) {
5400 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5401 if (!Size)
5402 return false;
5403
5404 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5405 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5406 return false;
5407
Nico Weber0e6daef2013-12-26 23:38:39 +00005408 SourceRange SizeRange = Size->getSourceRange();
5409 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5410 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005411 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005412 << FnName << FixItHint::CreateInsertion(
5413 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005414 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005415 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005416 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005417 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5418 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005419
5420 return true;
5421}
5422
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005423/// \brief Determine whether the given type is or contains a dynamic class type
5424/// (e.g., whether it has a vtable).
5425static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5426 bool &IsContained) {
5427 // Look through array types while ignoring qualifiers.
5428 const Type *Ty = T->getBaseElementTypeUnsafe();
5429 IsContained = false;
5430
5431 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5432 RD = RD ? RD->getDefinition() : nullptr;
5433 if (!RD)
5434 return nullptr;
5435
5436 if (RD->isDynamicClass())
5437 return RD;
5438
5439 // Check all the fields. If any bases were dynamic, the class is dynamic.
5440 // It's impossible for a class to transitively contain itself by value, so
5441 // infinite recursion is impossible.
5442 for (auto *FD : RD->fields()) {
5443 bool SubContained;
5444 if (const CXXRecordDecl *ContainedRD =
5445 getContainedDynamicClass(FD->getType(), SubContained)) {
5446 IsContained = true;
5447 return ContainedRD;
5448 }
5449 }
5450
5451 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005452}
5453
Chandler Carruth889ed862011-06-21 23:04:20 +00005454/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005455/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005456static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005457 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005458 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5459 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5460 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005461
Craig Topperc3ec1492014-05-26 06:22:03 +00005462 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005463}
5464
Chandler Carruth889ed862011-06-21 23:04:20 +00005465/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005466static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005467 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5468 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5469 if (SizeOf->getKind() == clang::UETT_SizeOf)
5470 return SizeOf->getTypeOfArgument();
5471
5472 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005473}
5474
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005475/// \brief Check for dangerous or invalid arguments to memset().
5476///
Chandler Carruthac687262011-06-03 06:23:57 +00005477/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005478/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5479/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005480///
5481/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005482void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005483 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005484 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005485 assert(BId != 0);
5486
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005487 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005488 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005489 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005490 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005491 return;
5492
Anna Zaks22122702012-01-17 00:37:07 +00005493 unsigned LastArg = (BId == Builtin::BImemset ||
5494 BId == Builtin::BIstrndup ? 1 : 2);
5495 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005496 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005497
Nico Weber0e6daef2013-12-26 23:38:39 +00005498 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5499 Call->getLocStart(), Call->getRParenLoc()))
5500 return;
5501
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005502 // We have special checking when the length is a sizeof expression.
5503 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5504 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5505 llvm::FoldingSetNodeID SizeOfArgID;
5506
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005507 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5508 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005509 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005510
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005511 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005512 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005513 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005514 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005515
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005516 // Never warn about void type pointers. This can be used to suppress
5517 // false positives.
5518 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005519 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005520
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005521 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5522 // actually comparing the expressions for equality. Because computing the
5523 // expression IDs can be expensive, we only do this if the diagnostic is
5524 // enabled.
5525 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005526 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5527 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005528 // We only compute IDs for expressions if the warning is enabled, and
5529 // cache the sizeof arg's ID.
5530 if (SizeOfArgID == llvm::FoldingSetNodeID())
5531 SizeOfArg->Profile(SizeOfArgID, Context, true);
5532 llvm::FoldingSetNodeID DestID;
5533 Dest->Profile(DestID, Context, true);
5534 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005535 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5536 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005537 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005538 StringRef ReadableName = FnName->getName();
5539
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005540 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005541 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005542 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005543 if (!PointeeTy->isIncompleteType() &&
5544 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005545 ActionIdx = 2; // If the pointee's size is sizeof(char),
5546 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005547
5548 // If the function is defined as a builtin macro, do not show macro
5549 // expansion.
5550 SourceLocation SL = SizeOfArg->getExprLoc();
5551 SourceRange DSR = Dest->getSourceRange();
5552 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005553 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005554
5555 if (SM.isMacroArgExpansion(SL)) {
5556 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5557 SL = SM.getSpellingLoc(SL);
5558 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5559 SM.getSpellingLoc(DSR.getEnd()));
5560 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5561 SM.getSpellingLoc(SSR.getEnd()));
5562 }
5563
Anna Zaksd08d9152012-05-30 23:14:52 +00005564 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005565 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005566 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005567 << PointeeTy
5568 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005569 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005570 << SSR);
5571 DiagRuntimeBehavior(SL, SizeOfArg,
5572 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5573 << ActionIdx
5574 << SSR);
5575
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005576 break;
5577 }
5578 }
5579
5580 // Also check for cases where the sizeof argument is the exact same
5581 // type as the memory argument, and where it points to a user-defined
5582 // record type.
5583 if (SizeOfArgTy != QualType()) {
5584 if (PointeeTy->isRecordType() &&
5585 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5586 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5587 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5588 << FnName << SizeOfArgTy << ArgIdx
5589 << PointeeTy << Dest->getSourceRange()
5590 << LenExpr->getSourceRange());
5591 break;
5592 }
Nico Weberc5e73862011-06-14 16:14:58 +00005593 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005594 } else if (DestTy->isArrayType()) {
5595 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005596 }
Nico Weberc5e73862011-06-14 16:14:58 +00005597
Nico Weberc44b35e2015-03-21 17:37:46 +00005598 if (PointeeTy == QualType())
5599 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005600
Nico Weberc44b35e2015-03-21 17:37:46 +00005601 // Always complain about dynamic classes.
5602 bool IsContained;
5603 if (const CXXRecordDecl *ContainedRD =
5604 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005605
Nico Weberc44b35e2015-03-21 17:37:46 +00005606 unsigned OperationType = 0;
5607 // "overwritten" if we're warning about the destination for any call
5608 // but memcmp; otherwise a verb appropriate to the call.
5609 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5610 if (BId == Builtin::BImemcpy)
5611 OperationType = 1;
5612 else if(BId == Builtin::BImemmove)
5613 OperationType = 2;
5614 else if (BId == Builtin::BImemcmp)
5615 OperationType = 3;
5616 }
5617
John McCall31168b02011-06-15 23:02:42 +00005618 DiagRuntimeBehavior(
5619 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005620 PDiag(diag::warn_dyn_class_memaccess)
5621 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5622 << FnName << IsContained << ContainedRD << OperationType
5623 << Call->getCallee()->getSourceRange());
5624 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5625 BId != Builtin::BImemset)
5626 DiagRuntimeBehavior(
5627 Dest->getExprLoc(), Dest,
5628 PDiag(diag::warn_arc_object_memaccess)
5629 << ArgIdx << FnName << PointeeTy
5630 << Call->getCallee()->getSourceRange());
5631 else
5632 continue;
5633
5634 DiagRuntimeBehavior(
5635 Dest->getExprLoc(), Dest,
5636 PDiag(diag::note_bad_memaccess_silence)
5637 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5638 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005639 }
5640}
5641
Ted Kremenek6865f772011-08-18 20:55:45 +00005642// A little helper routine: ignore addition and subtraction of integer literals.
5643// This intentionally does not ignore all integer constant expressions because
5644// we don't want to remove sizeof().
5645static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5646 Ex = Ex->IgnoreParenCasts();
5647
5648 for (;;) {
5649 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5650 if (!BO || !BO->isAdditiveOp())
5651 break;
5652
5653 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5654 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5655
5656 if (isa<IntegerLiteral>(RHS))
5657 Ex = LHS;
5658 else if (isa<IntegerLiteral>(LHS))
5659 Ex = RHS;
5660 else
5661 break;
5662 }
5663
5664 return Ex;
5665}
5666
Anna Zaks13b08572012-08-08 21:42:23 +00005667static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5668 ASTContext &Context) {
5669 // Only handle constant-sized or VLAs, but not flexible members.
5670 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5671 // Only issue the FIXIT for arrays of size > 1.
5672 if (CAT->getSize().getSExtValue() <= 1)
5673 return false;
5674 } else if (!Ty->isVariableArrayType()) {
5675 return false;
5676 }
5677 return true;
5678}
5679
Ted Kremenek6865f772011-08-18 20:55:45 +00005680// Warn if the user has made the 'size' argument to strlcpy or strlcat
5681// be the size of the source, instead of the destination.
5682void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5683 IdentifierInfo *FnName) {
5684
5685 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005686 unsigned NumArgs = Call->getNumArgs();
5687 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005688 return;
5689
5690 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5691 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005692 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005693
5694 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5695 Call->getLocStart(), Call->getRParenLoc()))
5696 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005697
5698 // Look for 'strlcpy(dst, x, sizeof(x))'
5699 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5700 CompareWithSrc = Ex;
5701 else {
5702 // Look for 'strlcpy(dst, x, strlen(x))'
5703 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005704 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5705 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005706 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5707 }
5708 }
5709
5710 if (!CompareWithSrc)
5711 return;
5712
5713 // Determine if the argument to sizeof/strlen is equal to the source
5714 // argument. In principle there's all kinds of things you could do
5715 // here, for instance creating an == expression and evaluating it with
5716 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5717 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5718 if (!SrcArgDRE)
5719 return;
5720
5721 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5722 if (!CompareWithSrcDRE ||
5723 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5724 return;
5725
5726 const Expr *OriginalSizeArg = Call->getArg(2);
5727 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5728 << OriginalSizeArg->getSourceRange() << FnName;
5729
5730 // Output a FIXIT hint if the destination is an array (rather than a
5731 // pointer to an array). This could be enhanced to handle some
5732 // pointers if we know the actual size, like if DstArg is 'array+2'
5733 // we could say 'sizeof(array)-2'.
5734 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005735 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005736 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005737
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005738 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005739 llvm::raw_svector_ostream OS(sizeString);
5740 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005741 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005742 OS << ")";
5743
5744 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5745 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5746 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005747}
5748
Anna Zaks314cd092012-02-01 19:08:57 +00005749/// Check if two expressions refer to the same declaration.
5750static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5751 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5752 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5753 return D1->getDecl() == D2->getDecl();
5754 return false;
5755}
5756
5757static const Expr *getStrlenExprArg(const Expr *E) {
5758 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5759 const FunctionDecl *FD = CE->getDirectCallee();
5760 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005761 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005762 return CE->getArg(0)->IgnoreParenCasts();
5763 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005764 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005765}
5766
5767// Warn on anti-patterns as the 'size' argument to strncat.
5768// The correct size argument should look like following:
5769// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5770void Sema::CheckStrncatArguments(const CallExpr *CE,
5771 IdentifierInfo *FnName) {
5772 // Don't crash if the user has the wrong number of arguments.
5773 if (CE->getNumArgs() < 3)
5774 return;
5775 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5776 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5777 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5778
Nico Weber0e6daef2013-12-26 23:38:39 +00005779 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5780 CE->getRParenLoc()))
5781 return;
5782
Anna Zaks314cd092012-02-01 19:08:57 +00005783 // Identify common expressions, which are wrongly used as the size argument
5784 // to strncat and may lead to buffer overflows.
5785 unsigned PatternType = 0;
5786 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5787 // - sizeof(dst)
5788 if (referToTheSameDecl(SizeOfArg, DstArg))
5789 PatternType = 1;
5790 // - sizeof(src)
5791 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5792 PatternType = 2;
5793 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5794 if (BE->getOpcode() == BO_Sub) {
5795 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5796 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5797 // - sizeof(dst) - strlen(dst)
5798 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5799 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5800 PatternType = 1;
5801 // - sizeof(src) - (anything)
5802 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5803 PatternType = 2;
5804 }
5805 }
5806
5807 if (PatternType == 0)
5808 return;
5809
Anna Zaks5069aa32012-02-03 01:27:37 +00005810 // Generate the diagnostic.
5811 SourceLocation SL = LenArg->getLocStart();
5812 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005813 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005814
5815 // If the function is defined as a builtin macro, do not show macro expansion.
5816 if (SM.isMacroArgExpansion(SL)) {
5817 SL = SM.getSpellingLoc(SL);
5818 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5819 SM.getSpellingLoc(SR.getEnd()));
5820 }
5821
Anna Zaks13b08572012-08-08 21:42:23 +00005822 // Check if the destination is an array (rather than a pointer to an array).
5823 QualType DstTy = DstArg->getType();
5824 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5825 Context);
5826 if (!isKnownSizeArray) {
5827 if (PatternType == 1)
5828 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5829 else
5830 Diag(SL, diag::warn_strncat_src_size) << SR;
5831 return;
5832 }
5833
Anna Zaks314cd092012-02-01 19:08:57 +00005834 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005835 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005836 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005837 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005838
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005839 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005840 llvm::raw_svector_ostream OS(sizeString);
5841 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005842 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005843 OS << ") - ";
5844 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005845 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005846 OS << ") - 1";
5847
Anna Zaks5069aa32012-02-03 01:27:37 +00005848 Diag(SL, diag::note_strncat_wrong_size)
5849 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005850}
5851
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005852//===--- CHECK: Return Address of Stack Variable --------------------------===//
5853
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005854static const Expr *EvalVal(const Expr *E,
5855 SmallVectorImpl<const DeclRefExpr *> &refVars,
5856 const Decl *ParentDecl);
5857static const Expr *EvalAddr(const Expr *E,
5858 SmallVectorImpl<const DeclRefExpr *> &refVars,
5859 const Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005860
5861/// CheckReturnStackAddr - Check if a return statement returns the address
5862/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005863static void
5864CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5865 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005866
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005867 const Expr *stackE = nullptr;
5868 SmallVector<const DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005869
5870 // Perform checking for returned stack addresses, local blocks,
5871 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005872 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005873 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005874 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005875 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005876 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005877 }
5878
Craig Topperc3ec1492014-05-26 06:22:03 +00005879 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005880 return; // Nothing suspicious was found.
5881
5882 SourceLocation diagLoc;
5883 SourceRange diagRange;
5884 if (refVars.empty()) {
5885 diagLoc = stackE->getLocStart();
5886 diagRange = stackE->getSourceRange();
5887 } else {
5888 // We followed through a reference variable. 'stackE' contains the
5889 // problematic expression but we will warn at the return statement pointing
5890 // at the reference variable. We will later display the "trail" of
5891 // reference variables using notes.
5892 diagLoc = refVars[0]->getLocStart();
5893 diagRange = refVars[0]->getSourceRange();
5894 }
5895
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005896 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
5897 // address of local var
Craig Topperda7b27f2015-11-17 05:40:09 +00005898 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005899 << DR->getDecl()->getDeclName() << diagRange;
5900 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005901 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005902 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005903 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005904 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00005905 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
5906 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005907 }
5908
5909 // Display the "trail" of reference variables that we followed until we
5910 // found the problematic expression using notes.
5911 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005912 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005913 // If this var binds to another reference var, show the range of the next
5914 // var, otherwise the var binds to the problematic expression, in which case
5915 // show the range of the expression.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005916 SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
5917 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005918 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5919 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005920 }
5921}
5922
5923/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5924/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005925/// to a location on the stack, a local block, an address of a label, or a
5926/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005927/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005928/// encounter a subexpression that (1) clearly does not lead to one of the
5929/// above problematic expressions (2) is something we cannot determine leads to
5930/// a problematic expression based on such local checking.
5931///
5932/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5933/// the expression that they point to. Such variables are added to the
5934/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005935///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005936/// EvalAddr processes expressions that are pointers that are used as
5937/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005938/// At the base case of the recursion is a check for the above problematic
5939/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005940///
5941/// This implementation handles:
5942///
5943/// * pointer-to-pointer casts
5944/// * implicit conversions from array references to pointers
5945/// * taking the address of fields
5946/// * arbitrary interplay between "&" and "*" operators
5947/// * pointer arithmetic from an address of a stack variable
5948/// * taking the address of an array element where the array is on the stack
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005949static const Expr *EvalAddr(const Expr *E,
5950 SmallVectorImpl<const DeclRefExpr *> &refVars,
5951 const Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005952 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005953 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005954
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005955 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005956 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005957 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005958 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005959 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005960
Peter Collingbourne91147592011-04-15 00:35:48 +00005961 E = E->IgnoreParens();
5962
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005963 // Our "symbolic interpreter" is just a dispatch off the currently
5964 // viewed AST node. We then recursively traverse the AST by calling
5965 // EvalAddr and EvalVal appropriately.
5966 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005967 case Stmt::DeclRefExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005968 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005969
Richard Smith40f08eb2014-01-30 22:05:38 +00005970 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005971 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005972 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005973
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005974 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005975 // If this is a reference variable, follow through to the expression that
5976 // it points to.
5977 if (V->hasLocalStorage() &&
5978 V->getType()->isReferenceType() && V->hasInit()) {
5979 // Add the reference variable to the "trail".
5980 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005981 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005982 }
5983
Craig Topperc3ec1492014-05-26 06:22:03 +00005984 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005985 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005986
Chris Lattner934edb22007-12-28 05:31:15 +00005987 case Stmt::UnaryOperatorClass: {
5988 // The only unary operator that make sense to handle here
5989 // is AddrOf. All others don't make sense as pointers.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005990 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005991
John McCalle3027922010-08-25 11:45:40 +00005992 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005993 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00005994 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005995 }
Mike Stump11289f42009-09-09 15:08:12 +00005996
Chris Lattner934edb22007-12-28 05:31:15 +00005997 case Stmt::BinaryOperatorClass: {
5998 // Handle pointer arithmetic. All other binary operators are not valid
5999 // in this context.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006000 const BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00006001 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00006002
John McCalle3027922010-08-25 11:45:40 +00006003 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00006004 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006005
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006006 const Expr *Base = B->getLHS();
Chris Lattner934edb22007-12-28 05:31:15 +00006007
6008 // Determine which argument is the real pointer base. It could be
6009 // the RHS argument instead of the LHS.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006010 if (!Base->getType()->isPointerType())
6011 Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00006012
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006013 assert(Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006014 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006015 }
Steve Naroff2752a172008-09-10 19:17:48 +00006016
Chris Lattner934edb22007-12-28 05:31:15 +00006017 // For conditional operators we need to see if either the LHS or RHS are
6018 // valid DeclRefExpr*s. If one of them is valid, we return it.
6019 case Stmt::ConditionalOperatorClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006020 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006021
Chris Lattner934edb22007-12-28 05:31:15 +00006022 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006023 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006024 if (const Expr *LHSExpr = C->getLHS()) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006025 // In C++, we can have a throw-expression, which has 'void' type.
6026 if (!LHSExpr->getType()->isVoidType())
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006027 if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006028 return LHS;
6029 }
Chris Lattner934edb22007-12-28 05:31:15 +00006030
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006031 // In C++, we can have a throw-expression, which has 'void' type.
6032 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00006033 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00006034
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006035 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00006036 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006037
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006038 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00006039 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006040 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00006041 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006042
6043 case Stmt::AddrLabelExprClass:
6044 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00006045
John McCall28fc7092011-11-10 05:35:25 +00006046 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006047 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6048 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00006049
Ted Kremenekc3b4c522008-08-07 00:49:01 +00006050 // For casts, we need to handle conversions from arrays to
6051 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00006052 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00006053 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006054 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00006055 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00006056 case Stmt::CXXStaticCastExprClass:
6057 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00006058 case Stmt::CXXConstCastExprClass:
6059 case Stmt::CXXReinterpretCastExprClass: {
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006060 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman8195ad72012-02-23 23:04:32 +00006061 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00006062 case CK_LValueToRValue:
6063 case CK_NoOp:
6064 case CK_BaseToDerived:
6065 case CK_DerivedToBase:
6066 case CK_UncheckedDerivedToBase:
6067 case CK_Dynamic:
6068 case CK_CPointerToObjCPointerCast:
6069 case CK_BlockPointerToObjCPointerCast:
6070 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006071 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006072
6073 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006074 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00006075
Richard Trieudadefde2014-07-02 04:39:38 +00006076 case CK_BitCast:
6077 if (SubExpr->getType()->isAnyPointerType() ||
6078 SubExpr->getType()->isBlockPointerType() ||
6079 SubExpr->getType()->isObjCQualifiedIdType())
6080 return EvalAddr(SubExpr, refVars, ParentDecl);
6081 else
6082 return nullptr;
6083
Eli Friedman8195ad72012-02-23 23:04:32 +00006084 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006085 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00006086 }
Chris Lattner934edb22007-12-28 05:31:15 +00006087 }
Mike Stump11289f42009-09-09 15:08:12 +00006088
Douglas Gregorfe314812011-06-21 17:03:29 +00006089 case Stmt::MaterializeTemporaryExprClass:
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006090 if (const Expr *Result =
6091 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6092 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00006093 return Result;
Douglas Gregorfe314812011-06-21 17:03:29 +00006094 return E;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006095
Chris Lattner934edb22007-12-28 05:31:15 +00006096 // Everything else: we simply don't reason about them.
6097 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00006098 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00006099 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006100}
Mike Stump11289f42009-09-09 15:08:12 +00006101
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006102/// EvalVal - This function is complements EvalAddr in the mutual recursion.
6103/// See the comments for EvalAddr for more details.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006104static const Expr *EvalVal(const Expr *E,
6105 SmallVectorImpl<const DeclRefExpr *> &refVars,
6106 const Decl *ParentDecl) {
6107 do {
6108 // We should only be called for evaluating non-pointer expressions, or
6109 // expressions with a pointer type that are not used as references but
6110 // instead
6111 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00006112
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006113 // Our "symbolic interpreter" is just a dispatch off the currently
6114 // viewed AST node. We then recursively traverse the AST by calling
6115 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00006116
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006117 E = E->IgnoreParens();
6118 switch (E->getStmtClass()) {
6119 case Stmt::ImplicitCastExprClass: {
6120 const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6121 if (IE->getValueKind() == VK_LValue) {
6122 E = IE->getSubExpr();
6123 continue;
6124 }
Craig Topperc3ec1492014-05-26 06:22:03 +00006125 return nullptr;
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006126 }
Richard Smith40f08eb2014-01-30 22:05:38 +00006127
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006128 case Stmt::ExprWithCleanupsClass:
6129 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6130 ParentDecl);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006131
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006132 case Stmt::DeclRefExprClass: {
6133 // When we hit a DeclRefExpr we are looking at code that refers to a
6134 // variable's name. If it's not a reference variable we check if it has
6135 // local storage within the function, and if so, return the expression.
6136 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6137
6138 // If we leave the immediate function, the lifetime isn't about to end.
6139 if (DR->refersToEnclosingVariableOrCapture())
6140 return nullptr;
6141
6142 if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6143 // Check if it refers to itself, e.g. "int& i = i;".
6144 if (V == ParentDecl)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006145 return DR;
6146
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006147 if (V->hasLocalStorage()) {
6148 if (!V->getType()->isReferenceType())
6149 return DR;
6150
6151 // Reference variable, follow through to the expression that
6152 // it points to.
6153 if (V->hasInit()) {
6154 // Add the reference variable to the "trail".
6155 refVars.push_back(DR);
6156 return EvalVal(V->getInit(), refVars, V);
6157 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006158 }
6159 }
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006160
6161 return nullptr;
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00006162 }
Mike Stump11289f42009-09-09 15:08:12 +00006163
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006164 case Stmt::UnaryOperatorClass: {
6165 // The only unary operator that make sense to handle here
6166 // is Deref. All others don't resolve to a "name." This includes
6167 // handling all sorts of rvalues passed to a unary operator.
6168 const UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00006169
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006170 if (U->getOpcode() == UO_Deref)
6171 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Mike Stump11289f42009-09-09 15:08:12 +00006172
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006173 return nullptr;
6174 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006175
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006176 case Stmt::ArraySubscriptExprClass: {
6177 // Array subscripts are potential references to data on the stack. We
6178 // retrieve the DeclRefExpr* for the array variable if it indeed
6179 // has local storage.
Saleem Abdulrasoolcfd45532016-02-15 01:51:24 +00006180 const auto *ASE = cast<ArraySubscriptExpr>(E);
6181 if (ASE->isTypeDependent())
6182 return nullptr;
6183 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006184 }
Mike Stump11289f42009-09-09 15:08:12 +00006185
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006186 case Stmt::OMPArraySectionExprClass: {
6187 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6188 ParentDecl);
6189 }
Mike Stump11289f42009-09-09 15:08:12 +00006190
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006191 case Stmt::ConditionalOperatorClass: {
6192 // For conditional operators we need to see if either the LHS or RHS are
6193 // non-NULL Expr's. If one is non-NULL, we return it.
6194 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006195
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006196 // Handle the GNU extension for missing LHS.
6197 if (const Expr *LHSExpr = C->getLHS()) {
6198 // In C++, we can have a throw-expression, which has 'void' type.
6199 if (!LHSExpr->getType()->isVoidType())
6200 if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6201 return LHS;
6202 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006203
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006204 // In C++, we can have a throw-expression, which has 'void' type.
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006205 if (C->getRHS()->getType()->isVoidType())
6206 return nullptr;
6207
6208 return EvalVal(C->getRHS(), refVars, ParentDecl);
Richard Smith6a6a4bb2014-01-27 04:19:56 +00006209 }
6210
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006211 // Accesses to members are potential references to data on the stack.
6212 case Stmt::MemberExprClass: {
6213 const MemberExpr *M = cast<MemberExpr>(E);
Anders Carlsson801c5c72007-11-30 19:04:31 +00006214
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006215 // Check for indirect access. We only want direct field accesses.
6216 if (M->isArrow())
6217 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006218
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006219 // Check whether the member type is itself a reference, in which case
6220 // we're not going to refer to the member, but to what the member refers
6221 // to.
6222 if (M->getMemberDecl()->getType()->isReferenceType())
6223 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00006224
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006225 return EvalVal(M->getBase(), refVars, ParentDecl);
6226 }
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00006227
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006228 case Stmt::MaterializeTemporaryExprClass:
6229 if (const Expr *Result =
6230 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6231 refVars, ParentDecl))
6232 return Result;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00006233 return E;
6234
Saleem Abdulrasool768eb4a2016-02-15 00:36:49 +00006235 default:
6236 // Check that we don't return or take the address of a reference to a
6237 // temporary. This is only useful in C++.
6238 if (!E->isTypeDependent() && E->isRValue())
6239 return E;
6240
6241 // Everything else: we simply don't reason about them.
6242 return nullptr;
6243 }
6244 } while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00006245}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006246
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006247void
6248Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6249 SourceLocation ReturnLoc,
6250 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00006251 const AttrVec *Attrs,
6252 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006253 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6254
6255 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006256 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6257 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006258 CheckNonNullExpr(*this, RetValExp))
6259 Diag(ReturnLoc, diag::warn_null_ret)
6260 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006261
6262 // C++11 [basic.stc.dynamic.allocation]p4:
6263 // If an allocation function declared with a non-throwing
6264 // exception-specification fails to allocate storage, it shall return
6265 // a null pointer. Any other allocation function that fails to allocate
6266 // storage shall indicate failure only by throwing an exception [...]
6267 if (FD) {
6268 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6269 if (Op == OO_New || Op == OO_Array_New) {
6270 const FunctionProtoType *Proto
6271 = FD->getType()->castAs<FunctionProtoType>();
6272 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6273 CheckNonNullExpr(*this, RetValExp))
6274 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6275 << FD << getLangOpts().CPlusPlus11;
6276 }
6277 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006278}
6279
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006280//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6281
6282/// Check for comparisons of floating point operands using != and ==.
6283/// Issue a warning if these are no self-comparisons, as they are not likely
6284/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006285void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006286 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6287 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006288
6289 // Special case: check for x == x (which is OK).
6290 // Do not emit warnings for such cases.
6291 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6292 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6293 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006294 return;
Mike Stump11289f42009-09-09 15:08:12 +00006295
Ted Kremenekeda40e22007-11-29 00:59:04 +00006296 // Special case: check for comparisons against literals that can be exactly
6297 // represented by APFloat. In such cases, do not emit a warning. This
6298 // is a heuristic: often comparison against such literals are used to
6299 // detect if a value in a variable has not changed. This clearly can
6300 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006301 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6302 if (FLL->isExact())
6303 return;
6304 } else
6305 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6306 if (FLR->isExact())
6307 return;
Mike Stump11289f42009-09-09 15:08:12 +00006308
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006309 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006310 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006311 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006312 return;
Mike Stump11289f42009-09-09 15:08:12 +00006313
David Blaikie1f4ff152012-07-16 20:47:22 +00006314 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006315 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006316 return;
Mike Stump11289f42009-09-09 15:08:12 +00006317
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006318 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006319 Diag(Loc, diag::warn_floatingpoint_eq)
6320 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006321}
John McCallca01b222010-01-04 23:21:16 +00006322
John McCall70aa5392010-01-06 05:24:50 +00006323//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6324//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006325
John McCall70aa5392010-01-06 05:24:50 +00006326namespace {
John McCallca01b222010-01-04 23:21:16 +00006327
John McCall70aa5392010-01-06 05:24:50 +00006328/// Structure recording the 'active' range of an integer-valued
6329/// expression.
6330struct IntRange {
6331 /// The number of bits active in the int.
6332 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006333
John McCall70aa5392010-01-06 05:24:50 +00006334 /// True if the int is known not to have negative values.
6335 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006336
John McCall70aa5392010-01-06 05:24:50 +00006337 IntRange(unsigned Width, bool NonNegative)
6338 : Width(Width), NonNegative(NonNegative)
6339 {}
John McCallca01b222010-01-04 23:21:16 +00006340
John McCall817d4af2010-11-10 23:38:19 +00006341 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006342 static IntRange forBoolType() {
6343 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006344 }
6345
John McCall817d4af2010-11-10 23:38:19 +00006346 /// Returns the range of an opaque value of the given integral type.
6347 static IntRange forValueOfType(ASTContext &C, QualType T) {
6348 return forValueOfCanonicalType(C,
6349 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006350 }
6351
John McCall817d4af2010-11-10 23:38:19 +00006352 /// Returns the range of an opaque value of a canonical integral type.
6353 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006354 assert(T->isCanonicalUnqualified());
6355
6356 if (const VectorType *VT = dyn_cast<VectorType>(T))
6357 T = VT->getElementType().getTypePtr();
6358 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6359 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006360 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6361 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006362
David Majnemer6a426652013-06-07 22:07:20 +00006363 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006364 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006365 EnumDecl *Enum = ET->getDecl();
6366 if (!Enum->isCompleteDefinition())
6367 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006368
David Majnemer6a426652013-06-07 22:07:20 +00006369 unsigned NumPositive = Enum->getNumPositiveBits();
6370 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006371
David Majnemer6a426652013-06-07 22:07:20 +00006372 if (NumNegative == 0)
6373 return IntRange(NumPositive, true/*NonNegative*/);
6374 else
6375 return IntRange(std::max(NumPositive + 1, NumNegative),
6376 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006377 }
John McCall70aa5392010-01-06 05:24:50 +00006378
6379 const BuiltinType *BT = cast<BuiltinType>(T);
6380 assert(BT->isInteger());
6381
6382 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6383 }
6384
John McCall817d4af2010-11-10 23:38:19 +00006385 /// Returns the "target" range of a canonical integral type, i.e.
6386 /// the range of values expressible in the type.
6387 ///
6388 /// This matches forValueOfCanonicalType except that enums have the
6389 /// full range of their type, not the range of their enumerators.
6390 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6391 assert(T->isCanonicalUnqualified());
6392
6393 if (const VectorType *VT = dyn_cast<VectorType>(T))
6394 T = VT->getElementType().getTypePtr();
6395 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6396 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006397 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6398 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006399 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006400 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006401
6402 const BuiltinType *BT = cast<BuiltinType>(T);
6403 assert(BT->isInteger());
6404
6405 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6406 }
6407
6408 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006409 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006410 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006411 L.NonNegative && R.NonNegative);
6412 }
6413
John McCall817d4af2010-11-10 23:38:19 +00006414 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006415 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006416 return IntRange(std::min(L.Width, R.Width),
6417 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006418 }
6419};
6420
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006421IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006422 if (value.isSigned() && value.isNegative())
6423 return IntRange(value.getMinSignedBits(), false);
6424
6425 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006426 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006427
6428 // isNonNegative() just checks the sign bit without considering
6429 // signedness.
6430 return IntRange(value.getActiveBits(), true);
6431}
6432
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006433IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6434 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006435 if (result.isInt())
6436 return GetValueRange(C, result.getInt(), MaxWidth);
6437
6438 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006439 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6440 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6441 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6442 R = IntRange::join(R, El);
6443 }
John McCall70aa5392010-01-06 05:24:50 +00006444 return R;
6445 }
6446
6447 if (result.isComplexInt()) {
6448 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6449 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6450 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006451 }
6452
6453 // This can happen with lossless casts to intptr_t of "based" lvalues.
6454 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006455 // FIXME: The only reason we need to pass the type in here is to get
6456 // the sign right on this one case. It would be nice if APValue
6457 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006458 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006459 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006460}
John McCall70aa5392010-01-06 05:24:50 +00006461
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006462QualType GetExprType(const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006463 QualType Ty = E->getType();
6464 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6465 Ty = AtomicRHS->getValueType();
6466 return Ty;
6467}
6468
John McCall70aa5392010-01-06 05:24:50 +00006469/// Pseudo-evaluate the given integer expression, estimating the
6470/// range of values it might take.
6471///
6472/// \param MaxWidth - the width to which the value will be truncated
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006473IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006474 E = E->IgnoreParens();
6475
6476 // Try a full evaluation first.
6477 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006478 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006479 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006480
6481 // I think we only want to look through implicit casts here; if the
6482 // user has an explicit widening cast, we should treat the value as
6483 // being of the new, wider type.
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006484 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006485 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006486 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6487
Eli Friedmane6d33952013-07-08 20:20:06 +00006488 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006489
George Burgess IVdf1ed002016-01-13 01:52:39 +00006490 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6491 CE->getCastKind() == CK_BooleanToSignedIntegral;
John McCall2ce81ad2010-01-06 22:07:33 +00006492
John McCall70aa5392010-01-06 05:24:50 +00006493 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006494 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006495 return OutputTypeRange;
6496
6497 IntRange SubRange
6498 = GetExprRange(C, CE->getSubExpr(),
6499 std::min(MaxWidth, OutputTypeRange.Width));
6500
6501 // Bail out if the subexpr's range is as wide as the cast type.
6502 if (SubRange.Width >= OutputTypeRange.Width)
6503 return OutputTypeRange;
6504
6505 // Otherwise, we take the smaller width, and we're non-negative if
6506 // either the output type or the subexpr is.
6507 return IntRange(SubRange.Width,
6508 SubRange.NonNegative || OutputTypeRange.NonNegative);
6509 }
6510
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006511 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006512 // If we can fold the condition, just take that operand.
6513 bool CondResult;
6514 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6515 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6516 : CO->getFalseExpr(),
6517 MaxWidth);
6518
6519 // Otherwise, conservatively merge.
6520 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6521 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6522 return IntRange::join(L, R);
6523 }
6524
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006525 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006526 switch (BO->getOpcode()) {
6527
6528 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006529 case BO_LAnd:
6530 case BO_LOr:
6531 case BO_LT:
6532 case BO_GT:
6533 case BO_LE:
6534 case BO_GE:
6535 case BO_EQ:
6536 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006537 return IntRange::forBoolType();
6538
John McCallc3688382011-07-13 06:35:24 +00006539 // The type of the assignments is the type of the LHS, so the RHS
6540 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006541 case BO_MulAssign:
6542 case BO_DivAssign:
6543 case BO_RemAssign:
6544 case BO_AddAssign:
6545 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006546 case BO_XorAssign:
6547 case BO_OrAssign:
6548 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006549 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006550
John McCallc3688382011-07-13 06:35:24 +00006551 // Simple assignments just pass through the RHS, which will have
6552 // been coerced to the LHS type.
6553 case BO_Assign:
6554 // TODO: bitfields?
6555 return GetExprRange(C, BO->getRHS(), MaxWidth);
6556
John McCall70aa5392010-01-06 05:24:50 +00006557 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006558 case BO_PtrMemD:
6559 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006560 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006561
John McCall2ce81ad2010-01-06 22:07:33 +00006562 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006563 case BO_And:
6564 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006565 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6566 GetExprRange(C, BO->getRHS(), MaxWidth));
6567
John McCall70aa5392010-01-06 05:24:50 +00006568 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006569 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006570 // ...except that we want to treat '1 << (blah)' as logically
6571 // positive. It's an important idiom.
6572 if (IntegerLiteral *I
6573 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6574 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006575 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006576 return IntRange(R.Width, /*NonNegative*/ true);
6577 }
6578 }
6579 // fallthrough
6580
John McCalle3027922010-08-25 11:45:40 +00006581 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006582 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006583
John McCall2ce81ad2010-01-06 22:07:33 +00006584 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006585 case BO_Shr:
6586 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006587 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6588
6589 // If the shift amount is a positive constant, drop the width by
6590 // that much.
6591 llvm::APSInt shift;
6592 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6593 shift.isNonNegative()) {
6594 unsigned zext = shift.getZExtValue();
6595 if (zext >= L.Width)
6596 L.Width = (L.NonNegative ? 0 : 1);
6597 else
6598 L.Width -= zext;
6599 }
6600
6601 return L;
6602 }
6603
6604 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006605 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006606 return GetExprRange(C, BO->getRHS(), MaxWidth);
6607
John McCall2ce81ad2010-01-06 22:07:33 +00006608 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006609 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006610 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006611 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006612 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006613
John McCall51431812011-07-14 22:39:48 +00006614 // The width of a division result is mostly determined by the size
6615 // of the LHS.
6616 case BO_Div: {
6617 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006618 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006619 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6620
6621 // If the divisor is constant, use that.
6622 llvm::APSInt divisor;
6623 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6624 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6625 if (log2 >= L.Width)
6626 L.Width = (L.NonNegative ? 0 : 1);
6627 else
6628 L.Width = std::min(L.Width - log2, MaxWidth);
6629 return L;
6630 }
6631
6632 // Otherwise, just use the LHS's width.
6633 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6634 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6635 }
6636
6637 // The result of a remainder can't be larger than the result of
6638 // either side.
6639 case BO_Rem: {
6640 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006641 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006642 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6643 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6644
6645 IntRange meet = IntRange::meet(L, R);
6646 meet.Width = std::min(meet.Width, MaxWidth);
6647 return meet;
6648 }
6649
6650 // The default behavior is okay for these.
6651 case BO_Mul:
6652 case BO_Add:
6653 case BO_Xor:
6654 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006655 break;
6656 }
6657
John McCall51431812011-07-14 22:39:48 +00006658 // The default case is to treat the operation as if it were closed
6659 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006660 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6661 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6662 return IntRange::join(L, R);
6663 }
6664
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006665 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
John McCall70aa5392010-01-06 05:24:50 +00006666 switch (UO->getOpcode()) {
6667 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006668 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006669 return IntRange::forBoolType();
6670
6671 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006672 case UO_Deref:
6673 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006674 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006675
6676 default:
6677 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6678 }
6679 }
6680
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006681 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006682 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6683
Daniel Marjamakid3e1ded2016-01-25 09:29:38 +00006684 if (const auto *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006685 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006686 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006687
Eli Friedmane6d33952013-07-08 20:20:06 +00006688 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006689}
John McCall263a48b2010-01-04 23:31:57 +00006690
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006691IntRange GetExprRange(ASTContext &C, const Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006692 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006693}
6694
John McCall263a48b2010-01-04 23:31:57 +00006695/// Checks whether the given value, which currently has the given
6696/// source semantics, has the same value when coerced through the
6697/// target semantics.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006698bool IsSameFloatAfterCast(const llvm::APFloat &value,
6699 const llvm::fltSemantics &Src,
6700 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006701 llvm::APFloat truncated = value;
6702
6703 bool ignored;
6704 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6705 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6706
6707 return truncated.bitwiseIsEqual(value);
6708}
6709
6710/// Checks whether the given value, which currently has the given
6711/// source semantics, has the same value when coerced through the
6712/// target semantics.
6713///
6714/// The value might be a vector of floats (or a complex number).
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006715bool IsSameFloatAfterCast(const APValue &value,
6716 const llvm::fltSemantics &Src,
6717 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006718 if (value.isFloat())
6719 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6720
6721 if (value.isVector()) {
6722 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6723 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6724 return false;
6725 return true;
6726 }
6727
6728 assert(value.isComplexFloat());
6729 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6730 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6731}
6732
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006733void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006734
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006735bool IsZero(Sema &S, Expr *E) {
Ted Kremenek6274be42010-09-23 21:43:44 +00006736 // Suppress cases where we are comparing against an enum constant.
6737 if (const DeclRefExpr *DR =
6738 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6739 if (isa<EnumConstantDecl>(DR->getDecl()))
6740 return false;
6741
6742 // Suppress cases where the '0' value is expanded from a macro.
6743 if (E->getLocStart().isMacroID())
6744 return false;
6745
John McCallcc7e5bf2010-05-06 08:58:33 +00006746 llvm::APSInt Value;
6747 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6748}
6749
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006750bool HasEnumType(Expr *E) {
John McCall2551c1b2010-10-06 00:25:24 +00006751 // Strip off implicit integral promotions.
6752 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006753 if (ICE->getCastKind() != CK_IntegralCast &&
6754 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006755 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006756 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006757 }
6758
6759 return E->getType()->isEnumeralType();
6760}
6761
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006762void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006763 // Disable warning in template instantiations.
6764 if (!S.ActiveTemplateInstantiations.empty())
6765 return;
6766
John McCalle3027922010-08-25 11:45:40 +00006767 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006768 if (E->isValueDependent())
6769 return;
6770
John McCalle3027922010-08-25 11:45:40 +00006771 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006772 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006773 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006774 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006775 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006776 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006777 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006778 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006779 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006780 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006781 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006782 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006783 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006784 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006785 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006786 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6787 }
6788}
6789
Eugene Zelenko1ced5092016-02-12 22:53:10 +00006790void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6791 Expr *Constant, Expr *Other,
6792 llvm::APSInt Value,
6793 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006794 // Disable warning in template instantiations.
6795 if (!S.ActiveTemplateInstantiations.empty())
6796 return;
6797
Richard Trieu0f097742014-04-04 04:13:47 +00006798 // TODO: Investigate using GetExprRange() to get tighter bounds
6799 // on the bit ranges.
6800 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006801 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006802 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006803 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6804 unsigned OtherWidth = OtherRange.Width;
6805
6806 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6807
Richard Trieu560910c2012-11-14 22:50:24 +00006808 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006809 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006810 return;
6811
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006812 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006813 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006814
Richard Trieu0f097742014-04-04 04:13:47 +00006815 // Used for diagnostic printout.
6816 enum {
6817 LiteralConstant = 0,
6818 CXXBoolLiteralTrue,
6819 CXXBoolLiteralFalse
6820 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006821
Richard Trieu0f097742014-04-04 04:13:47 +00006822 if (!OtherIsBooleanType) {
6823 QualType ConstantT = Constant->getType();
6824 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006825
Richard Trieu0f097742014-04-04 04:13:47 +00006826 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6827 return;
6828 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6829 "comparison with non-integer type");
6830
6831 bool ConstantSigned = ConstantT->isSignedIntegerType();
6832 bool CommonSigned = CommonT->isSignedIntegerType();
6833
6834 bool EqualityOnly = false;
6835
6836 if (CommonSigned) {
6837 // The common type is signed, therefore no signed to unsigned conversion.
6838 if (!OtherRange.NonNegative) {
6839 // Check that the constant is representable in type OtherT.
6840 if (ConstantSigned) {
6841 if (OtherWidth >= Value.getMinSignedBits())
6842 return;
6843 } else { // !ConstantSigned
6844 if (OtherWidth >= Value.getActiveBits() + 1)
6845 return;
6846 }
6847 } else { // !OtherSigned
6848 // Check that the constant is representable in type OtherT.
6849 // Negative values are out of range.
6850 if (ConstantSigned) {
6851 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6852 return;
6853 } else { // !ConstantSigned
6854 if (OtherWidth >= Value.getActiveBits())
6855 return;
6856 }
Richard Trieu560910c2012-11-14 22:50:24 +00006857 }
Richard Trieu0f097742014-04-04 04:13:47 +00006858 } else { // !CommonSigned
6859 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006860 if (OtherWidth >= Value.getActiveBits())
6861 return;
Craig Toppercf360162014-06-18 05:13:11 +00006862 } else { // OtherSigned
6863 assert(!ConstantSigned &&
6864 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006865 // Check to see if the constant is representable in OtherT.
6866 if (OtherWidth > Value.getActiveBits())
6867 return;
6868 // Check to see if the constant is equivalent to a negative value
6869 // cast to CommonT.
6870 if (S.Context.getIntWidth(ConstantT) ==
6871 S.Context.getIntWidth(CommonT) &&
6872 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6873 return;
6874 // The constant value rests between values that OtherT can represent
6875 // after conversion. Relational comparison still works, but equality
6876 // comparisons will be tautological.
6877 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006878 }
6879 }
Richard Trieu0f097742014-04-04 04:13:47 +00006880
6881 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6882
6883 if (op == BO_EQ || op == BO_NE) {
6884 IsTrue = op == BO_NE;
6885 } else if (EqualityOnly) {
6886 return;
6887 } else if (RhsConstant) {
6888 if (op == BO_GT || op == BO_GE)
6889 IsTrue = !PositiveConstant;
6890 else // op == BO_LT || op == BO_LE
6891 IsTrue = PositiveConstant;
6892 } else {
6893 if (op == BO_LT || op == BO_LE)
6894 IsTrue = !PositiveConstant;
6895 else // op == BO_GT || op == BO_GE
6896 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006897 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006898 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006899 // Other isKnownToHaveBooleanValue
6900 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6901 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6902 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6903
6904 static const struct LinkedConditions {
6905 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6906 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6907 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6908 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6909 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6910 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6911
6912 } TruthTable = {
6913 // Constant on LHS. | Constant on RHS. |
6914 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6915 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6916 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6917 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6918 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6919 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6920 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6921 };
6922
6923 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6924
6925 enum ConstantValue ConstVal = Zero;
6926 if (Value.isUnsigned() || Value.isNonNegative()) {
6927 if (Value == 0) {
6928 LiteralOrBoolConstant =
6929 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6930 ConstVal = Zero;
6931 } else if (Value == 1) {
6932 LiteralOrBoolConstant =
6933 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6934 ConstVal = One;
6935 } else {
6936 LiteralOrBoolConstant = LiteralConstant;
6937 ConstVal = GT_One;
6938 }
6939 } else {
6940 ConstVal = LT_Zero;
6941 }
6942
6943 CompareBoolWithConstantResult CmpRes;
6944
6945 switch (op) {
6946 case BO_LT:
6947 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6948 break;
6949 case BO_GT:
6950 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6951 break;
6952 case BO_LE:
6953 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6954 break;
6955 case BO_GE:
6956 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6957 break;
6958 case BO_EQ:
6959 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6960 break;
6961 case BO_NE:
6962 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6963 break;
6964 default:
6965 CmpRes = Unkwn;
6966 break;
6967 }
6968
6969 if (CmpRes == AFals) {
6970 IsTrue = false;
6971 } else if (CmpRes == ATrue) {
6972 IsTrue = true;
6973 } else {
6974 return;
6975 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006976 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006977
6978 // If this is a comparison to an enum constant, include that
6979 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006980 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006981 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6982 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6983
6984 SmallString<64> PrettySourceValue;
6985 llvm::raw_svector_ostream OS(PrettySourceValue);
6986 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006987 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006988 else
6989 OS << Value;
6990
Richard Trieu0f097742014-04-04 04:13:47 +00006991 S.DiagRuntimeBehavior(
6992 E->getOperatorLoc(), E,
6993 S.PDiag(diag::warn_out_of_range_compare)
6994 << OS.str() << LiteralOrBoolConstant
6995 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6996 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006997}
6998
John McCallcc7e5bf2010-05-06 08:58:33 +00006999/// Analyze the operands of the given comparison. Implements the
7000/// fallback case from AnalyzeComparison.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007001void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00007002 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7003 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007004}
John McCall263a48b2010-01-04 23:31:57 +00007005
John McCallca01b222010-01-04 23:21:16 +00007006/// \brief Implements -Wsign-compare.
7007///
Richard Trieu82402a02011-09-15 21:56:47 +00007008/// \param E the binary operator to check for warnings
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007009void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007010 // The type the comparison is being performed in.
7011 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00007012
7013 // Only analyze comparison operators where both sides have been converted to
7014 // the same type.
7015 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7016 return AnalyzeImpConvsInComparison(S, E);
7017
7018 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00007019 if (E->isValueDependent())
7020 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007021
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007022 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7023 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007024
7025 bool IsComparisonConstant = false;
7026
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007027 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007028 // of 'true' or 'false'.
7029 if (T->isIntegralType(S.Context)) {
7030 llvm::APSInt RHSValue;
7031 bool IsRHSIntegralLiteral =
7032 RHS->isIntegerConstantExpr(RHSValue, S.Context);
7033 llvm::APSInt LHSValue;
7034 bool IsLHSIntegralLiteral =
7035 LHS->isIntegerConstantExpr(LHSValue, S.Context);
7036 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7037 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7038 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7039 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7040 else
7041 IsComparisonConstant =
7042 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00007043 } else if (!T->hasUnsignedIntegerRepresentation())
7044 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007045
John McCallcc7e5bf2010-05-06 08:58:33 +00007046 // We don't do anything special if this isn't an unsigned integral
7047 // comparison: we're only interested in integral comparisons, and
7048 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00007049 //
7050 // We also don't care about value-dependent expressions or expressions
7051 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007052 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00007053 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00007054
John McCallcc7e5bf2010-05-06 08:58:33 +00007055 // Check to see if one of the (unmodified) operands is of different
7056 // signedness.
7057 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00007058 if (LHS->getType()->hasSignedIntegerRepresentation()) {
7059 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00007060 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00007061 signedOperand = LHS;
7062 unsignedOperand = RHS;
7063 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7064 signedOperand = RHS;
7065 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00007066 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00007067 CheckTrivialUnsignedComparison(S, E);
7068 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007069 }
7070
John McCallcc7e5bf2010-05-06 08:58:33 +00007071 // Otherwise, calculate the effective range of the signed operand.
7072 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00007073
John McCallcc7e5bf2010-05-06 08:58:33 +00007074 // Go ahead and analyze implicit conversions in the operands. Note
7075 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00007076 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7077 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00007078
John McCallcc7e5bf2010-05-06 08:58:33 +00007079 // If the signed range is non-negative, -Wsign-compare won't fire,
7080 // but we should still check for comparisons which are always true
7081 // or false.
7082 if (signedRange.NonNegative)
7083 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00007084
7085 // For (in)equality comparisons, if the unsigned operand is a
7086 // constant which cannot collide with a overflowed signed operand,
7087 // then reinterpreting the signed operand as unsigned will not
7088 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00007089 if (E->isEqualityOp()) {
7090 unsigned comparisonWidth = S.Context.getIntWidth(T);
7091 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00007092
John McCallcc7e5bf2010-05-06 08:58:33 +00007093 // We should never be unable to prove that the unsigned operand is
7094 // non-negative.
7095 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7096
7097 if (unsignedRange.Width < comparisonWidth)
7098 return;
7099 }
7100
Douglas Gregorbfb4a212012-05-01 01:53:49 +00007101 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7102 S.PDiag(diag::warn_mixed_sign_comparison)
7103 << LHS->getType() << RHS->getType()
7104 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00007105}
7106
John McCall1f425642010-11-11 03:21:53 +00007107/// Analyzes an attempt to assign the given value to a bitfield.
7108///
7109/// Returns true if there was something fishy about the attempt.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007110bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7111 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00007112 assert(Bitfield->isBitField());
7113 if (Bitfield->isInvalidDecl())
7114 return false;
7115
John McCalldeebbcf2010-11-11 05:33:51 +00007116 // White-list bool bitfields.
7117 if (Bitfield->getType()->isBooleanType())
7118 return false;
7119
Douglas Gregor789adec2011-02-04 13:09:01 +00007120 // Ignore value- or type-dependent expressions.
7121 if (Bitfield->getBitWidth()->isValueDependent() ||
7122 Bitfield->getBitWidth()->isTypeDependent() ||
7123 Init->isValueDependent() ||
7124 Init->isTypeDependent())
7125 return false;
7126
John McCall1f425642010-11-11 03:21:53 +00007127 Expr *OriginalInit = Init->IgnoreParenImpCasts();
7128
Richard Smith5fab0c92011-12-28 19:48:30 +00007129 llvm::APSInt Value;
7130 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00007131 return false;
7132
John McCall1f425642010-11-11 03:21:53 +00007133 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00007134 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00007135
7136 if (OriginalWidth <= FieldWidth)
7137 return false;
7138
Eli Friedmanc267a322012-01-26 23:11:39 +00007139 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007140 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00007141 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00007142
Eli Friedmanc267a322012-01-26 23:11:39 +00007143 // Check whether the stored value is equal to the original value.
7144 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00007145 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00007146 return false;
7147
Eli Friedmanc267a322012-01-26 23:11:39 +00007148 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00007149 // therefore don't strictly fit into a signed bitfield of width 1.
7150 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00007151 return false;
7152
John McCall1f425642010-11-11 03:21:53 +00007153 std::string PrettyValue = Value.toString(10);
7154 std::string PrettyTrunc = TruncatedValue.toString(10);
7155
7156 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7157 << PrettyValue << PrettyTrunc << OriginalInit->getType()
7158 << Init->getSourceRange();
7159
7160 return true;
7161}
7162
John McCalld2a53122010-11-09 23:24:47 +00007163/// Analyze the given simple or compound assignment for warning-worthy
7164/// operations.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007165void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00007166 // Just recurse on the LHS.
7167 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7168
7169 // We want to recurse on the RHS as normal unless we're assigning to
7170 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00007171 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007172 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00007173 E->getOperatorLoc())) {
7174 // Recurse, ignoring any implicit conversions on the RHS.
7175 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7176 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00007177 }
7178 }
7179
7180 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7181}
7182
John McCall263a48b2010-01-04 23:31:57 +00007183/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007184void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7185 SourceLocation CContext, unsigned diag,
7186 bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007187 if (pruneControlFlow) {
7188 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7189 S.PDiag(diag)
7190 << SourceType << T << E->getSourceRange()
7191 << SourceRange(CContext));
7192 return;
7193 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00007194 S.Diag(E->getExprLoc(), diag)
7195 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7196}
7197
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007198/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007199void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7200 unsigned diag, bool pruneControlFlow = false) {
Anna Zaks314cd092012-02-01 19:08:57 +00007201 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00007202}
7203
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007204/// Diagnose an implicit cast from a literal expression. Does not warn when the
7205/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00007206void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
7207 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007208 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00007209 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007210 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00007211 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7212 T->hasUnsignedIntegerRepresentation());
7213 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00007214 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007215 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00007216 return;
7217
Eli Friedman07185912013-08-29 23:44:43 +00007218 // FIXME: Force the precision of the source value down so we don't print
7219 // digits which are usually useless (we don't really care here if we
7220 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
7221 // would automatically print the shortest representation, but it's a bit
7222 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00007223 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00007224 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7225 precision = (precision * 59 + 195) / 196;
7226 Value.toString(PrettySourceValue, precision);
7227
David Blaikie9b88cc02012-05-15 17:18:27 +00007228 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00007229 if (T->isSpecificBuiltinType(BuiltinType::Bool))
Aaron Ballmandbc441e2015-12-30 14:26:07 +00007230 PrettyTargetValue = Value.isZero() ? "false" : "true";
David Blaikie7555b6a2012-05-15 16:56:36 +00007231 else
David Blaikie9b88cc02012-05-15 17:18:27 +00007232 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00007233
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00007234 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00007235 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
7236 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00007237}
7238
John McCall18a2c2c2010-11-09 22:22:12 +00007239std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7240 if (!Range.Width) return "0";
7241
7242 llvm::APSInt ValueInRange = Value;
7243 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00007244 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00007245 return ValueInRange.toString(10);
7246}
7247
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007248bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007249 if (!isa<ImplicitCastExpr>(Ex))
7250 return false;
7251
7252 Expr *InnerE = Ex->IgnoreParenImpCasts();
7253 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7254 const Type *Source =
7255 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7256 if (Target->isDependentType())
7257 return false;
7258
7259 const BuiltinType *FloatCandidateBT =
7260 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7261 const Type *BoolCandidateType = ToBool ? Target : Source;
7262
7263 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7264 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7265}
7266
7267void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7268 SourceLocation CC) {
7269 unsigned NumArgs = TheCall->getNumArgs();
7270 for (unsigned i = 0; i < NumArgs; ++i) {
7271 Expr *CurrA = TheCall->getArg(i);
7272 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7273 continue;
7274
7275 bool IsSwapped = ((i > 0) &&
7276 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7277 IsSwapped |= ((i < (NumArgs - 1)) &&
7278 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7279 if (IsSwapped) {
7280 // Warn on this floating-point to bool conversion.
7281 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7282 CurrA->getType(), CC,
7283 diag::warn_impcast_floating_point_to_bool);
7284 }
7285 }
7286}
7287
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007288void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
Richard Trieu5b993502014-10-15 03:42:06 +00007289 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7290 E->getExprLoc()))
7291 return;
7292
Richard Trieu09d6b802016-01-08 23:35:06 +00007293 // Don't warn on functions which have return type nullptr_t.
7294 if (isa<CallExpr>(E))
7295 return;
7296
Richard Trieu5b993502014-10-15 03:42:06 +00007297 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7298 const Expr::NullPointerConstantKind NullKind =
7299 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7300 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7301 return;
7302
7303 // Return if target type is a safe conversion.
7304 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7305 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7306 return;
7307
7308 SourceLocation Loc = E->getSourceRange().getBegin();
7309
Richard Trieu0a5e1662016-02-13 00:58:53 +00007310 // Venture through the macro stacks to get to the source of macro arguments.
7311 // The new location is a better location than the complete location that was
7312 // passed in.
7313 while (S.SourceMgr.isMacroArgExpansion(Loc))
7314 Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7315
7316 while (S.SourceMgr.isMacroArgExpansion(CC))
7317 CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7318
Richard Trieu5b993502014-10-15 03:42:06 +00007319 // __null is usually wrapped in a macro. Go up a macro if that is the case.
Richard Trieu0a5e1662016-02-13 00:58:53 +00007320 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7321 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7322 Loc, S.SourceMgr, S.getLangOpts());
7323 if (MacroName == "NULL")
7324 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
Richard Trieu5b993502014-10-15 03:42:06 +00007325 }
7326
7327 // Only warn if the null and context location are in the same macro expansion.
7328 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7329 return;
7330
7331 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7332 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7333 << FixItHint::CreateReplacement(Loc,
7334 S.getFixItZeroLiteralForType(T, Loc));
7335}
7336
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007337void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7338 ObjCArrayLiteral *ArrayLiteral);
7339void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7340 ObjCDictionaryLiteral *DictionaryLiteral);
Douglas Gregor5054cb02015-07-07 03:58:22 +00007341
7342/// Check a single element within a collection literal against the
7343/// target element type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007344void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7345 Expr *Element, unsigned ElementKind) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007346 // Skip a bitcast to 'id' or qualified 'id'.
7347 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7348 if (ICE->getCastKind() == CK_BitCast &&
7349 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7350 Element = ICE->getSubExpr();
7351 }
7352
7353 QualType ElementType = Element->getType();
7354 ExprResult ElementResult(Element);
7355 if (ElementType->getAs<ObjCObjectPointerType>() &&
7356 S.CheckSingleAssignmentConstraints(TargetElementType,
7357 ElementResult,
7358 false, false)
7359 != Sema::Compatible) {
7360 S.Diag(Element->getLocStart(),
7361 diag::warn_objc_collection_literal_element)
7362 << ElementType << ElementKind << TargetElementType
7363 << Element->getSourceRange();
7364 }
7365
7366 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7367 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7368 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7369 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7370}
7371
7372/// Check an Objective-C array literal being converted to the given
7373/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007374void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7375 ObjCArrayLiteral *ArrayLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007376 if (!S.NSArrayDecl)
7377 return;
7378
7379 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7380 if (!TargetObjCPtr)
7381 return;
7382
7383 if (TargetObjCPtr->isUnspecialized() ||
7384 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7385 != S.NSArrayDecl->getCanonicalDecl())
7386 return;
7387
7388 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7389 if (TypeArgs.size() != 1)
7390 return;
7391
7392 QualType TargetElementType = TypeArgs[0];
7393 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7394 checkObjCCollectionLiteralElement(S, TargetElementType,
7395 ArrayLiteral->getElement(I),
7396 0);
7397 }
7398}
7399
7400/// Check an Objective-C dictionary literal being converted to the given
7401/// target type.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007402void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7403 ObjCDictionaryLiteral *DictionaryLiteral) {
Douglas Gregor5054cb02015-07-07 03:58:22 +00007404 if (!S.NSDictionaryDecl)
7405 return;
7406
7407 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7408 if (!TargetObjCPtr)
7409 return;
7410
7411 if (TargetObjCPtr->isUnspecialized() ||
7412 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7413 != S.NSDictionaryDecl->getCanonicalDecl())
7414 return;
7415
7416 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7417 if (TypeArgs.size() != 2)
7418 return;
7419
7420 QualType TargetKeyType = TypeArgs[0];
7421 QualType TargetObjectType = TypeArgs[1];
7422 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7423 auto Element = DictionaryLiteral->getKeyValueElement(I);
7424 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7425 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7426 }
7427}
7428
Richard Trieufc404c72016-02-05 23:02:38 +00007429// Helper function to filter out cases for constant width constant conversion.
7430// Don't warn on char array initialization or for non-decimal values.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007431bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7432 SourceLocation CC) {
Richard Trieufc404c72016-02-05 23:02:38 +00007433 // If initializing from a constant, and the constant starts with '0',
7434 // then it is a binary, octal, or hexadecimal. Allow these constants
7435 // to fill all the bits, even if there is a sign change.
7436 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7437 const char FirstLiteralCharacter =
7438 S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7439 if (FirstLiteralCharacter == '0')
7440 return false;
7441 }
7442
7443 // If the CC location points to a '{', and the type is char, then assume
7444 // assume it is an array initialization.
7445 if (CC.isValid() && T->isCharType()) {
7446 const char FirstContextCharacter =
7447 S.getSourceManager().getCharacterData(CC)[0];
7448 if (FirstContextCharacter == '{')
7449 return false;
7450 }
7451
7452 return true;
7453}
7454
John McCallcc7e5bf2010-05-06 08:58:33 +00007455void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007456 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007457 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007458
John McCallcc7e5bf2010-05-06 08:58:33 +00007459 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7460 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7461 if (Source == Target) return;
7462 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007463
Chandler Carruthc22845a2011-07-26 05:40:03 +00007464 // If the conversion context location is invalid don't complain. We also
7465 // don't want to emit a warning if the issue occurs from the expansion of
7466 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7467 // delay this check as long as possible. Once we detect we are in that
7468 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007469 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007470 return;
7471
Richard Trieu021baa32011-09-23 20:10:00 +00007472 // Diagnose implicit casts to bool.
7473 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7474 if (isa<StringLiteral>(E))
7475 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007476 // and expressions, for instance, assert(0 && "error here"), are
7477 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007478 return DiagnoseImpCast(S, E, T, CC,
7479 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007480 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7481 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7482 // This covers the literal expressions that evaluate to Objective-C
7483 // objects.
7484 return DiagnoseImpCast(S, E, T, CC,
7485 diag::warn_impcast_objective_c_literal_to_bool);
7486 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007487 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7488 // Warn on pointer to bool conversion that is always true.
7489 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7490 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007491 }
Richard Trieu021baa32011-09-23 20:10:00 +00007492 }
John McCall263a48b2010-01-04 23:31:57 +00007493
Douglas Gregor5054cb02015-07-07 03:58:22 +00007494 // Check implicit casts from Objective-C collection literals to specialized
7495 // collection types, e.g., NSArray<NSString *> *.
7496 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7497 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7498 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7499 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7500
John McCall263a48b2010-01-04 23:31:57 +00007501 // Strip vector types.
7502 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007503 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007504 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007505 return;
John McCallacf0ee52010-10-08 02:01:28 +00007506 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007507 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007508
7509 // If the vector cast is cast between two vectors of the same size, it is
7510 // a bitcast, not a conversion.
7511 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7512 return;
John McCall263a48b2010-01-04 23:31:57 +00007513
7514 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7515 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7516 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007517 if (auto VecTy = dyn_cast<VectorType>(Target))
7518 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007519
7520 // Strip complex types.
7521 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007522 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007523 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007524 return;
7525
John McCallacf0ee52010-10-08 02:01:28 +00007526 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007527 }
John McCall263a48b2010-01-04 23:31:57 +00007528
7529 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7530 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7531 }
7532
7533 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7534 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7535
7536 // If the source is floating point...
7537 if (SourceBT && SourceBT->isFloatingPoint()) {
7538 // ...and the target is floating point...
7539 if (TargetBT && TargetBT->isFloatingPoint()) {
7540 // ...then warn if we're dropping FP rank.
7541
7542 // Builtin FP kinds are ordered by increasing FP rank.
7543 if (SourceBT->getKind() > TargetBT->getKind()) {
7544 // Don't warn about float constants that are precisely
7545 // representable in the target type.
7546 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007547 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007548 // Value might be a float, a float vector, or a float complex.
7549 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007550 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7551 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007552 return;
7553 }
7554
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007555 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007556 return;
7557
John McCallacf0ee52010-10-08 02:01:28 +00007558 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007559 }
7560 // ... or possibly if we're increasing rank, too
7561 else if (TargetBT->getKind() > SourceBT->getKind()) {
7562 if (S.SourceMgr.isInSystemMacro(CC))
7563 return;
7564
7565 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007566 }
7567 return;
7568 }
7569
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007570 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007571 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007572 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007573 return;
7574
Chandler Carruth22c7a792011-02-17 11:05:49 +00007575 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007576 // We also want to warn on, e.g., "int i = -1.234"
7577 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7578 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7579 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7580
Chandler Carruth016ef402011-04-10 08:36:24 +00007581 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7582 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007583 } else {
7584 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7585 }
7586 }
John McCall263a48b2010-01-04 23:31:57 +00007587
Richard Smith54894fd2015-12-30 01:06:52 +00007588 // Detect the case where a call result is converted from floating-point to
7589 // to bool, and the final argument to the call is converted from bool, to
7590 // discover this typo:
7591 //
7592 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
7593 //
7594 // FIXME: This is an incredibly special case; is there some more general
7595 // way to detect this class of misplaced-parentheses bug?
7596 if (Target->isBooleanType() && isa<CallExpr>(E)) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007597 // Check last argument of function call to see if it is an
7598 // implicit cast from a type matching the type the result
7599 // is being cast to.
7600 CallExpr *CEx = cast<CallExpr>(E);
Richard Smith54894fd2015-12-30 01:06:52 +00007601 if (unsigned NumArgs = CEx->getNumArgs()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007602 Expr *LastA = CEx->getArg(NumArgs - 1);
7603 Expr *InnerE = LastA->IgnoreParenImpCasts();
Richard Smith54894fd2015-12-30 01:06:52 +00007604 if (isa<ImplicitCastExpr>(LastA) &&
7605 InnerE->getType()->isBooleanType()) {
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007606 // Warn on this floating-point to bool conversion
7607 DiagnoseImpCast(S, E, T, CC,
7608 diag::warn_impcast_floating_point_to_bool);
7609 }
7610 }
7611 }
John McCall263a48b2010-01-04 23:31:57 +00007612 return;
7613 }
7614
Richard Trieu5b993502014-10-15 03:42:06 +00007615 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007616
David Blaikie9366d2b2012-06-19 21:19:06 +00007617 if (!Source->isIntegerType() || !Target->isIntegerType())
7618 return;
7619
David Blaikie7555b6a2012-05-15 16:56:36 +00007620 // TODO: remove this early return once the false positives for constant->bool
7621 // in templates, macros, etc, are reduced or removed.
7622 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7623 return;
7624
John McCallcc7e5bf2010-05-06 08:58:33 +00007625 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007626 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007627
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007628 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007629 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007630 // TODO: this should happen for bitfield stores, too.
7631 llvm::APSInt Value(32);
Richard Trieudcb55572016-01-29 23:51:16 +00007632 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007633 if (S.SourceMgr.isInSystemMacro(CC))
7634 return;
7635
John McCall18a2c2c2010-11-09 22:22:12 +00007636 std::string PrettySourceValue = Value.toString(10);
7637 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007638
Ted Kremenek33ba9952011-10-22 02:37:33 +00007639 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7640 S.PDiag(diag::warn_impcast_integer_precision_constant)
7641 << PrettySourceValue << PrettyTargetValue
7642 << E->getType() << T << E->getSourceRange()
7643 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007644 return;
7645 }
7646
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007647 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7648 if (S.SourceMgr.isInSystemMacro(CC))
7649 return;
7650
David Blaikie9455da02012-04-12 22:40:54 +00007651 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007652 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7653 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007654 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007655 }
7656
Richard Trieudcb55572016-01-29 23:51:16 +00007657 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7658 SourceRange.NonNegative && Source->isSignedIntegerType()) {
7659 // Warn when doing a signed to signed conversion, warn if the positive
7660 // source value is exactly the width of the target type, which will
7661 // cause a negative value to be stored.
7662
7663 llvm::APSInt Value;
Richard Trieufc404c72016-02-05 23:02:38 +00007664 if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7665 !S.SourceMgr.isInSystemMacro(CC)) {
7666 if (isSameWidthConstantConversion(S, E, T, CC)) {
7667 std::string PrettySourceValue = Value.toString(10);
7668 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Richard Trieudcb55572016-01-29 23:51:16 +00007669
Richard Trieufc404c72016-02-05 23:02:38 +00007670 S.DiagRuntimeBehavior(
7671 E->getExprLoc(), E,
7672 S.PDiag(diag::warn_impcast_integer_precision_constant)
7673 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7674 << E->getSourceRange() << clang::SourceRange(CC));
7675 return;
Richard Trieudcb55572016-01-29 23:51:16 +00007676 }
7677 }
Richard Trieufc404c72016-02-05 23:02:38 +00007678
Richard Trieudcb55572016-01-29 23:51:16 +00007679 // Fall through for non-constants to give a sign conversion warning.
7680 }
7681
John McCallcc7e5bf2010-05-06 08:58:33 +00007682 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7683 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7684 SourceRange.Width == TargetRange.Width)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007685 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007686 return;
7687
John McCallcc7e5bf2010-05-06 08:58:33 +00007688 unsigned DiagID = diag::warn_impcast_integer_sign;
7689
7690 // Traditionally, gcc has warned about this under -Wsign-compare.
7691 // We also want to warn about it in -Wconversion.
7692 // So if -Wconversion is off, use a completely identical diagnostic
7693 // in the sign-compare group.
7694 // The conditional-checking code will
7695 if (ICContext) {
7696 DiagID = diag::warn_impcast_integer_sign_conditional;
7697 *ICContext = true;
7698 }
7699
John McCallacf0ee52010-10-08 02:01:28 +00007700 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007701 }
7702
Douglas Gregora78f1932011-02-22 02:45:07 +00007703 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007704 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7705 // type, to give us better diagnostics.
7706 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007707 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007708 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7709 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7710 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7711 SourceType = S.Context.getTypeDeclType(Enum);
7712 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7713 }
7714 }
7715
Douglas Gregora78f1932011-02-22 02:45:07 +00007716 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7717 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007718 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7719 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007720 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007721 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007722 return;
7723
Douglas Gregor364f7db2011-03-12 00:14:31 +00007724 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007725 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007726 }
John McCall263a48b2010-01-04 23:31:57 +00007727}
7728
David Blaikie18e9ac72012-05-15 21:57:38 +00007729void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7730 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007731
7732void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007733 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007734 E = E->IgnoreParenImpCasts();
7735
7736 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007737 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007738
John McCallacf0ee52010-10-08 02:01:28 +00007739 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007740 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007741 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007742}
7743
David Blaikie18e9ac72012-05-15 21:57:38 +00007744void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7745 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007746 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007747
7748 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007749 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7750 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007751
7752 // If -Wconversion would have warned about either of the candidates
7753 // for a signedness conversion to the context type...
7754 if (!Suspicious) return;
7755
7756 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007757 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007758 return;
7759
John McCallcc7e5bf2010-05-06 08:58:33 +00007760 // ...then check whether it would have warned about either of the
7761 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007762 if (E->getType() == T) return;
7763
7764 Suspicious = false;
7765 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7766 E->getType(), CC, &Suspicious);
7767 if (!Suspicious)
7768 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007769 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007770}
7771
Richard Trieu65724892014-11-15 06:37:39 +00007772/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7773/// Input argument E is a logical expression.
Eugene Zelenko1ced5092016-02-12 22:53:10 +00007774void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
Richard Trieu65724892014-11-15 06:37:39 +00007775 if (S.getLangOpts().Bool)
7776 return;
7777 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7778}
7779
John McCallcc7e5bf2010-05-06 08:58:33 +00007780/// AnalyzeImplicitConversions - Find and report any interesting
7781/// implicit conversions in the given expression. There are a couple
7782/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007783void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007784 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007785 Expr *E = OrigE->IgnoreParenImpCasts();
7786
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007787 if (E->isTypeDependent() || E->isValueDependent())
7788 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007789
John McCallcc7e5bf2010-05-06 08:58:33 +00007790 // For conditional operators, we analyze the arguments as if they
7791 // were being fed directly into the output.
7792 if (isa<ConditionalOperator>(E)) {
7793 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007794 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007795 return;
7796 }
7797
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007798 // Check implicit argument conversions for function calls.
7799 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7800 CheckImplicitArgumentConversions(S, Call, CC);
7801
John McCallcc7e5bf2010-05-06 08:58:33 +00007802 // Go ahead and check any implicit conversions we might have skipped.
7803 // The non-canonical typecheck is just an optimization;
7804 // CheckImplicitConversion will filter out dead implicit conversions.
7805 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007806 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007807
7808 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007809
7810 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7811 // The bound subexpressions in a PseudoObjectExpr are not reachable
7812 // as transitive children.
7813 // FIXME: Use a more uniform representation for this.
7814 for (auto *SE : POE->semantics())
7815 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7816 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007817 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007818
John McCallcc7e5bf2010-05-06 08:58:33 +00007819 // Skip past explicit casts.
7820 if (isa<ExplicitCastExpr>(E)) {
7821 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007822 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007823 }
7824
John McCalld2a53122010-11-09 23:24:47 +00007825 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7826 // Do a somewhat different check with comparison operators.
7827 if (BO->isComparisonOp())
7828 return AnalyzeComparison(S, BO);
7829
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007830 // And with simple assignments.
7831 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007832 return AnalyzeAssignment(S, BO);
7833 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007834
7835 // These break the otherwise-useful invariant below. Fortunately,
7836 // we don't really need to recurse into them, because any internal
7837 // expressions should have been analyzed already when they were
7838 // built into statements.
7839 if (isa<StmtExpr>(E)) return;
7840
7841 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007842 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007843
7844 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007845 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007846 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007847 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007848 for (Stmt *SubStmt : E->children()) {
7849 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007850 if (!ChildExpr)
7851 continue;
7852
Richard Trieu955231d2014-01-25 01:10:35 +00007853 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007854 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007855 // Ignore checking string literals that are in logical and operators.
7856 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007857 continue;
7858 AnalyzeImplicitConversions(S, ChildExpr, CC);
7859 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007860
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007861 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007862 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7863 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007864 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007865
7866 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7867 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007868 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007869 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007870
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007871 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7872 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007873 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007874}
7875
7876} // end anonymous namespace
7877
Richard Trieuc1888e02014-06-28 23:25:37 +00007878// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7879// Returns true when emitting a warning about taking the address of a reference.
7880static bool CheckForReference(Sema &SemaRef, const Expr *E,
7881 PartialDiagnostic PD) {
7882 E = E->IgnoreParenImpCasts();
7883
7884 const FunctionDecl *FD = nullptr;
7885
7886 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7887 if (!DRE->getDecl()->getType()->isReferenceType())
7888 return false;
7889 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7890 if (!M->getMemberDecl()->getType()->isReferenceType())
7891 return false;
7892 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007893 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007894 return false;
7895 FD = Call->getDirectCallee();
7896 } else {
7897 return false;
7898 }
7899
7900 SemaRef.Diag(E->getExprLoc(), PD);
7901
7902 // If possible, point to location of function.
7903 if (FD) {
7904 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7905 }
7906
7907 return true;
7908}
7909
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007910// Returns true if the SourceLocation is expanded from any macro body.
7911// Returns false if the SourceLocation is invalid, is from not in a macro
7912// expansion, or is from expanded from a top-level macro argument.
7913static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7914 if (Loc.isInvalid())
7915 return false;
7916
7917 while (Loc.isMacroID()) {
7918 if (SM.isMacroBodyExpansion(Loc))
7919 return true;
7920 Loc = SM.getImmediateMacroCallerLoc(Loc);
7921 }
7922
7923 return false;
7924}
7925
Richard Trieu3bb8b562014-02-26 02:36:06 +00007926/// \brief Diagnose pointers that are always non-null.
7927/// \param E the expression containing the pointer
7928/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7929/// compared to a null pointer
7930/// \param IsEqual True when the comparison is equal to a null pointer
7931/// \param Range Extra SourceRange to highlight in the diagnostic
7932void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7933 Expr::NullPointerConstantKind NullKind,
7934 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007935 if (!E)
7936 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007937
7938 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007939 if (E->getExprLoc().isMacroID()) {
7940 const SourceManager &SM = getSourceManager();
7941 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7942 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007943 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007944 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007945 E = E->IgnoreImpCasts();
7946
7947 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7948
Richard Trieuf7432752014-06-06 21:39:26 +00007949 if (isa<CXXThisExpr>(E)) {
7950 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7951 : diag::warn_this_bool_conversion;
7952 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7953 return;
7954 }
7955
Richard Trieu3bb8b562014-02-26 02:36:06 +00007956 bool IsAddressOf = false;
7957
7958 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7959 if (UO->getOpcode() != UO_AddrOf)
7960 return;
7961 IsAddressOf = true;
7962 E = UO->getSubExpr();
7963 }
7964
Richard Trieuc1888e02014-06-28 23:25:37 +00007965 if (IsAddressOf) {
7966 unsigned DiagID = IsCompare
7967 ? diag::warn_address_of_reference_null_compare
7968 : diag::warn_address_of_reference_bool_conversion;
7969 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7970 << IsEqual;
7971 if (CheckForReference(*this, E, PD)) {
7972 return;
7973 }
7974 }
7975
George Burgess IV850269a2015-12-08 22:02:00 +00007976 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
7977 std::string Str;
7978 llvm::raw_string_ostream S(Str);
7979 E->printPretty(S, nullptr, getPrintingPolicy());
7980 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
7981 : diag::warn_cast_nonnull_to_bool;
7982 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
7983 << E->getSourceRange() << Range << IsEqual;
7984 };
7985
7986 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
7987 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
7988 if (auto *Callee = Call->getDirectCallee()) {
7989 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
7990 ComplainAboutNonnullParamOrCall(false);
7991 return;
7992 }
7993 }
7994 }
7995
Richard Trieu3bb8b562014-02-26 02:36:06 +00007996 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007997 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007998 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7999 D = R->getDecl();
8000 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8001 D = M->getMemberDecl();
8002 }
8003
8004 // Weak Decls can be null.
8005 if (!D || D->isWeak())
8006 return;
George Burgess IV850269a2015-12-08 22:02:00 +00008007
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008008 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00008009 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8010 if (getCurFunction() &&
8011 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8012 if (PV->hasAttr<NonNullAttr>()) {
8013 ComplainAboutNonnullParamOrCall(true);
8014 return;
8015 }
8016
8017 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8018 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8019 assert(ParamIter != FD->param_end());
8020 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8021
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008022 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8023 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00008024 ComplainAboutNonnullParamOrCall(true);
8025 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008026 }
George Burgess IV850269a2015-12-08 22:02:00 +00008027
8028 for (unsigned ArgNo : NonNull->args()) {
8029 if (ArgNo == ParamNo) {
8030 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008031 return;
8032 }
George Burgess IV850269a2015-12-08 22:02:00 +00008033 }
8034 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00008035 }
8036 }
George Burgess IV850269a2015-12-08 22:02:00 +00008037 }
8038
Richard Trieu3bb8b562014-02-26 02:36:06 +00008039 QualType T = D->getType();
8040 const bool IsArray = T->isArrayType();
8041 const bool IsFunction = T->isFunctionType();
8042
Richard Trieuc1888e02014-06-28 23:25:37 +00008043 // Address of function is used to silence the function warning.
8044 if (IsAddressOf && IsFunction) {
8045 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008046 }
8047
8048 // Found nothing.
8049 if (!IsAddressOf && !IsFunction && !IsArray)
8050 return;
8051
8052 // Pretty print the expression for the diagnostic.
8053 std::string Str;
8054 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00008055 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00008056
8057 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8058 : diag::warn_impcast_pointer_to_bool;
Craig Topperfa1340f2015-12-23 05:44:46 +00008059 enum {
8060 AddressOf,
8061 FunctionPointer,
8062 ArrayPointer
8063 } DiagType;
Richard Trieu3bb8b562014-02-26 02:36:06 +00008064 if (IsAddressOf)
8065 DiagType = AddressOf;
8066 else if (IsFunction)
8067 DiagType = FunctionPointer;
8068 else if (IsArray)
8069 DiagType = ArrayPointer;
8070 else
8071 llvm_unreachable("Could not determine diagnostic.");
8072 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8073 << Range << IsEqual;
8074
8075 if (!IsFunction)
8076 return;
8077
8078 // Suggest '&' to silence the function warning.
8079 Diag(E->getExprLoc(), diag::note_function_warning_silence)
8080 << FixItHint::CreateInsertion(E->getLocStart(), "&");
8081
8082 // Check to see if '()' fixit should be emitted.
8083 QualType ReturnType;
8084 UnresolvedSet<4> NonTemplateOverloads;
8085 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8086 if (ReturnType.isNull())
8087 return;
8088
8089 if (IsCompare) {
8090 // There are two cases here. If there is null constant, the only suggest
8091 // for a pointer return type. If the null is 0, then suggest if the return
8092 // type is a pointer or an integer type.
8093 if (!ReturnType->isPointerType()) {
8094 if (NullKind == Expr::NPCK_ZeroExpression ||
8095 NullKind == Expr::NPCK_ZeroLiteral) {
8096 if (!ReturnType->isIntegerType())
8097 return;
8098 } else {
8099 return;
8100 }
8101 }
8102 } else { // !IsCompare
8103 // For function to bool, only suggest if the function pointer has bool
8104 // return type.
8105 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8106 return;
8107 }
8108 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00008109 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00008110}
8111
John McCallcc7e5bf2010-05-06 08:58:33 +00008112/// Diagnoses "dangerous" implicit conversions within the given
8113/// expression (which is a full expression). Implements -Wconversion
8114/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00008115///
8116/// \param CC the "context" location of the implicit conversion, i.e.
8117/// the most location of the syntactic entity requiring the implicit
8118/// conversion
8119void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00008120 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00008121 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00008122 return;
8123
8124 // Don't diagnose for value- or type-dependent expressions.
8125 if (E->isTypeDependent() || E->isValueDependent())
8126 return;
8127
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008128 // Check for array bounds violations in cases where the check isn't triggered
8129 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8130 // ArraySubscriptExpr is on the RHS of a variable initialization.
8131 CheckArrayAccess(E);
8132
John McCallacf0ee52010-10-08 02:01:28 +00008133 // This is not the right CC for (e.g.) a variable initialization.
8134 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00008135}
8136
Richard Trieu65724892014-11-15 06:37:39 +00008137/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8138/// Input argument E is a logical expression.
8139void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8140 ::CheckBoolLikeConversion(*this, E, CC);
8141}
8142
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008143/// Diagnose when expression is an integer constant expression and its evaluation
8144/// results in integer overflow
8145void Sema::CheckForIntOverflow (Expr *E) {
Akira Hatanakadfe2156f2016-02-10 06:06:06 +00008146 // Use a work list to deal with nested struct initializers.
8147 SmallVector<Expr *, 2> Exprs(1, E);
8148
8149 do {
8150 Expr *E = Exprs.pop_back_val();
8151
8152 if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8153 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8154 continue;
8155 }
8156
8157 if (auto InitList = dyn_cast<InitListExpr>(E))
8158 Exprs.append(InitList->inits().begin(), InitList->inits().end());
8159 } while (!Exprs.empty());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008160}
8161
Richard Smithc406cb72013-01-17 01:17:56 +00008162namespace {
8163/// \brief Visitor for expressions which looks for unsequenced operations on the
8164/// same object.
8165class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008166 typedef EvaluatedExprVisitor<SequenceChecker> Base;
8167
Richard Smithc406cb72013-01-17 01:17:56 +00008168 /// \brief A tree of sequenced regions within an expression. Two regions are
8169 /// unsequenced if one is an ancestor or a descendent of the other. When we
8170 /// finish processing an expression with sequencing, such as a comma
8171 /// expression, we fold its tree nodes into its parent, since they are
8172 /// unsequenced with respect to nodes we will visit later.
8173 class SequenceTree {
8174 struct Value {
8175 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8176 unsigned Parent : 31;
8177 bool Merged : 1;
8178 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008179 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00008180
8181 public:
8182 /// \brief A region within an expression which may be sequenced with respect
8183 /// to some other region.
8184 class Seq {
8185 explicit Seq(unsigned N) : Index(N) {}
8186 unsigned Index;
8187 friend class SequenceTree;
8188 public:
8189 Seq() : Index(0) {}
8190 };
8191
8192 SequenceTree() { Values.push_back(Value(0)); }
8193 Seq root() const { return Seq(0); }
8194
8195 /// \brief Create a new sequence of operations, which is an unsequenced
8196 /// subset of \p Parent. This sequence of operations is sequenced with
8197 /// respect to other children of \p Parent.
8198 Seq allocate(Seq Parent) {
8199 Values.push_back(Value(Parent.Index));
8200 return Seq(Values.size() - 1);
8201 }
8202
8203 /// \brief Merge a sequence of operations into its parent.
8204 void merge(Seq S) {
8205 Values[S.Index].Merged = true;
8206 }
8207
8208 /// \brief Determine whether two operations are unsequenced. This operation
8209 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8210 /// should have been merged into its parent as appropriate.
8211 bool isUnsequenced(Seq Cur, Seq Old) {
8212 unsigned C = representative(Cur.Index);
8213 unsigned Target = representative(Old.Index);
8214 while (C >= Target) {
8215 if (C == Target)
8216 return true;
8217 C = Values[C].Parent;
8218 }
8219 return false;
8220 }
8221
8222 private:
8223 /// \brief Pick a representative for a sequence.
8224 unsigned representative(unsigned K) {
8225 if (Values[K].Merged)
8226 // Perform path compression as we go.
8227 return Values[K].Parent = representative(Values[K].Parent);
8228 return K;
8229 }
8230 };
8231
8232 /// An object for which we can track unsequenced uses.
8233 typedef NamedDecl *Object;
8234
8235 /// Different flavors of object usage which we track. We only track the
8236 /// least-sequenced usage of each kind.
8237 enum UsageKind {
8238 /// A read of an object. Multiple unsequenced reads are OK.
8239 UK_Use,
8240 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00008241 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00008242 UK_ModAsValue,
8243 /// A modification of an object which is not sequenced before the value
8244 /// computation of the expression, such as n++.
8245 UK_ModAsSideEffect,
8246
8247 UK_Count = UK_ModAsSideEffect + 1
8248 };
8249
8250 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00008251 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00008252 Expr *Use;
8253 SequenceTree::Seq Seq;
8254 };
8255
8256 struct UsageInfo {
8257 UsageInfo() : Diagnosed(false) {}
8258 Usage Uses[UK_Count];
8259 /// Have we issued a diagnostic for this variable already?
8260 bool Diagnosed;
8261 };
8262 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8263
8264 Sema &SemaRef;
8265 /// Sequenced regions within the expression.
8266 SequenceTree Tree;
8267 /// Declaration modifications and references which we have seen.
8268 UsageInfoMap UsageMap;
8269 /// The region we are currently within.
8270 SequenceTree::Seq Region;
8271 /// Filled in with declarations which were modified as a side-effect
8272 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008273 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00008274 /// Expressions to check later. We defer checking these to reduce
8275 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008276 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00008277
8278 /// RAII object wrapping the visitation of a sequenced subexpression of an
8279 /// expression. At the end of this process, the side-effects of the evaluation
8280 /// become sequenced with respect to the value computation of the result, so
8281 /// we downgrade any UK_ModAsSideEffect within the evaluation to
8282 /// UK_ModAsValue.
8283 struct SequencedSubexpression {
8284 SequencedSubexpression(SequenceChecker &Self)
8285 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8286 Self.ModAsSideEffect = &ModAsSideEffect;
8287 }
8288 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00008289 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8290 MI != ME; ++MI) {
8291 UsageInfo &U = Self.UsageMap[MI->first];
8292 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8293 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8294 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00008295 }
8296 Self.ModAsSideEffect = OldModAsSideEffect;
8297 }
8298
8299 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008300 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8301 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00008302 };
8303
Richard Smith40238f02013-06-20 22:21:56 +00008304 /// RAII object wrapping the visitation of a subexpression which we might
8305 /// choose to evaluate as a constant. If any subexpression is evaluated and
8306 /// found to be non-constant, this allows us to suppress the evaluation of
8307 /// the outer expression.
8308 class EvaluationTracker {
8309 public:
8310 EvaluationTracker(SequenceChecker &Self)
8311 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8312 Self.EvalTracker = this;
8313 }
8314 ~EvaluationTracker() {
8315 Self.EvalTracker = Prev;
8316 if (Prev)
8317 Prev->EvalOK &= EvalOK;
8318 }
8319
8320 bool evaluate(const Expr *E, bool &Result) {
8321 if (!EvalOK || E->isValueDependent())
8322 return false;
8323 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8324 return EvalOK;
8325 }
8326
8327 private:
8328 SequenceChecker &Self;
8329 EvaluationTracker *Prev;
8330 bool EvalOK;
8331 } *EvalTracker;
8332
Richard Smithc406cb72013-01-17 01:17:56 +00008333 /// \brief Find the object which is produced by the specified expression,
8334 /// if any.
8335 Object getObject(Expr *E, bool Mod) const {
8336 E = E->IgnoreParenCasts();
8337 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8338 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8339 return getObject(UO->getSubExpr(), Mod);
8340 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8341 if (BO->getOpcode() == BO_Comma)
8342 return getObject(BO->getRHS(), Mod);
8343 if (Mod && BO->isAssignmentOp())
8344 return getObject(BO->getLHS(), Mod);
8345 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8346 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8347 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8348 return ME->getMemberDecl();
8349 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8350 // FIXME: If this is a reference, map through to its value.
8351 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008352 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008353 }
8354
8355 /// \brief Note that an object was modified or used by an expression.
8356 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8357 Usage &U = UI.Uses[UK];
8358 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8359 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8360 ModAsSideEffect->push_back(std::make_pair(O, U));
8361 U.Use = Ref;
8362 U.Seq = Region;
8363 }
8364 }
8365 /// \brief Check whether a modification or use conflicts with a prior usage.
8366 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8367 bool IsModMod) {
8368 if (UI.Diagnosed)
8369 return;
8370
8371 const Usage &U = UI.Uses[OtherKind];
8372 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8373 return;
8374
8375 Expr *Mod = U.Use;
8376 Expr *ModOrUse = Ref;
8377 if (OtherKind == UK_Use)
8378 std::swap(Mod, ModOrUse);
8379
8380 SemaRef.Diag(Mod->getExprLoc(),
8381 IsModMod ? diag::warn_unsequenced_mod_mod
8382 : diag::warn_unsequenced_mod_use)
8383 << O << SourceRange(ModOrUse->getExprLoc());
8384 UI.Diagnosed = true;
8385 }
8386
8387 void notePreUse(Object O, Expr *Use) {
8388 UsageInfo &U = UsageMap[O];
8389 // Uses conflict with other modifications.
8390 checkUsage(O, U, Use, UK_ModAsValue, false);
8391 }
8392 void notePostUse(Object O, Expr *Use) {
8393 UsageInfo &U = UsageMap[O];
8394 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8395 addUsage(U, O, Use, UK_Use);
8396 }
8397
8398 void notePreMod(Object O, Expr *Mod) {
8399 UsageInfo &U = UsageMap[O];
8400 // Modifications conflict with other modifications and with uses.
8401 checkUsage(O, U, Mod, UK_ModAsValue, true);
8402 checkUsage(O, U, Mod, UK_Use, false);
8403 }
8404 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8405 UsageInfo &U = UsageMap[O];
8406 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8407 addUsage(U, O, Use, UK);
8408 }
8409
8410public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008411 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008412 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8413 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008414 Visit(E);
8415 }
8416
8417 void VisitStmt(Stmt *S) {
8418 // Skip all statements which aren't expressions for now.
8419 }
8420
8421 void VisitExpr(Expr *E) {
8422 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008423 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008424 }
8425
8426 void VisitCastExpr(CastExpr *E) {
8427 Object O = Object();
8428 if (E->getCastKind() == CK_LValueToRValue)
8429 O = getObject(E->getSubExpr(), false);
8430
8431 if (O)
8432 notePreUse(O, E);
8433 VisitExpr(E);
8434 if (O)
8435 notePostUse(O, E);
8436 }
8437
8438 void VisitBinComma(BinaryOperator *BO) {
8439 // C++11 [expr.comma]p1:
8440 // Every value computation and side effect associated with the left
8441 // expression is sequenced before every value computation and side
8442 // effect associated with the right expression.
8443 SequenceTree::Seq LHS = Tree.allocate(Region);
8444 SequenceTree::Seq RHS = Tree.allocate(Region);
8445 SequenceTree::Seq OldRegion = Region;
8446
8447 {
8448 SequencedSubexpression SeqLHS(*this);
8449 Region = LHS;
8450 Visit(BO->getLHS());
8451 }
8452
8453 Region = RHS;
8454 Visit(BO->getRHS());
8455
8456 Region = OldRegion;
8457
8458 // Forget that LHS and RHS are sequenced. They are both unsequenced
8459 // with respect to other stuff.
8460 Tree.merge(LHS);
8461 Tree.merge(RHS);
8462 }
8463
8464 void VisitBinAssign(BinaryOperator *BO) {
8465 // The modification is sequenced after the value computation of the LHS
8466 // and RHS, so check it before inspecting the operands and update the
8467 // map afterwards.
8468 Object O = getObject(BO->getLHS(), true);
8469 if (!O)
8470 return VisitExpr(BO);
8471
8472 notePreMod(O, BO);
8473
8474 // C++11 [expr.ass]p7:
8475 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8476 // only once.
8477 //
8478 // Therefore, for a compound assignment operator, O is considered used
8479 // everywhere except within the evaluation of E1 itself.
8480 if (isa<CompoundAssignOperator>(BO))
8481 notePreUse(O, BO);
8482
8483 Visit(BO->getLHS());
8484
8485 if (isa<CompoundAssignOperator>(BO))
8486 notePostUse(O, BO);
8487
8488 Visit(BO->getRHS());
8489
Richard Smith83e37bee2013-06-26 23:16:51 +00008490 // C++11 [expr.ass]p1:
8491 // the assignment is sequenced [...] before the value computation of the
8492 // assignment expression.
8493 // C11 6.5.16/3 has no such rule.
8494 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8495 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008496 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008497
Richard Smithc406cb72013-01-17 01:17:56 +00008498 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8499 VisitBinAssign(CAO);
8500 }
8501
8502 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8503 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8504 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8505 Object O = getObject(UO->getSubExpr(), true);
8506 if (!O)
8507 return VisitExpr(UO);
8508
8509 notePreMod(O, UO);
8510 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008511 // C++11 [expr.pre.incr]p1:
8512 // the expression ++x is equivalent to x+=1
8513 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8514 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008515 }
8516
8517 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8518 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8519 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8520 Object O = getObject(UO->getSubExpr(), true);
8521 if (!O)
8522 return VisitExpr(UO);
8523
8524 notePreMod(O, UO);
8525 Visit(UO->getSubExpr());
8526 notePostMod(O, UO, UK_ModAsSideEffect);
8527 }
8528
8529 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8530 void VisitBinLOr(BinaryOperator *BO) {
8531 // The side-effects of the LHS of an '&&' are sequenced before the
8532 // value computation of the RHS, and hence before the value computation
8533 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8534 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008535 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008536 {
8537 SequencedSubexpression Sequenced(*this);
8538 Visit(BO->getLHS());
8539 }
8540
8541 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008542 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008543 if (!Result)
8544 Visit(BO->getRHS());
8545 } else {
8546 // Check for unsequenced operations in the RHS, treating it as an
8547 // entirely separate evaluation.
8548 //
8549 // FIXME: If there are operations in the RHS which are unsequenced
8550 // with respect to operations outside the RHS, and those operations
8551 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008552 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008553 }
Richard Smithc406cb72013-01-17 01:17:56 +00008554 }
8555 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008556 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008557 {
8558 SequencedSubexpression Sequenced(*this);
8559 Visit(BO->getLHS());
8560 }
8561
8562 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008563 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008564 if (Result)
8565 Visit(BO->getRHS());
8566 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008567 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008568 }
Richard Smithc406cb72013-01-17 01:17:56 +00008569 }
8570
8571 // Only visit the condition, unless we can be sure which subexpression will
8572 // be chosen.
8573 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008574 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008575 {
8576 SequencedSubexpression Sequenced(*this);
8577 Visit(CO->getCond());
8578 }
Richard Smithc406cb72013-01-17 01:17:56 +00008579
8580 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008581 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008582 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008583 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008584 WorkList.push_back(CO->getTrueExpr());
8585 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008586 }
Richard Smithc406cb72013-01-17 01:17:56 +00008587 }
8588
Richard Smithe3dbfe02013-06-30 10:40:20 +00008589 void VisitCallExpr(CallExpr *CE) {
8590 // C++11 [intro.execution]p15:
8591 // When calling a function [...], every value computation and side effect
8592 // associated with any argument expression, or with the postfix expression
8593 // designating the called function, is sequenced before execution of every
8594 // expression or statement in the body of the function [and thus before
8595 // the value computation of its result].
8596 SequencedSubexpression Sequenced(*this);
8597 Base::VisitCallExpr(CE);
8598
8599 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8600 }
8601
Richard Smithc406cb72013-01-17 01:17:56 +00008602 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008603 // This is a call, so all subexpressions are sequenced before the result.
8604 SequencedSubexpression Sequenced(*this);
8605
Richard Smithc406cb72013-01-17 01:17:56 +00008606 if (!CCE->isListInitialization())
8607 return VisitExpr(CCE);
8608
8609 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008610 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008611 SequenceTree::Seq Parent = Region;
8612 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8613 E = CCE->arg_end();
8614 I != E; ++I) {
8615 Region = Tree.allocate(Parent);
8616 Elts.push_back(Region);
8617 Visit(*I);
8618 }
8619
8620 // Forget that the initializers are sequenced.
8621 Region = Parent;
8622 for (unsigned I = 0; I < Elts.size(); ++I)
8623 Tree.merge(Elts[I]);
8624 }
8625
8626 void VisitInitListExpr(InitListExpr *ILE) {
8627 if (!SemaRef.getLangOpts().CPlusPlus11)
8628 return VisitExpr(ILE);
8629
8630 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008631 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008632 SequenceTree::Seq Parent = Region;
8633 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8634 Expr *E = ILE->getInit(I);
8635 if (!E) continue;
8636 Region = Tree.allocate(Parent);
8637 Elts.push_back(Region);
8638 Visit(E);
8639 }
8640
8641 // Forget that the initializers are sequenced.
8642 Region = Parent;
8643 for (unsigned I = 0; I < Elts.size(); ++I)
8644 Tree.merge(Elts[I]);
8645 }
8646};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00008647} // end anonymous namespace
Richard Smithc406cb72013-01-17 01:17:56 +00008648
8649void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008650 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008651 WorkList.push_back(E);
8652 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008653 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008654 SequenceChecker(*this, Item, WorkList);
8655 }
Richard Smithc406cb72013-01-17 01:17:56 +00008656}
8657
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008658void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8659 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008660 CheckImplicitConversions(E, CheckLoc);
8661 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008662 if (!IsConstexpr && !E->isValueDependent())
8663 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008664}
8665
John McCall1f425642010-11-11 03:21:53 +00008666void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8667 FieldDecl *BitField,
8668 Expr *Init) {
8669 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8670}
8671
David Majnemer61a5bbf2015-04-07 22:08:51 +00008672static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8673 SourceLocation Loc) {
8674 if (!PType->isVariablyModifiedType())
8675 return;
8676 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8677 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8678 return;
8679 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008680 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8681 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8682 return;
8683 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008684 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8685 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8686 return;
8687 }
8688
8689 const ArrayType *AT = S.Context.getAsArrayType(PType);
8690 if (!AT)
8691 return;
8692
8693 if (AT->getSizeModifier() != ArrayType::Star) {
8694 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8695 return;
8696 }
8697
8698 S.Diag(Loc, diag::err_array_star_in_function_definition);
8699}
8700
Mike Stump0c2ec772010-01-21 03:59:47 +00008701/// CheckParmsForFunctionDef - Check that the parameters of the given
8702/// function are appropriate for the definition of a function. This
8703/// takes care of any checks that cannot be performed on the
8704/// declaration itself, e.g., that the types of each of the function
8705/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008706bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8707 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008708 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008709 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008710 for (; P != PEnd; ++P) {
8711 ParmVarDecl *Param = *P;
8712
Mike Stump0c2ec772010-01-21 03:59:47 +00008713 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8714 // function declarator that is part of a function definition of
8715 // that function shall not have incomplete type.
8716 //
8717 // This is also C++ [dcl.fct]p6.
8718 if (!Param->isInvalidDecl() &&
8719 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008720 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008721 Param->setInvalidDecl();
8722 HasInvalidParm = true;
8723 }
8724
8725 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8726 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008727 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008728 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008729 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008730 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008731 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008732
8733 // C99 6.7.5.3p12:
8734 // If the function declarator is not part of a definition of that
8735 // function, parameters may have incomplete type and may use the [*]
8736 // notation in their sequences of declarator specifiers to specify
8737 // variable length array types.
8738 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008739 // FIXME: This diagnostic should point the '[*]' if source-location
8740 // information is added for it.
8741 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008742
8743 // MSVC destroys objects passed by value in the callee. Therefore a
8744 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008745 // object's destructor. However, we don't perform any direct access check
8746 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008747 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8748 .getCXXABI()
8749 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008750 if (!Param->isInvalidDecl()) {
8751 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8752 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8753 if (!ClassDecl->isInvalidDecl() &&
8754 !ClassDecl->hasIrrelevantDestructor() &&
8755 !ClassDecl->isDependentContext()) {
8756 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8757 MarkFunctionReferenced(Param->getLocation(), Destructor);
8758 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8759 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008760 }
8761 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008762 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008763
8764 // Parameters with the pass_object_size attribute only need to be marked
8765 // constant at function definitions. Because we lack information about
8766 // whether we're on a declaration or definition when we're instantiating the
8767 // attribute, we need to check for constness here.
8768 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8769 if (!Param->getType().isConstQualified())
8770 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8771 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008772 }
8773
8774 return HasInvalidParm;
8775}
John McCall2b5c1b22010-08-12 21:44:57 +00008776
8777/// CheckCastAlign - Implements -Wcast-align, which warns when a
8778/// pointer cast increases the alignment requirements.
8779void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8780 // This is actually a lot of work to potentially be doing on every
8781 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008782 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008783 return;
8784
8785 // Ignore dependent types.
8786 if (T->isDependentType() || Op->getType()->isDependentType())
8787 return;
8788
8789 // Require that the destination be a pointer type.
8790 const PointerType *DestPtr = T->getAs<PointerType>();
8791 if (!DestPtr) return;
8792
8793 // If the destination has alignment 1, we're done.
8794 QualType DestPointee = DestPtr->getPointeeType();
8795 if (DestPointee->isIncompleteType()) return;
8796 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8797 if (DestAlign.isOne()) return;
8798
8799 // Require that the source be a pointer type.
8800 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8801 if (!SrcPtr) return;
8802 QualType SrcPointee = SrcPtr->getPointeeType();
8803
8804 // Whitelist casts from cv void*. We already implicitly
8805 // whitelisted casts to cv void*, since they have alignment 1.
8806 // Also whitelist casts involving incomplete types, which implicitly
8807 // includes 'void'.
8808 if (SrcPointee->isIncompleteType()) return;
8809
8810 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8811 if (SrcAlign >= DestAlign) return;
8812
8813 Diag(TRange.getBegin(), diag::warn_cast_align)
8814 << Op->getType() << T
8815 << static_cast<unsigned>(SrcAlign.getQuantity())
8816 << static_cast<unsigned>(DestAlign.getQuantity())
8817 << TRange << Op->getSourceRange();
8818}
8819
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008820static const Type* getElementType(const Expr *BaseExpr) {
8821 const Type* EltType = BaseExpr->getType().getTypePtr();
8822 if (EltType->isAnyPointerType())
8823 return EltType->getPointeeType().getTypePtr();
8824 else if (EltType->isArrayType())
8825 return EltType->getBaseElementTypeUnsafe();
8826 return EltType;
8827}
8828
Chandler Carruth28389f02011-08-05 09:10:50 +00008829/// \brief Check whether this array fits the idiom of a size-one tail padded
8830/// array member of a struct.
8831///
8832/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8833/// commonly used to emulate flexible arrays in C89 code.
8834static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8835 const NamedDecl *ND) {
8836 if (Size != 1 || !ND) return false;
8837
8838 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8839 if (!FD) return false;
8840
8841 // Don't consider sizes resulting from macro expansions or template argument
8842 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008843
8844 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008845 while (TInfo) {
8846 TypeLoc TL = TInfo->getTypeLoc();
8847 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008848 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8849 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008850 TInfo = TDL->getTypeSourceInfo();
8851 continue;
8852 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008853 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8854 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008855 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8856 return false;
8857 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008858 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008859 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008860
8861 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008862 if (!RD) return false;
8863 if (RD->isUnion()) return false;
8864 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8865 if (!CRD->isStandardLayout()) return false;
8866 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008867
Benjamin Kramer8c543672011-08-06 03:04:42 +00008868 // See if this is the last field decl in the record.
8869 const Decl *D = FD;
8870 while ((D = D->getNextDeclInContext()))
8871 if (isa<FieldDecl>(D))
8872 return false;
8873 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008874}
8875
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008876void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008877 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008878 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008879 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008880 if (IndexExpr->isValueDependent())
8881 return;
8882
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008883 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008884 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008885 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008886 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008887 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008888 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008889
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008890 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00008891 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00008892 return;
Richard Smith13f67182011-12-16 19:31:14 +00008893 if (IndexNegated)
8894 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008895
Craig Topperc3ec1492014-05-26 06:22:03 +00008896 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008897 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8898 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008899 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008900 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008901
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008902 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008903 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008904 if (!size.isStrictlyPositive())
8905 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008906
8907 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008908 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008909 // Make sure we're comparing apples to apples when comparing index to size
8910 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8911 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008912 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008913 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008914 if (ptrarith_typesize != array_typesize) {
8915 // There's a cast to a different size type involved
8916 uint64_t ratio = array_typesize / ptrarith_typesize;
8917 // TODO: Be smarter about handling cases where array_typesize is not a
8918 // multiple of ptrarith_typesize
8919 if (ptrarith_typesize * ratio == array_typesize)
8920 size *= llvm::APInt(size.getBitWidth(), ratio);
8921 }
8922 }
8923
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008924 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008925 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008926 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008927 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008928
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008929 // For array subscripting the index must be less than size, but for pointer
8930 // arithmetic also allow the index (offset) to be equal to size since
8931 // computing the next address after the end of the array is legal and
8932 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008933 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008934 return;
8935
8936 // Also don't warn for arrays of size 1 which are members of some
8937 // structure. These are often used to approximate flexible arrays in C89
8938 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008939 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008940 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008941
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008942 // Suppress the warning if the subscript expression (as identified by the
8943 // ']' location) and the index expression are both from macro expansions
8944 // within a system header.
8945 if (ASE) {
8946 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8947 ASE->getRBracketLoc());
8948 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8949 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8950 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008951 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008952 return;
8953 }
8954 }
8955
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008956 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008957 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008958 DiagID = diag::warn_array_index_exceeds_bounds;
8959
8960 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8961 PDiag(DiagID) << index.toString(10, true)
8962 << size.toString(10, true)
8963 << (unsigned)size.getLimitedValue(~0U)
8964 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008965 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008966 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008967 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008968 DiagID = diag::warn_ptr_arith_precedes_bounds;
8969 if (index.isNegative()) index = -index;
8970 }
8971
8972 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8973 PDiag(DiagID) << index.toString(10, true)
8974 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008975 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008976
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008977 if (!ND) {
8978 // Try harder to find a NamedDecl to point at in the note.
8979 while (const ArraySubscriptExpr *ASE =
8980 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8981 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8982 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8983 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8984 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8985 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8986 }
8987
Chandler Carruth1af88f12011-02-17 21:10:52 +00008988 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008989 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8990 PDiag(diag::note_array_index_out_of_bounds)
8991 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008992}
8993
Ted Kremenekdf26df72011-03-01 18:41:00 +00008994void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008995 int AllowOnePastEnd = 0;
8996 while (expr) {
8997 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008998 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008999 case Stmt::ArraySubscriptExprClass: {
9000 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00009001 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009002 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00009003 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009004 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009005 case Stmt::OMPArraySectionExprClass: {
9006 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9007 if (ASE->getLowerBound())
9008 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9009 /*ASE=*/nullptr, AllowOnePastEnd > 0);
9010 return;
9011 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00009012 case Stmt::UnaryOperatorClass: {
9013 // Only unwrap the * and & unary operators
9014 const UnaryOperator *UO = cast<UnaryOperator>(expr);
9015 expr = UO->getSubExpr();
9016 switch (UO->getOpcode()) {
9017 case UO_AddrOf:
9018 AllowOnePastEnd++;
9019 break;
9020 case UO_Deref:
9021 AllowOnePastEnd--;
9022 break;
9023 default:
9024 return;
9025 }
9026 break;
9027 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009028 case Stmt::ConditionalOperatorClass: {
9029 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9030 if (const Expr *lhs = cond->getLHS())
9031 CheckArrayAccess(lhs);
9032 if (const Expr *rhs = cond->getRHS())
9033 CheckArrayAccess(rhs);
9034 return;
9035 }
9036 default:
9037 return;
9038 }
Peter Collingbourne91147592011-04-15 00:35:48 +00009039 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00009040}
John McCall31168b02011-06-15 23:02:42 +00009041
9042//===--- CHECK: Objective-C retain cycles ----------------------------------//
9043
9044namespace {
9045 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00009046 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00009047 VarDecl *Variable;
9048 SourceRange Range;
9049 SourceLocation Loc;
9050 bool Indirect;
9051
9052 void setLocsFrom(Expr *e) {
9053 Loc = e->getExprLoc();
9054 Range = e->getSourceRange();
9055 }
9056 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009057} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009058
9059/// Consider whether capturing the given variable can possibly lead to
9060/// a retain cycle.
9061static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00009062 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00009063 // lifetime. In MRR, it's captured strongly if the variable is
9064 // __block and has an appropriate type.
9065 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9066 return false;
9067
9068 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009069 if (ref)
9070 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00009071 return true;
9072}
9073
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009074static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00009075 while (true) {
9076 e = e->IgnoreParens();
9077 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9078 switch (cast->getCastKind()) {
9079 case CK_BitCast:
9080 case CK_LValueBitCast:
9081 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00009082 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00009083 e = cast->getSubExpr();
9084 continue;
9085
John McCall31168b02011-06-15 23:02:42 +00009086 default:
9087 return false;
9088 }
9089 }
9090
9091 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9092 ObjCIvarDecl *ivar = ref->getDecl();
9093 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9094 return false;
9095
9096 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009097 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00009098 return false;
9099
9100 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9101 owner.Indirect = true;
9102 return true;
9103 }
9104
9105 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9106 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9107 if (!var) return false;
9108 return considerVariable(var, ref, owner);
9109 }
9110
John McCall31168b02011-06-15 23:02:42 +00009111 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9112 if (member->isArrow()) return false;
9113
9114 // Don't count this as an indirect ownership.
9115 e = member->getBase();
9116 continue;
9117 }
9118
John McCallfe96e0b2011-11-06 09:01:30 +00009119 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9120 // Only pay attention to pseudo-objects on property references.
9121 ObjCPropertyRefExpr *pre
9122 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9123 ->IgnoreParens());
9124 if (!pre) return false;
9125 if (pre->isImplicitProperty()) return false;
9126 ObjCPropertyDecl *property = pre->getExplicitProperty();
9127 if (!property->isRetaining() &&
9128 !(property->getPropertyIvarDecl() &&
9129 property->getPropertyIvarDecl()->getType()
9130 .getObjCLifetime() == Qualifiers::OCL_Strong))
9131 return false;
9132
9133 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009134 if (pre->isSuperReceiver()) {
9135 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9136 if (!owner.Variable)
9137 return false;
9138 owner.Loc = pre->getLocation();
9139 owner.Range = pre->getSourceRange();
9140 return true;
9141 }
John McCallfe96e0b2011-11-06 09:01:30 +00009142 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9143 ->getSourceExpr());
9144 continue;
9145 }
9146
John McCall31168b02011-06-15 23:02:42 +00009147 // Array ivars?
9148
9149 return false;
9150 }
9151}
9152
9153namespace {
9154 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9155 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9156 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009157 Context(Context), Variable(variable), Capturer(nullptr),
9158 VarWillBeReased(false) {}
9159 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00009160 VarDecl *Variable;
9161 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009162 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00009163
9164 void VisitDeclRefExpr(DeclRefExpr *ref) {
9165 if (ref->getDecl() == Variable && !Capturer)
9166 Capturer = ref;
9167 }
9168
John McCall31168b02011-06-15 23:02:42 +00009169 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9170 if (Capturer) return;
9171 Visit(ref->getBase());
9172 if (Capturer && ref->isFreeIvar())
9173 Capturer = ref;
9174 }
9175
9176 void VisitBlockExpr(BlockExpr *block) {
9177 // Look inside nested blocks
9178 if (block->getBlockDecl()->capturesVariable(Variable))
9179 Visit(block->getBlockDecl()->getBody());
9180 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00009181
9182 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9183 if (Capturer) return;
9184 if (OVE->getSourceExpr())
9185 Visit(OVE->getSourceExpr());
9186 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009187 void VisitBinaryOperator(BinaryOperator *BinOp) {
9188 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9189 return;
9190 Expr *LHS = BinOp->getLHS();
9191 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9192 if (DRE->getDecl() != Variable)
9193 return;
9194 if (Expr *RHS = BinOp->getRHS()) {
9195 RHS = RHS->IgnoreParenCasts();
9196 llvm::APSInt Value;
9197 VarWillBeReased =
9198 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9199 }
9200 }
9201 }
John McCall31168b02011-06-15 23:02:42 +00009202 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009203} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00009204
9205/// Check whether the given argument is a block which captures a
9206/// variable.
9207static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9208 assert(owner.Variable && owner.Loc.isValid());
9209
9210 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00009211
9212 // Look through [^{...} copy] and Block_copy(^{...}).
9213 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9214 Selector Cmd = ME->getSelector();
9215 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9216 e = ME->getInstanceReceiver();
9217 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00009218 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00009219 e = e->IgnoreParenCasts();
9220 }
9221 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9222 if (CE->getNumArgs() == 1) {
9223 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00009224 if (Fn) {
9225 const IdentifierInfo *FnI = Fn->getIdentifier();
9226 if (FnI && FnI->isStr("_Block_copy")) {
9227 e = CE->getArg(0)->IgnoreParenCasts();
9228 }
9229 }
Jordan Rose67e887c2012-09-17 17:54:30 +00009230 }
9231 }
9232
John McCall31168b02011-06-15 23:02:42 +00009233 BlockExpr *block = dyn_cast<BlockExpr>(e);
9234 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00009235 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00009236
9237 FindCaptureVisitor visitor(S.Context, owner.Variable);
9238 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00009239 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00009240}
9241
9242static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9243 RetainCycleOwner &owner) {
9244 assert(capturer);
9245 assert(owner.Variable && owner.Loc.isValid());
9246
9247 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9248 << owner.Variable << capturer->getSourceRange();
9249 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9250 << owner.Indirect << owner.Range;
9251}
9252
9253/// Check for a keyword selector that starts with the word 'add' or
9254/// 'set'.
9255static bool isSetterLikeSelector(Selector sel) {
9256 if (sel.isUnarySelector()) return false;
9257
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009258 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00009259 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009260 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00009261 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00009262 else if (str.startswith("add")) {
9263 // Specially whitelist 'addOperationWithBlock:'.
9264 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9265 return false;
9266 str = str.substr(3);
9267 }
John McCall31168b02011-06-15 23:02:42 +00009268 else
9269 return false;
9270
9271 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00009272 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00009273}
9274
Benjamin Kramer3a743452015-03-09 15:03:32 +00009275static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9276 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009277 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9278 Message->getReceiverInterface(),
9279 NSAPI::ClassId_NSMutableArray);
9280 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009281 return None;
9282 }
9283
9284 Selector Sel = Message->getSelector();
9285
9286 Optional<NSAPI::NSArrayMethodKind> MKOpt =
9287 S.NSAPIObj->getNSArrayMethodKind(Sel);
9288 if (!MKOpt) {
9289 return None;
9290 }
9291
9292 NSAPI::NSArrayMethodKind MK = *MKOpt;
9293
9294 switch (MK) {
9295 case NSAPI::NSMutableArr_addObject:
9296 case NSAPI::NSMutableArr_insertObjectAtIndex:
9297 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9298 return 0;
9299 case NSAPI::NSMutableArr_replaceObjectAtIndex:
9300 return 1;
9301
9302 default:
9303 return None;
9304 }
9305
9306 return None;
9307}
9308
9309static
9310Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9311 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009312 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9313 Message->getReceiverInterface(),
9314 NSAPI::ClassId_NSMutableDictionary);
9315 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009316 return None;
9317 }
9318
9319 Selector Sel = Message->getSelector();
9320
9321 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9322 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9323 if (!MKOpt) {
9324 return None;
9325 }
9326
9327 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9328
9329 switch (MK) {
9330 case NSAPI::NSMutableDict_setObjectForKey:
9331 case NSAPI::NSMutableDict_setValueForKey:
9332 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9333 return 0;
9334
9335 default:
9336 return None;
9337 }
9338
9339 return None;
9340}
9341
9342static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009343 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9344 Message->getReceiverInterface(),
9345 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009346
Alex Denisov5dfac812015-08-06 04:51:14 +00009347 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9348 Message->getReceiverInterface(),
9349 NSAPI::ClassId_NSMutableOrderedSet);
9350 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009351 return None;
9352 }
9353
9354 Selector Sel = Message->getSelector();
9355
9356 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9357 if (!MKOpt) {
9358 return None;
9359 }
9360
9361 NSAPI::NSSetMethodKind MK = *MKOpt;
9362
9363 switch (MK) {
9364 case NSAPI::NSMutableSet_addObject:
9365 case NSAPI::NSOrderedSet_setObjectAtIndex:
9366 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9367 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9368 return 0;
9369 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9370 return 1;
9371 }
9372
9373 return None;
9374}
9375
9376void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9377 if (!Message->isInstanceMessage()) {
9378 return;
9379 }
9380
9381 Optional<int> ArgOpt;
9382
9383 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9384 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9385 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9386 return;
9387 }
9388
9389 int ArgIndex = *ArgOpt;
9390
Alex Denisove1d882c2015-03-04 17:55:52 +00009391 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9392 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9393 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9394 }
9395
Alex Denisov5dfac812015-08-06 04:51:14 +00009396 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009397 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009398 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009399 Diag(Message->getSourceRange().getBegin(),
9400 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009401 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009402 }
9403 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009404 } else {
9405 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9406
9407 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9408 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9409 }
9410
9411 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9412 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9413 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9414 ValueDecl *Decl = ReceiverRE->getDecl();
9415 Diag(Message->getSourceRange().getBegin(),
9416 diag::warn_objc_circular_container)
9417 << Decl->getName() << Decl->getName();
9418 if (!ArgRE->isObjCSelfExpr()) {
9419 Diag(Decl->getLocation(),
9420 diag::note_objc_circular_container_declared_here)
9421 << Decl->getName();
9422 }
9423 }
9424 }
9425 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9426 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9427 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9428 ObjCIvarDecl *Decl = IvarRE->getDecl();
9429 Diag(Message->getSourceRange().getBegin(),
9430 diag::warn_objc_circular_container)
9431 << Decl->getName() << Decl->getName();
9432 Diag(Decl->getLocation(),
9433 diag::note_objc_circular_container_declared_here)
9434 << Decl->getName();
9435 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009436 }
9437 }
9438 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009439}
9440
John McCall31168b02011-06-15 23:02:42 +00009441/// Check a message send to see if it's likely to cause a retain cycle.
9442void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9443 // Only check instance methods whose selector looks like a setter.
9444 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9445 return;
9446
9447 // Try to find a variable that the receiver is strongly owned by.
9448 RetainCycleOwner owner;
9449 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009450 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009451 return;
9452 } else {
9453 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9454 owner.Variable = getCurMethodDecl()->getSelfDecl();
9455 owner.Loc = msg->getSuperLoc();
9456 owner.Range = msg->getSuperLoc();
9457 }
9458
9459 // Check whether the receiver is captured by any of the arguments.
9460 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9461 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9462 return diagnoseRetainCycle(*this, capturer, owner);
9463}
9464
9465/// Check a property assign to see if it's likely to cause a retain cycle.
9466void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9467 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009468 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009469 return;
9470
9471 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9472 diagnoseRetainCycle(*this, capturer, owner);
9473}
9474
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009475void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9476 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009477 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009478 return;
9479
9480 // Because we don't have an expression for the variable, we have to set the
9481 // location explicitly here.
9482 Owner.Loc = Var->getLocation();
9483 Owner.Range = Var->getSourceRange();
9484
9485 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9486 diagnoseRetainCycle(*this, Capturer, Owner);
9487}
9488
Ted Kremenek9304da92012-12-21 08:04:28 +00009489static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9490 Expr *RHS, bool isProperty) {
9491 // Check if RHS is an Objective-C object literal, which also can get
9492 // immediately zapped in a weak reference. Note that we explicitly
9493 // allow ObjCStringLiterals, since those are designed to never really die.
9494 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009495
Ted Kremenek64873352012-12-21 22:46:35 +00009496 // This enum needs to match with the 'select' in
9497 // warn_objc_arc_literal_assign (off-by-1).
9498 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9499 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9500 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009501
9502 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009503 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009504 << (isProperty ? 0 : 1)
9505 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009506
9507 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009508}
9509
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009510static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9511 Qualifiers::ObjCLifetime LT,
9512 Expr *RHS, bool isProperty) {
9513 // Strip off any implicit cast added to get to the one ARC-specific.
9514 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9515 if (cast->getCastKind() == CK_ARCConsumeObject) {
9516 S.Diag(Loc, diag::warn_arc_retained_assign)
9517 << (LT == Qualifiers::OCL_ExplicitNone)
9518 << (isProperty ? 0 : 1)
9519 << RHS->getSourceRange();
9520 return true;
9521 }
9522 RHS = cast->getSubExpr();
9523 }
9524
9525 if (LT == Qualifiers::OCL_Weak &&
9526 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9527 return true;
9528
9529 return false;
9530}
9531
Ted Kremenekb36234d2012-12-21 08:04:20 +00009532bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9533 QualType LHS, Expr *RHS) {
9534 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9535
9536 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9537 return false;
9538
9539 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9540 return true;
9541
9542 return false;
9543}
9544
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009545void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9546 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009547 QualType LHSType;
9548 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009549 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009550 ObjCPropertyRefExpr *PRE
9551 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9552 if (PRE && !PRE->isImplicitProperty()) {
9553 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9554 if (PD)
9555 LHSType = PD->getType();
9556 }
9557
9558 if (LHSType.isNull())
9559 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009560
9561 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9562
9563 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009564 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009565 getCurFunction()->markSafeWeakUse(LHS);
9566 }
9567
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009568 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9569 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009570
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009571 // FIXME. Check for other life times.
9572 if (LT != Qualifiers::OCL_None)
9573 return;
9574
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009575 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009576 if (PRE->isImplicitProperty())
9577 return;
9578 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9579 if (!PD)
9580 return;
9581
Bill Wendling44426052012-12-20 19:22:21 +00009582 unsigned Attributes = PD->getPropertyAttributes();
9583 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009584 // when 'assign' attribute was not explicitly specified
9585 // by user, ignore it and rely on property type itself
9586 // for lifetime info.
9587 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9588 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9589 LHSType->isObjCRetainableType())
9590 return;
9591
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009592 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009593 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009594 Diag(Loc, diag::warn_arc_retained_property_assign)
9595 << RHS->getSourceRange();
9596 return;
9597 }
9598 RHS = cast->getSubExpr();
9599 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009600 }
Bill Wendling44426052012-12-20 19:22:21 +00009601 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009602 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9603 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009604 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009605 }
9606}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009607
9608//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9609
9610namespace {
9611bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9612 SourceLocation StmtLoc,
9613 const NullStmt *Body) {
9614 // Do not warn if the body is a macro that expands to nothing, e.g:
9615 //
9616 // #define CALL(x)
9617 // if (condition)
9618 // CALL(0);
9619 //
9620 if (Body->hasLeadingEmptyMacro())
9621 return false;
9622
9623 // Get line numbers of statement and body.
9624 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009625 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009626 &StmtLineInvalid);
9627 if (StmtLineInvalid)
9628 return false;
9629
9630 bool BodyLineInvalid;
9631 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9632 &BodyLineInvalid);
9633 if (BodyLineInvalid)
9634 return false;
9635
9636 // Warn if null statement and body are on the same line.
9637 if (StmtLine != BodyLine)
9638 return false;
9639
9640 return true;
9641}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009642} // end anonymous namespace
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009643
9644void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9645 const Stmt *Body,
9646 unsigned DiagID) {
9647 // Since this is a syntactic check, don't emit diagnostic for template
9648 // instantiations, this just adds noise.
9649 if (CurrentInstantiationScope)
9650 return;
9651
9652 // The body should be a null statement.
9653 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9654 if (!NBody)
9655 return;
9656
9657 // Do the usual checks.
9658 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9659 return;
9660
9661 Diag(NBody->getSemiLoc(), DiagID);
9662 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9663}
9664
9665void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9666 const Stmt *PossibleBody) {
9667 assert(!CurrentInstantiationScope); // Ensured by caller
9668
9669 SourceLocation StmtLoc;
9670 const Stmt *Body;
9671 unsigned DiagID;
9672 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9673 StmtLoc = FS->getRParenLoc();
9674 Body = FS->getBody();
9675 DiagID = diag::warn_empty_for_body;
9676 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9677 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9678 Body = WS->getBody();
9679 DiagID = diag::warn_empty_while_body;
9680 } else
9681 return; // Neither `for' nor `while'.
9682
9683 // The body should be a null statement.
9684 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9685 if (!NBody)
9686 return;
9687
9688 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009689 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009690 return;
9691
9692 // Do the usual checks.
9693 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9694 return;
9695
9696 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9697 // noise level low, emit diagnostics only if for/while is followed by a
9698 // CompoundStmt, e.g.:
9699 // for (int i = 0; i < n; i++);
9700 // {
9701 // a(i);
9702 // }
9703 // or if for/while is followed by a statement with more indentation
9704 // than for/while itself:
9705 // for (int i = 0; i < n; i++);
9706 // a(i);
9707 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9708 if (!ProbableTypo) {
9709 bool BodyColInvalid;
9710 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9711 PossibleBody->getLocStart(),
9712 &BodyColInvalid);
9713 if (BodyColInvalid)
9714 return;
9715
9716 bool StmtColInvalid;
9717 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9718 S->getLocStart(),
9719 &StmtColInvalid);
9720 if (StmtColInvalid)
9721 return;
9722
9723 if (BodyCol > StmtCol)
9724 ProbableTypo = true;
9725 }
9726
9727 if (ProbableTypo) {
9728 Diag(NBody->getSemiLoc(), DiagID);
9729 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9730 }
9731}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009732
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009733//===--- CHECK: Warn on self move with std::move. -------------------------===//
9734
9735/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9736void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9737 SourceLocation OpLoc) {
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009738 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9739 return;
9740
9741 if (!ActiveTemplateInstantiations.empty())
9742 return;
9743
9744 // Strip parens and casts away.
9745 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9746 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9747
9748 // Check for a call expression
9749 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9750 if (!CE || CE->getNumArgs() != 1)
9751 return;
9752
9753 // Check for a call to std::move
9754 const FunctionDecl *FD = CE->getDirectCallee();
9755 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9756 !FD->getIdentifier()->isStr("move"))
9757 return;
9758
9759 // Get argument from std::move
9760 RHSExpr = CE->getArg(0);
9761
9762 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9763 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9764
9765 // Two DeclRefExpr's, check that the decls are the same.
9766 if (LHSDeclRef && RHSDeclRef) {
9767 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9768 return;
9769 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9770 RHSDeclRef->getDecl()->getCanonicalDecl())
9771 return;
9772
9773 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9774 << LHSExpr->getSourceRange()
9775 << RHSExpr->getSourceRange();
9776 return;
9777 }
9778
9779 // Member variables require a different approach to check for self moves.
9780 // MemberExpr's are the same if every nested MemberExpr refers to the same
9781 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9782 // the base Expr's are CXXThisExpr's.
9783 const Expr *LHSBase = LHSExpr;
9784 const Expr *RHSBase = RHSExpr;
9785 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9786 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9787 if (!LHSME || !RHSME)
9788 return;
9789
9790 while (LHSME && RHSME) {
9791 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9792 RHSME->getMemberDecl()->getCanonicalDecl())
9793 return;
9794
9795 LHSBase = LHSME->getBase();
9796 RHSBase = RHSME->getBase();
9797 LHSME = dyn_cast<MemberExpr>(LHSBase);
9798 RHSME = dyn_cast<MemberExpr>(RHSBase);
9799 }
9800
9801 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9802 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9803 if (LHSDeclRef && RHSDeclRef) {
9804 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9805 return;
9806 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9807 RHSDeclRef->getDecl()->getCanonicalDecl())
9808 return;
9809
9810 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9811 << LHSExpr->getSourceRange()
9812 << RHSExpr->getSourceRange();
9813 return;
9814 }
9815
9816 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9817 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9818 << LHSExpr->getSourceRange()
9819 << RHSExpr->getSourceRange();
9820}
9821
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009822//===--- Layout compatibility ----------------------------------------------//
9823
9824namespace {
9825
9826bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9827
9828/// \brief Check if two enumeration types are layout-compatible.
9829bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9830 // C++11 [dcl.enum] p8:
9831 // Two enumeration types are layout-compatible if they have the same
9832 // underlying type.
9833 return ED1->isComplete() && ED2->isComplete() &&
9834 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9835}
9836
9837/// \brief Check if two fields are layout-compatible.
9838bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9839 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9840 return false;
9841
9842 if (Field1->isBitField() != Field2->isBitField())
9843 return false;
9844
9845 if (Field1->isBitField()) {
9846 // Make sure that the bit-fields are the same length.
9847 unsigned Bits1 = Field1->getBitWidthValue(C);
9848 unsigned Bits2 = Field2->getBitWidthValue(C);
9849
9850 if (Bits1 != Bits2)
9851 return false;
9852 }
9853
9854 return true;
9855}
9856
9857/// \brief Check if two standard-layout structs are layout-compatible.
9858/// (C++11 [class.mem] p17)
9859bool isLayoutCompatibleStruct(ASTContext &C,
9860 RecordDecl *RD1,
9861 RecordDecl *RD2) {
9862 // If both records are C++ classes, check that base classes match.
9863 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9864 // If one of records is a CXXRecordDecl we are in C++ mode,
9865 // thus the other one is a CXXRecordDecl, too.
9866 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9867 // Check number of base classes.
9868 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9869 return false;
9870
9871 // Check the base classes.
9872 for (CXXRecordDecl::base_class_const_iterator
9873 Base1 = D1CXX->bases_begin(),
9874 BaseEnd1 = D1CXX->bases_end(),
9875 Base2 = D2CXX->bases_begin();
9876 Base1 != BaseEnd1;
9877 ++Base1, ++Base2) {
9878 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9879 return false;
9880 }
9881 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9882 // If only RD2 is a C++ class, it should have zero base classes.
9883 if (D2CXX->getNumBases() > 0)
9884 return false;
9885 }
9886
9887 // Check the fields.
9888 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9889 Field2End = RD2->field_end(),
9890 Field1 = RD1->field_begin(),
9891 Field1End = RD1->field_end();
9892 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9893 if (!isLayoutCompatible(C, *Field1, *Field2))
9894 return false;
9895 }
9896 if (Field1 != Field1End || Field2 != Field2End)
9897 return false;
9898
9899 return true;
9900}
9901
9902/// \brief Check if two standard-layout unions are layout-compatible.
9903/// (C++11 [class.mem] p18)
9904bool isLayoutCompatibleUnion(ASTContext &C,
9905 RecordDecl *RD1,
9906 RecordDecl *RD2) {
9907 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009908 for (auto *Field2 : RD2->fields())
9909 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009910
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009911 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009912 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9913 I = UnmatchedFields.begin(),
9914 E = UnmatchedFields.end();
9915
9916 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009917 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009918 bool Result = UnmatchedFields.erase(*I);
9919 (void) Result;
9920 assert(Result);
9921 break;
9922 }
9923 }
9924 if (I == E)
9925 return false;
9926 }
9927
9928 return UnmatchedFields.empty();
9929}
9930
9931bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9932 if (RD1->isUnion() != RD2->isUnion())
9933 return false;
9934
9935 if (RD1->isUnion())
9936 return isLayoutCompatibleUnion(C, RD1, RD2);
9937 else
9938 return isLayoutCompatibleStruct(C, RD1, RD2);
9939}
9940
9941/// \brief Check if two types are layout-compatible in C++11 sense.
9942bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9943 if (T1.isNull() || T2.isNull())
9944 return false;
9945
9946 // C++11 [basic.types] p11:
9947 // If two types T1 and T2 are the same type, then T1 and T2 are
9948 // layout-compatible types.
9949 if (C.hasSameType(T1, T2))
9950 return true;
9951
9952 T1 = T1.getCanonicalType().getUnqualifiedType();
9953 T2 = T2.getCanonicalType().getUnqualifiedType();
9954
9955 const Type::TypeClass TC1 = T1->getTypeClass();
9956 const Type::TypeClass TC2 = T2->getTypeClass();
9957
9958 if (TC1 != TC2)
9959 return false;
9960
9961 if (TC1 == Type::Enum) {
9962 return isLayoutCompatible(C,
9963 cast<EnumType>(T1)->getDecl(),
9964 cast<EnumType>(T2)->getDecl());
9965 } else if (TC1 == Type::Record) {
9966 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9967 return false;
9968
9969 return isLayoutCompatible(C,
9970 cast<RecordType>(T1)->getDecl(),
9971 cast<RecordType>(T2)->getDecl());
9972 }
9973
9974 return false;
9975}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00009976} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009977
9978//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9979
9980namespace {
9981/// \brief Given a type tag expression find the type tag itself.
9982///
9983/// \param TypeExpr Type tag expression, as it appears in user's code.
9984///
9985/// \param VD Declaration of an identifier that appears in a type tag.
9986///
9987/// \param MagicValue Type tag magic value.
9988bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9989 const ValueDecl **VD, uint64_t *MagicValue) {
9990 while(true) {
9991 if (!TypeExpr)
9992 return false;
9993
9994 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9995
9996 switch (TypeExpr->getStmtClass()) {
9997 case Stmt::UnaryOperatorClass: {
9998 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9999 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10000 TypeExpr = UO->getSubExpr();
10001 continue;
10002 }
10003 return false;
10004 }
10005
10006 case Stmt::DeclRefExprClass: {
10007 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10008 *VD = DRE->getDecl();
10009 return true;
10010 }
10011
10012 case Stmt::IntegerLiteralClass: {
10013 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10014 llvm::APInt MagicValueAPInt = IL->getValue();
10015 if (MagicValueAPInt.getActiveBits() <= 64) {
10016 *MagicValue = MagicValueAPInt.getZExtValue();
10017 return true;
10018 } else
10019 return false;
10020 }
10021
10022 case Stmt::BinaryConditionalOperatorClass:
10023 case Stmt::ConditionalOperatorClass: {
10024 const AbstractConditionalOperator *ACO =
10025 cast<AbstractConditionalOperator>(TypeExpr);
10026 bool Result;
10027 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10028 if (Result)
10029 TypeExpr = ACO->getTrueExpr();
10030 else
10031 TypeExpr = ACO->getFalseExpr();
10032 continue;
10033 }
10034 return false;
10035 }
10036
10037 case Stmt::BinaryOperatorClass: {
10038 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10039 if (BO->getOpcode() == BO_Comma) {
10040 TypeExpr = BO->getRHS();
10041 continue;
10042 }
10043 return false;
10044 }
10045
10046 default:
10047 return false;
10048 }
10049 }
10050}
10051
10052/// \brief Retrieve the C type corresponding to type tag TypeExpr.
10053///
10054/// \param TypeExpr Expression that specifies a type tag.
10055///
10056/// \param MagicValues Registered magic values.
10057///
10058/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10059/// kind.
10060///
10061/// \param TypeInfo Information about the corresponding C type.
10062///
10063/// \returns true if the corresponding C type was found.
10064bool GetMatchingCType(
10065 const IdentifierInfo *ArgumentKind,
10066 const Expr *TypeExpr, const ASTContext &Ctx,
10067 const llvm::DenseMap<Sema::TypeTagMagicValue,
10068 Sema::TypeTagData> *MagicValues,
10069 bool &FoundWrongKind,
10070 Sema::TypeTagData &TypeInfo) {
10071 FoundWrongKind = false;
10072
10073 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +000010074 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010075
10076 uint64_t MagicValue;
10077
10078 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10079 return false;
10080
10081 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +000010082 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010083 if (I->getArgumentKind() != ArgumentKind) {
10084 FoundWrongKind = true;
10085 return false;
10086 }
10087 TypeInfo.Type = I->getMatchingCType();
10088 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10089 TypeInfo.MustBeNull = I->getMustBeNull();
10090 return true;
10091 }
10092 return false;
10093 }
10094
10095 if (!MagicValues)
10096 return false;
10097
10098 llvm::DenseMap<Sema::TypeTagMagicValue,
10099 Sema::TypeTagData>::const_iterator I =
10100 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10101 if (I == MagicValues->end())
10102 return false;
10103
10104 TypeInfo = I->second;
10105 return true;
10106}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010107} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010108
10109void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10110 uint64_t MagicValue, QualType Type,
10111 bool LayoutCompatible,
10112 bool MustBeNull) {
10113 if (!TypeTagForDatatypeMagicValues)
10114 TypeTagForDatatypeMagicValues.reset(
10115 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10116
10117 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10118 (*TypeTagForDatatypeMagicValues)[Magic] =
10119 TypeTagData(Type, LayoutCompatible, MustBeNull);
10120}
10121
10122namespace {
10123bool IsSameCharType(QualType T1, QualType T2) {
10124 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10125 if (!BT1)
10126 return false;
10127
10128 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10129 if (!BT2)
10130 return false;
10131
10132 BuiltinType::Kind T1Kind = BT1->getKind();
10133 BuiltinType::Kind T2Kind = BT2->getKind();
10134
10135 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
10136 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
10137 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10138 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10139}
Eugene Zelenko1ced5092016-02-12 22:53:10 +000010140} // end anonymous namespace
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010141
10142void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10143 const Expr * const *ExprArgs) {
10144 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10145 bool IsPointerAttr = Attr->getIsPointer();
10146
10147 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10148 bool FoundWrongKind;
10149 TypeTagData TypeInfo;
10150 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10151 TypeTagForDatatypeMagicValues.get(),
10152 FoundWrongKind, TypeInfo)) {
10153 if (FoundWrongKind)
10154 Diag(TypeTagExpr->getExprLoc(),
10155 diag::warn_type_tag_for_datatype_wrong_kind)
10156 << TypeTagExpr->getSourceRange();
10157 return;
10158 }
10159
10160 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10161 if (IsPointerAttr) {
10162 // Skip implicit cast of pointer to `void *' (as a function argument).
10163 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +000010164 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +000010165 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010166 ArgumentExpr = ICE->getSubExpr();
10167 }
10168 QualType ArgumentType = ArgumentExpr->getType();
10169
10170 // Passing a `void*' pointer shouldn't trigger a warning.
10171 if (IsPointerAttr && ArgumentType->isVoidPointerType())
10172 return;
10173
10174 if (TypeInfo.MustBeNull) {
10175 // Type tag with matching void type requires a null pointer.
10176 if (!ArgumentExpr->isNullPointerConstant(Context,
10177 Expr::NPC_ValueDependentIsNotNull)) {
10178 Diag(ArgumentExpr->getExprLoc(),
10179 diag::warn_type_safety_null_pointer_required)
10180 << ArgumentKind->getName()
10181 << ArgumentExpr->getSourceRange()
10182 << TypeTagExpr->getSourceRange();
10183 }
10184 return;
10185 }
10186
10187 QualType RequiredType = TypeInfo.Type;
10188 if (IsPointerAttr)
10189 RequiredType = Context.getPointerType(RequiredType);
10190
10191 bool mismatch = false;
10192 if (!TypeInfo.LayoutCompatible) {
10193 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10194
10195 // C++11 [basic.fundamental] p1:
10196 // Plain char, signed char, and unsigned char are three distinct types.
10197 //
10198 // But we treat plain `char' as equivalent to `signed char' or `unsigned
10199 // char' depending on the current char signedness mode.
10200 if (mismatch)
10201 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10202 RequiredType->getPointeeType())) ||
10203 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10204 mismatch = false;
10205 } else
10206 if (IsPointerAttr)
10207 mismatch = !isLayoutCompatible(Context,
10208 ArgumentType->getPointeeType(),
10209 RequiredType->getPointeeType());
10210 else
10211 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10212
10213 if (mismatch)
10214 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +000010215 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +000010216 << TypeInfo.LayoutCompatible << RequiredType
10217 << ArgumentExpr->getSourceRange()
10218 << TypeTagExpr->getSourceRange();
10219}