blob: 7462869306340da075b73997bb90dc71d39f4b73 [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"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
John McCalldadc5752010-08-24 06:29:42 +0000142ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000143Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
144 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000145 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000146
Chris Lattner3be167f2010-10-01 23:23:24 +0000147 // Find out if any arguments are required to be integer constant expressions.
148 unsigned ICEArguments = 0;
149 ASTContext::GetBuiltinTypeError Error;
150 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
151 if (Error != ASTContext::GE_None)
152 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
153
154 // If any arguments are required to be ICE's, check and diagnose.
155 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
156 // Skip arguments not required to be ICE's.
157 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
158
159 llvm::APSInt Result;
160 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
161 return true;
162 ICEArguments &= ~(1 << ArgNo);
163 }
164
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000165 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000166 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000167 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000168 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000169 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000170 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000171 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000172 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000173 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000174 if (SemaBuiltinVAStart(TheCall))
175 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000176 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000177 case Builtin::BI__va_start: {
178 switch (Context.getTargetInfo().getTriple().getArch()) {
179 case llvm::Triple::arm:
180 case llvm::Triple::thumb:
181 if (SemaBuiltinVAStartARM(TheCall))
182 return ExprError();
183 break;
184 default:
185 if (SemaBuiltinVAStart(TheCall))
186 return ExprError();
187 break;
188 }
189 break;
190 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000191 case Builtin::BI__builtin_isgreater:
192 case Builtin::BI__builtin_isgreaterequal:
193 case Builtin::BI__builtin_isless:
194 case Builtin::BI__builtin_islessequal:
195 case Builtin::BI__builtin_islessgreater:
196 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000197 if (SemaBuiltinUnorderedCompare(TheCall))
198 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000199 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000200 case Builtin::BI__builtin_fpclassify:
201 if (SemaBuiltinFPClassification(TheCall, 6))
202 return ExprError();
203 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000204 case Builtin::BI__builtin_isfinite:
205 case Builtin::BI__builtin_isinf:
206 case Builtin::BI__builtin_isinf_sign:
207 case Builtin::BI__builtin_isnan:
208 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000209 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000210 return ExprError();
211 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000212 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000213 return SemaBuiltinShuffleVector(TheCall);
214 // TheCall will be freed by the smart pointer here, but that's fine, since
215 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000216 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000217 if (SemaBuiltinPrefetch(TheCall))
218 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000219 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000220 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000221 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000222 if (SemaBuiltinAssume(TheCall))
223 return ExprError();
224 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000225 case Builtin::BI__builtin_assume_aligned:
226 if (SemaBuiltinAssumeAligned(TheCall))
227 return ExprError();
228 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000229 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000230 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000231 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000232 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000233 case Builtin::BI__builtin_longjmp:
234 if (SemaBuiltinLongjmp(TheCall))
235 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000236 break;
John McCallbebede42011-02-26 05:39:39 +0000237
238 case Builtin::BI__builtin_classify_type:
239 if (checkArgCount(*this, TheCall, 1)) return true;
240 TheCall->setType(Context.IntTy);
241 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000242 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000243 if (checkArgCount(*this, TheCall, 1)) return true;
244 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000245 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000246 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000247 case Builtin::BI__sync_fetch_and_add_1:
248 case Builtin::BI__sync_fetch_and_add_2:
249 case Builtin::BI__sync_fetch_and_add_4:
250 case Builtin::BI__sync_fetch_and_add_8:
251 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000252 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000253 case Builtin::BI__sync_fetch_and_sub_1:
254 case Builtin::BI__sync_fetch_and_sub_2:
255 case Builtin::BI__sync_fetch_and_sub_4:
256 case Builtin::BI__sync_fetch_and_sub_8:
257 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000258 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000259 case Builtin::BI__sync_fetch_and_or_1:
260 case Builtin::BI__sync_fetch_and_or_2:
261 case Builtin::BI__sync_fetch_and_or_4:
262 case Builtin::BI__sync_fetch_and_or_8:
263 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000264 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000265 case Builtin::BI__sync_fetch_and_and_1:
266 case Builtin::BI__sync_fetch_and_and_2:
267 case Builtin::BI__sync_fetch_and_and_4:
268 case Builtin::BI__sync_fetch_and_and_8:
269 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000270 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000271 case Builtin::BI__sync_fetch_and_xor_1:
272 case Builtin::BI__sync_fetch_and_xor_2:
273 case Builtin::BI__sync_fetch_and_xor_4:
274 case Builtin::BI__sync_fetch_and_xor_8:
275 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000276 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000277 case Builtin::BI__sync_add_and_fetch_1:
278 case Builtin::BI__sync_add_and_fetch_2:
279 case Builtin::BI__sync_add_and_fetch_4:
280 case Builtin::BI__sync_add_and_fetch_8:
281 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000282 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000283 case Builtin::BI__sync_sub_and_fetch_1:
284 case Builtin::BI__sync_sub_and_fetch_2:
285 case Builtin::BI__sync_sub_and_fetch_4:
286 case Builtin::BI__sync_sub_and_fetch_8:
287 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000288 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000289 case Builtin::BI__sync_and_and_fetch_1:
290 case Builtin::BI__sync_and_and_fetch_2:
291 case Builtin::BI__sync_and_and_fetch_4:
292 case Builtin::BI__sync_and_and_fetch_8:
293 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000294 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000295 case Builtin::BI__sync_or_and_fetch_1:
296 case Builtin::BI__sync_or_and_fetch_2:
297 case Builtin::BI__sync_or_and_fetch_4:
298 case Builtin::BI__sync_or_and_fetch_8:
299 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000300 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000301 case Builtin::BI__sync_xor_and_fetch_1:
302 case Builtin::BI__sync_xor_and_fetch_2:
303 case Builtin::BI__sync_xor_and_fetch_4:
304 case Builtin::BI__sync_xor_and_fetch_8:
305 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000306 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000307 case Builtin::BI__sync_val_compare_and_swap_1:
308 case Builtin::BI__sync_val_compare_and_swap_2:
309 case Builtin::BI__sync_val_compare_and_swap_4:
310 case Builtin::BI__sync_val_compare_and_swap_8:
311 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000312 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000313 case Builtin::BI__sync_bool_compare_and_swap_1:
314 case Builtin::BI__sync_bool_compare_and_swap_2:
315 case Builtin::BI__sync_bool_compare_and_swap_4:
316 case Builtin::BI__sync_bool_compare_and_swap_8:
317 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000318 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000319 case Builtin::BI__sync_lock_test_and_set_1:
320 case Builtin::BI__sync_lock_test_and_set_2:
321 case Builtin::BI__sync_lock_test_and_set_4:
322 case Builtin::BI__sync_lock_test_and_set_8:
323 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000324 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000325 case Builtin::BI__sync_lock_release_1:
326 case Builtin::BI__sync_lock_release_2:
327 case Builtin::BI__sync_lock_release_4:
328 case Builtin::BI__sync_lock_release_8:
329 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000330 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000331 case Builtin::BI__sync_swap_1:
332 case Builtin::BI__sync_swap_2:
333 case Builtin::BI__sync_swap_4:
334 case Builtin::BI__sync_swap_8:
335 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000336 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000337#define BUILTIN(ID, TYPE, ATTRS)
338#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
339 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000340 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000341#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000342 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000343 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000344 return ExprError();
345 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000346 case Builtin::BI__builtin_addressof:
347 if (SemaBuiltinAddressof(*this, TheCall))
348 return ExprError();
349 break;
Richard Smith760520b2014-06-03 23:27:44 +0000350 case Builtin::BI__builtin_operator_new:
351 case Builtin::BI__builtin_operator_delete:
352 if (!getLangOpts().CPlusPlus) {
353 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
354 << (BuiltinID == Builtin::BI__builtin_operator_new
355 ? "__builtin_operator_new"
356 : "__builtin_operator_delete")
357 << "C++";
358 return ExprError();
359 }
360 // CodeGen assumes it can find the global new and delete to call,
361 // so ensure that they are declared.
362 DeclareGlobalNewDelete();
363 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000364
365 // check secure string manipulation functions where overflows
366 // are detectable at compile time
367 case Builtin::BI__builtin___memcpy_chk:
368 case Builtin::BI__builtin___memccpy_chk:
369 case Builtin::BI__builtin___memmove_chk:
370 case Builtin::BI__builtin___memset_chk:
371 case Builtin::BI__builtin___strlcat_chk:
372 case Builtin::BI__builtin___strlcpy_chk:
373 case Builtin::BI__builtin___strncat_chk:
374 case Builtin::BI__builtin___strncpy_chk:
375 case Builtin::BI__builtin___stpncpy_chk:
376 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
377 break;
378 case Builtin::BI__builtin___snprintf_chk:
379 case Builtin::BI__builtin___vsnprintf_chk:
380 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
381 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000382 }
Richard Smith760520b2014-06-03 23:27:44 +0000383
Nate Begeman4904e322010-06-08 02:47:44 +0000384 // Since the target specific builtins for each arch overlap, only check those
385 // of the arch we are compiling for.
386 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000387 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000388 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000389 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000390 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000391 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000392 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
393 return ExprError();
394 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000395 case llvm::Triple::aarch64:
396 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000397 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000398 return ExprError();
399 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000400 case llvm::Triple::mips:
401 case llvm::Triple::mipsel:
402 case llvm::Triple::mips64:
403 case llvm::Triple::mips64el:
404 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
405 return ExprError();
406 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000407 case llvm::Triple::x86:
408 case llvm::Triple::x86_64:
409 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
410 return ExprError();
411 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000412 default:
413 break;
414 }
415 }
416
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000417 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000418}
419
Nate Begeman91e1fea2010-06-14 05:21:25 +0000420// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000421static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000422 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000423 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000424 switch (Type.getEltType()) {
425 case NeonTypeFlags::Int8:
426 case NeonTypeFlags::Poly8:
427 return shift ? 7 : (8 << IsQuad) - 1;
428 case NeonTypeFlags::Int16:
429 case NeonTypeFlags::Poly16:
430 return shift ? 15 : (4 << IsQuad) - 1;
431 case NeonTypeFlags::Int32:
432 return shift ? 31 : (2 << IsQuad) - 1;
433 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000434 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000435 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000436 case NeonTypeFlags::Poly128:
437 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000438 case NeonTypeFlags::Float16:
439 assert(!shift && "cannot shift float types!");
440 return (4 << IsQuad) - 1;
441 case NeonTypeFlags::Float32:
442 assert(!shift && "cannot shift float types!");
443 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000444 case NeonTypeFlags::Float64:
445 assert(!shift && "cannot shift float types!");
446 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000447 }
David Blaikie8a40f702012-01-17 06:56:22 +0000448 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000449}
450
Bob Wilsone4d77232011-11-08 05:04:11 +0000451/// getNeonEltType - Return the QualType corresponding to the elements of
452/// the vector type specified by the NeonTypeFlags. This is used to check
453/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000454static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000455 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000456 switch (Flags.getEltType()) {
457 case NeonTypeFlags::Int8:
458 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
459 case NeonTypeFlags::Int16:
460 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
461 case NeonTypeFlags::Int32:
462 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
463 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000464 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000465 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
466 else
467 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
468 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000469 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000470 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000471 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000472 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000473 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000474 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000475 case NeonTypeFlags::Poly128:
476 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000477 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000478 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000479 case NeonTypeFlags::Float32:
480 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000481 case NeonTypeFlags::Float64:
482 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000483 }
David Blaikie8a40f702012-01-17 06:56:22 +0000484 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000485}
486
Tim Northover12670412014-02-19 10:37:05 +0000487bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000488 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000489 uint64_t mask = 0;
490 unsigned TV = 0;
491 int PtrArgNum = -1;
492 bool HasConstPtr = false;
493 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000494#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000495#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000496#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000497 }
498
499 // For NEON intrinsics which are overloaded on vector element type, validate
500 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000501 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000502 if (mask) {
503 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
504 return true;
505
506 TV = Result.getLimitedValue(64);
507 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
508 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000509 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000510 }
511
512 if (PtrArgNum >= 0) {
513 // Check that pointer arguments have the specified type.
514 Expr *Arg = TheCall->getArg(PtrArgNum);
515 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
516 Arg = ICE->getSubExpr();
517 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
518 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000519
Tim Northovera2ee4332014-03-29 15:09:45 +0000520 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000521 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000522 bool IsInt64Long =
523 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
524 QualType EltTy =
525 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000526 if (HasConstPtr)
527 EltTy = EltTy.withConst();
528 QualType LHSTy = Context.getPointerType(EltTy);
529 AssignConvertType ConvTy;
530 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
531 if (RHS.isInvalid())
532 return true;
533 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
534 RHS.get(), AA_Assigning))
535 return true;
536 }
537
538 // For NEON intrinsics which take an immediate value as part of the
539 // instruction, range check them here.
540 unsigned i = 0, l = 0, u = 0;
541 switch (BuiltinID) {
542 default:
543 return false;
Tim Northover12670412014-02-19 10:37:05 +0000544#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000545#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000546#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000547 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000548
Richard Sandiford28940af2014-04-16 08:47:51 +0000549 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000550}
551
Tim Northovera2ee4332014-03-29 15:09:45 +0000552bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
553 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000554 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000555 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000556 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000557 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000558 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000559 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
560 BuiltinID == AArch64::BI__builtin_arm_strex ||
561 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000562 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000563 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000564 BuiltinID == ARM::BI__builtin_arm_ldaex ||
565 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
566 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000567
568 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
569
570 // Ensure that we have the proper number of arguments.
571 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
572 return true;
573
574 // Inspect the pointer argument of the atomic builtin. This should always be
575 // a pointer type, whose element is an integral scalar or pointer type.
576 // Because it is a pointer type, we don't have to worry about any implicit
577 // casts here.
578 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
579 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
580 if (PointerArgRes.isInvalid())
581 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000582 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000583
584 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
585 if (!pointerType) {
586 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
587 << PointerArg->getType() << PointerArg->getSourceRange();
588 return true;
589 }
590
591 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
592 // task is to insert the appropriate casts into the AST. First work out just
593 // what the appropriate type is.
594 QualType ValType = pointerType->getPointeeType();
595 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
596 if (IsLdrex)
597 AddrType.addConst();
598
599 // Issue a warning if the cast is dodgy.
600 CastKind CastNeeded = CK_NoOp;
601 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
602 CastNeeded = CK_BitCast;
603 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
604 << PointerArg->getType()
605 << Context.getPointerType(AddrType)
606 << AA_Passing << PointerArg->getSourceRange();
607 }
608
609 // Finally, do the cast and replace the argument with the corrected version.
610 AddrType = Context.getPointerType(AddrType);
611 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
612 if (PointerArgRes.isInvalid())
613 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000614 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000615
616 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
617
618 // In general, we allow ints, floats and pointers to be loaded and stored.
619 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
620 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
621 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
622 << PointerArg->getType() << PointerArg->getSourceRange();
623 return true;
624 }
625
626 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000627 if (Context.getTypeSize(ValType) > MaxWidth) {
628 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000629 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
630 << PointerArg->getType() << PointerArg->getSourceRange();
631 return true;
632 }
633
634 switch (ValType.getObjCLifetime()) {
635 case Qualifiers::OCL_None:
636 case Qualifiers::OCL_ExplicitNone:
637 // okay
638 break;
639
640 case Qualifiers::OCL_Weak:
641 case Qualifiers::OCL_Strong:
642 case Qualifiers::OCL_Autoreleasing:
643 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
644 << ValType << PointerArg->getSourceRange();
645 return true;
646 }
647
648
649 if (IsLdrex) {
650 TheCall->setType(ValType);
651 return false;
652 }
653
654 // Initialize the argument to be stored.
655 ExprResult ValArg = TheCall->getArg(0);
656 InitializedEntity Entity = InitializedEntity::InitializeParameter(
657 Context, ValType, /*consume*/ false);
658 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
659 if (ValArg.isInvalid())
660 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000661 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000662
663 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
664 // but the custom checker bypasses all default analysis.
665 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000666 return false;
667}
668
Nate Begeman4904e322010-06-08 02:47:44 +0000669bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000670 llvm::APSInt Result;
671
Tim Northover6aacd492013-07-16 09:47:53 +0000672 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000673 BuiltinID == ARM::BI__builtin_arm_ldaex ||
674 BuiltinID == ARM::BI__builtin_arm_strex ||
675 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000676 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000677 }
678
Yi Kong26d104a2014-08-13 19:18:14 +0000679 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
680 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
681 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
682 }
683
Tim Northover12670412014-02-19 10:37:05 +0000684 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
685 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000686
Yi Kong4efadfb2014-07-03 16:01:25 +0000687 // For intrinsics which take an immediate value as part of the instruction,
688 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000689 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000690 switch (BuiltinID) {
691 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000692 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
693 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000694 case ARM::BI__builtin_arm_vcvtr_f:
695 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000696 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000697 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000698 case ARM::BI__builtin_arm_isb:
699 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000700 }
Nate Begemand773fe62010-06-13 04:47:52 +0000701
Nate Begemanf568b072010-08-03 21:32:34 +0000702 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000703 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000704}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000705
Tim Northover573cbee2014-05-24 12:52:07 +0000706bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000707 CallExpr *TheCall) {
708 llvm::APSInt Result;
709
Tim Northover573cbee2014-05-24 12:52:07 +0000710 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000711 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
712 BuiltinID == AArch64::BI__builtin_arm_strex ||
713 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000714 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
715 }
716
Yi Konga5548432014-08-13 19:18:20 +0000717 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
718 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
719 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
720 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
721 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
722 }
723
Tim Northovera2ee4332014-03-29 15:09:45 +0000724 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
725 return true;
726
Yi Kong19a29ac2014-07-17 10:52:06 +0000727 // For intrinsics which take an immediate value as part of the instruction,
728 // range check them here.
729 unsigned i = 0, l = 0, u = 0;
730 switch (BuiltinID) {
731 default: return false;
732 case AArch64::BI__builtin_arm_dmb:
733 case AArch64::BI__builtin_arm_dsb:
734 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
735 }
736
Yi Kong19a29ac2014-07-17 10:52:06 +0000737 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000738}
739
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000740bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
741 unsigned i = 0, l = 0, u = 0;
742 switch (BuiltinID) {
743 default: return false;
744 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
745 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000746 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
747 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
748 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
749 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
750 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000751 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000752
Richard Sandiford28940af2014-04-16 08:47:51 +0000753 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000754}
755
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000756bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
757 switch (BuiltinID) {
758 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000759 // This is declared to take (const char*, int)
760 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000761 }
762 return false;
763}
764
Richard Smith55ce3522012-06-25 20:30:08 +0000765/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
766/// parameter with the FormatAttr's correct format_idx and firstDataArg.
767/// Returns true when the format fits the function and the FormatStringInfo has
768/// been populated.
769bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
770 FormatStringInfo *FSI) {
771 FSI->HasVAListArg = Format->getFirstArg() == 0;
772 FSI->FormatIdx = Format->getFormatIdx() - 1;
773 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000774
Richard Smith55ce3522012-06-25 20:30:08 +0000775 // The way the format attribute works in GCC, the implicit this argument
776 // of member functions is counted. However, it doesn't appear in our own
777 // lists, so decrement format_idx in that case.
778 if (IsCXXMember) {
779 if(FSI->FormatIdx == 0)
780 return false;
781 --FSI->FormatIdx;
782 if (FSI->FirstDataArg != 0)
783 --FSI->FirstDataArg;
784 }
785 return true;
786}
Mike Stump11289f42009-09-09 15:08:12 +0000787
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000788/// Checks if a the given expression evaluates to null.
789///
790/// \brief Returns true if the value evaluates to null.
791static bool CheckNonNullExpr(Sema &S,
792 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000793 // As a special case, transparent unions initialized with zero are
794 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000795 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000796 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
797 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000798 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000799 if (const InitListExpr *ILE =
800 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000801 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000802 }
803
804 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000805 return (!Expr->isValueDependent() &&
806 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
807 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000808}
809
810static void CheckNonNullArgument(Sema &S,
811 const Expr *ArgExpr,
812 SourceLocation CallSiteLoc) {
813 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000814 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
815}
816
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000817bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
818 FormatStringInfo FSI;
819 if ((GetFormatStringType(Format) == FST_NSString) &&
820 getFormatStringInfo(Format, false, &FSI)) {
821 Idx = FSI.FormatIdx;
822 return true;
823 }
824 return false;
825}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000826/// \brief Diagnose use of %s directive in an NSString which is being passed
827/// as formatting string to formatting method.
828static void
829DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
830 const NamedDecl *FDecl,
831 Expr **Args,
832 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000833 unsigned Idx = 0;
834 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000835 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
836 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000837 Idx = 2;
838 Format = true;
839 }
840 else
841 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
842 if (S.GetFormatNSStringIdx(I, Idx)) {
843 Format = true;
844 break;
845 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000846 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000847 if (!Format || NumArgs <= Idx)
848 return;
849 const Expr *FormatExpr = Args[Idx];
850 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
851 FormatExpr = CSCE->getSubExpr();
852 const StringLiteral *FormatString;
853 if (const ObjCStringLiteral *OSL =
854 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
855 FormatString = OSL->getString();
856 else
857 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
858 if (!FormatString)
859 return;
860 if (S.FormatStringHasSArg(FormatString)) {
861 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
862 << "%s" << 1 << 1;
863 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
864 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000865 }
866}
867
Ted Kremenek2bc73332014-01-17 06:24:43 +0000868static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000869 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +0000870 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000871 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000872 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +0000873 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000874 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000875 if (!NonNull->args_size()) {
876 // Easy case: all pointer arguments are nonnull.
877 for (const auto *Arg : Args)
878 if (S.isValidNonNullAttrType(Arg->getType()))
879 CheckNonNullArgument(S, Arg, CallSiteLoc);
880 return;
881 }
882
883 for (unsigned Val : NonNull->args()) {
884 if (Val >= Args.size())
885 continue;
886 if (NonNullArgs.empty())
887 NonNullArgs.resize(Args.size());
888 NonNullArgs.set(Val);
889 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000890 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000891
892 // Check the attributes on the parameters.
893 ArrayRef<ParmVarDecl*> parms;
894 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
895 parms = FD->parameters();
896 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
897 parms = MD->parameters();
898
Richard Smith588bd9b2014-08-27 04:59:42 +0000899 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +0000900 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +0000901 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000902 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +0000903 if (PVD->hasAttr<NonNullAttr>() ||
904 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
905 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +0000906 }
Richard Smith588bd9b2014-08-27 04:59:42 +0000907
908 // In case this is a variadic call, check any remaining arguments.
909 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
910 if (NonNullArgs[ArgIndex])
911 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000912}
913
Richard Smith55ce3522012-06-25 20:30:08 +0000914/// Handles the checks for format strings, non-POD arguments to vararg
915/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000916void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
917 unsigned NumParams, bool IsMemberFunction,
918 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000919 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000920 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000921 if (CurContext->isDependentContext())
922 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000923
Ted Kremenekb8176da2010-09-09 04:33:05 +0000924 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000925 llvm::SmallBitVector CheckedVarArgs;
926 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000927 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000928 // Only create vector if there are format attributes.
929 CheckedVarArgs.resize(Args.size());
930
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000931 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000932 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000933 }
Richard Smithd7293d72013-08-05 18:49:43 +0000934 }
Richard Smith55ce3522012-06-25 20:30:08 +0000935
936 // Refuse POD arguments that weren't caught by the format string
937 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000938 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000939 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000940 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000941 if (const Expr *Arg = Args[ArgIdx]) {
942 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
943 checkVariadicArgument(Arg, CallType);
944 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000945 }
Richard Smithd7293d72013-08-05 18:49:43 +0000946 }
Mike Stump11289f42009-09-09 15:08:12 +0000947
Richard Trieu41bc0992013-06-22 00:20:41 +0000948 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000949 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000950
Richard Trieu41bc0992013-06-22 00:20:41 +0000951 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000952 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
953 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000954 }
Richard Smith55ce3522012-06-25 20:30:08 +0000955}
956
957/// CheckConstructorCall - Check a constructor call for correctness and safety
958/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000959void Sema::CheckConstructorCall(FunctionDecl *FDecl,
960 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000961 const FunctionProtoType *Proto,
962 SourceLocation Loc) {
963 VariadicCallType CallType =
964 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000965 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000966 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
967}
968
969/// CheckFunctionCall - Check a direct function call for various correctness
970/// and safety properties not strictly enforced by the C type system.
971bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
972 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000973 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
974 isa<CXXMethodDecl>(FDecl);
975 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
976 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000977 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
978 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000979 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000980 Expr** Args = TheCall->getArgs();
981 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000982 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000983 // If this is a call to a member operator, hide the first argument
984 // from checkCall.
985 // FIXME: Our choice of AST representation here is less than ideal.
986 ++Args;
987 --NumArgs;
988 }
Craig Topper8c2a2a02014-08-30 16:55:39 +0000989 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000990 IsMemberFunction, TheCall->getRParenLoc(),
991 TheCall->getCallee()->getSourceRange(), CallType);
992
993 IdentifierInfo *FnInfo = FDecl->getIdentifier();
994 // None of the checks below are needed for functions that don't have
995 // simple names (e.g., C++ conversion functions).
996 if (!FnInfo)
997 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000998
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000999 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001000 if (getLangOpts().ObjC1)
1001 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001002
Anna Zaks22122702012-01-17 00:37:07 +00001003 unsigned CMId = FDecl->getMemoryFunctionKind();
1004 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001005 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001006
Anna Zaks201d4892012-01-13 21:52:01 +00001007 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001008 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001009 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001010 else if (CMId == Builtin::BIstrncat)
1011 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001012 else
Anna Zaks22122702012-01-17 00:37:07 +00001013 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001014
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001015 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001016}
1017
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001018bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001019 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001020 VariadicCallType CallType =
1021 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001022
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001023 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001024 /*IsMemberFunction=*/false,
1025 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001026
1027 return false;
1028}
1029
Richard Trieu664c4c62013-06-20 21:03:13 +00001030bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1031 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001032 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1033 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001034 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001035
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001036 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001037 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001038 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001039
Richard Trieu664c4c62013-06-20 21:03:13 +00001040 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001041 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001042 CallType = VariadicDoesNotApply;
1043 } else if (Ty->isBlockPointerType()) {
1044 CallType = VariadicBlock;
1045 } else { // Ty->isFunctionPointerType()
1046 CallType = VariadicFunction;
1047 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001048 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001049
Craig Topper8c2a2a02014-08-30 16:55:39 +00001050 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1051 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001052 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001053 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001054
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001055 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001056}
1057
Richard Trieu41bc0992013-06-22 00:20:41 +00001058/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1059/// such as function pointers returned from functions.
1060bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001061 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001062 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001063 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001064
Craig Topperc3ec1492014-05-26 06:22:03 +00001065 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001066 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001067 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001068 TheCall->getCallee()->getSourceRange(), CallType);
1069
1070 return false;
1071}
1072
Tim Northovere94a34c2014-03-11 10:49:14 +00001073static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1074 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1075 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1076 return false;
1077
1078 switch (Op) {
1079 case AtomicExpr::AO__c11_atomic_init:
1080 llvm_unreachable("There is no ordering argument for an init");
1081
1082 case AtomicExpr::AO__c11_atomic_load:
1083 case AtomicExpr::AO__atomic_load_n:
1084 case AtomicExpr::AO__atomic_load:
1085 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1086 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1087
1088 case AtomicExpr::AO__c11_atomic_store:
1089 case AtomicExpr::AO__atomic_store:
1090 case AtomicExpr::AO__atomic_store_n:
1091 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1092 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1093 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1094
1095 default:
1096 return true;
1097 }
1098}
1099
Richard Smithfeea8832012-04-12 05:08:17 +00001100ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1101 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001102 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1103 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001104
Richard Smithfeea8832012-04-12 05:08:17 +00001105 // All these operations take one of the following forms:
1106 enum {
1107 // C __c11_atomic_init(A *, C)
1108 Init,
1109 // C __c11_atomic_load(A *, int)
1110 Load,
1111 // void __atomic_load(A *, CP, int)
1112 Copy,
1113 // C __c11_atomic_add(A *, M, int)
1114 Arithmetic,
1115 // C __atomic_exchange_n(A *, CP, int)
1116 Xchg,
1117 // void __atomic_exchange(A *, C *, CP, int)
1118 GNUXchg,
1119 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1120 C11CmpXchg,
1121 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1122 GNUCmpXchg
1123 } Form = Init;
1124 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1125 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1126 // where:
1127 // C is an appropriate type,
1128 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1129 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1130 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1131 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001132
Richard Smithfeea8832012-04-12 05:08:17 +00001133 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1134 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1135 && "need to update code for modified C11 atomics");
1136 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1137 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1138 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1139 Op == AtomicExpr::AO__atomic_store_n ||
1140 Op == AtomicExpr::AO__atomic_exchange_n ||
1141 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1142 bool IsAddSub = false;
1143
1144 switch (Op) {
1145 case AtomicExpr::AO__c11_atomic_init:
1146 Form = Init;
1147 break;
1148
1149 case AtomicExpr::AO__c11_atomic_load:
1150 case AtomicExpr::AO__atomic_load_n:
1151 Form = Load;
1152 break;
1153
1154 case AtomicExpr::AO__c11_atomic_store:
1155 case AtomicExpr::AO__atomic_load:
1156 case AtomicExpr::AO__atomic_store:
1157 case AtomicExpr::AO__atomic_store_n:
1158 Form = Copy;
1159 break;
1160
1161 case AtomicExpr::AO__c11_atomic_fetch_add:
1162 case AtomicExpr::AO__c11_atomic_fetch_sub:
1163 case AtomicExpr::AO__atomic_fetch_add:
1164 case AtomicExpr::AO__atomic_fetch_sub:
1165 case AtomicExpr::AO__atomic_add_fetch:
1166 case AtomicExpr::AO__atomic_sub_fetch:
1167 IsAddSub = true;
1168 // Fall through.
1169 case AtomicExpr::AO__c11_atomic_fetch_and:
1170 case AtomicExpr::AO__c11_atomic_fetch_or:
1171 case AtomicExpr::AO__c11_atomic_fetch_xor:
1172 case AtomicExpr::AO__atomic_fetch_and:
1173 case AtomicExpr::AO__atomic_fetch_or:
1174 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001175 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001176 case AtomicExpr::AO__atomic_and_fetch:
1177 case AtomicExpr::AO__atomic_or_fetch:
1178 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001179 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001180 Form = Arithmetic;
1181 break;
1182
1183 case AtomicExpr::AO__c11_atomic_exchange:
1184 case AtomicExpr::AO__atomic_exchange_n:
1185 Form = Xchg;
1186 break;
1187
1188 case AtomicExpr::AO__atomic_exchange:
1189 Form = GNUXchg;
1190 break;
1191
1192 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1193 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1194 Form = C11CmpXchg;
1195 break;
1196
1197 case AtomicExpr::AO__atomic_compare_exchange:
1198 case AtomicExpr::AO__atomic_compare_exchange_n:
1199 Form = GNUCmpXchg;
1200 break;
1201 }
1202
1203 // Check we have the right number of arguments.
1204 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001205 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001206 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001207 << TheCall->getCallee()->getSourceRange();
1208 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001209 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1210 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001211 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001212 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001213 << TheCall->getCallee()->getSourceRange();
1214 return ExprError();
1215 }
1216
Richard Smithfeea8832012-04-12 05:08:17 +00001217 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001218 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001219 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1220 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1221 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001222 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001223 << Ptr->getType() << Ptr->getSourceRange();
1224 return ExprError();
1225 }
1226
Richard Smithfeea8832012-04-12 05:08:17 +00001227 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1228 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1229 QualType ValType = AtomTy; // 'C'
1230 if (IsC11) {
1231 if (!AtomTy->isAtomicType()) {
1232 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1233 << Ptr->getType() << Ptr->getSourceRange();
1234 return ExprError();
1235 }
Richard Smithe00921a2012-09-15 06:09:58 +00001236 if (AtomTy.isConstQualified()) {
1237 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1238 << Ptr->getType() << Ptr->getSourceRange();
1239 return ExprError();
1240 }
Richard Smithfeea8832012-04-12 05:08:17 +00001241 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001242 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001243
Richard Smithfeea8832012-04-12 05:08:17 +00001244 // For an arithmetic operation, the implied arithmetic must be well-formed.
1245 if (Form == Arithmetic) {
1246 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1247 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1248 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1249 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1250 return ExprError();
1251 }
1252 if (!IsAddSub && !ValType->isIntegerType()) {
1253 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1254 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1255 return ExprError();
1256 }
1257 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1258 // For __atomic_*_n operations, the value type must be a scalar integral or
1259 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001260 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001261 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1262 return ExprError();
1263 }
1264
Eli Friedmanaa769812013-09-11 03:49:34 +00001265 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1266 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001267 // For GNU atomics, require a trivially-copyable type. This is not part of
1268 // the GNU atomics specification, but we enforce it for sanity.
1269 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001270 << Ptr->getType() << Ptr->getSourceRange();
1271 return ExprError();
1272 }
1273
Richard Smithfeea8832012-04-12 05:08:17 +00001274 // FIXME: For any builtin other than a load, the ValType must not be
1275 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001276
1277 switch (ValType.getObjCLifetime()) {
1278 case Qualifiers::OCL_None:
1279 case Qualifiers::OCL_ExplicitNone:
1280 // okay
1281 break;
1282
1283 case Qualifiers::OCL_Weak:
1284 case Qualifiers::OCL_Strong:
1285 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001286 // FIXME: Can this happen? By this point, ValType should be known
1287 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001288 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1289 << ValType << Ptr->getSourceRange();
1290 return ExprError();
1291 }
1292
1293 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001294 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001295 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001296 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001297 ResultType = Context.BoolTy;
1298
Richard Smithfeea8832012-04-12 05:08:17 +00001299 // The type of a parameter passed 'by value'. In the GNU atomics, such
1300 // arguments are actually passed as pointers.
1301 QualType ByValType = ValType; // 'CP'
1302 if (!IsC11 && !IsN)
1303 ByValType = Ptr->getType();
1304
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001305 // The first argument --- the pointer --- has a fixed type; we
1306 // deduce the types of the rest of the arguments accordingly. Walk
1307 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001308 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001309 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001310 if (i < NumVals[Form] + 1) {
1311 switch (i) {
1312 case 1:
1313 // The second argument is the non-atomic operand. For arithmetic, this
1314 // is always passed by value, and for a compare_exchange it is always
1315 // passed by address. For the rest, GNU uses by-address and C11 uses
1316 // by-value.
1317 assert(Form != Load);
1318 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1319 Ty = ValType;
1320 else if (Form == Copy || Form == Xchg)
1321 Ty = ByValType;
1322 else if (Form == Arithmetic)
1323 Ty = Context.getPointerDiffType();
1324 else
1325 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1326 break;
1327 case 2:
1328 // The third argument to compare_exchange / GNU exchange is a
1329 // (pointer to a) desired value.
1330 Ty = ByValType;
1331 break;
1332 case 3:
1333 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1334 Ty = Context.BoolTy;
1335 break;
1336 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001337 } else {
1338 // The order(s) are always converted to int.
1339 Ty = Context.IntTy;
1340 }
Richard Smithfeea8832012-04-12 05:08:17 +00001341
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001342 InitializedEntity Entity =
1343 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001344 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001345 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1346 if (Arg.isInvalid())
1347 return true;
1348 TheCall->setArg(i, Arg.get());
1349 }
1350
Richard Smithfeea8832012-04-12 05:08:17 +00001351 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001352 SmallVector<Expr*, 5> SubExprs;
1353 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001354 switch (Form) {
1355 case Init:
1356 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001357 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001358 break;
1359 case Load:
1360 SubExprs.push_back(TheCall->getArg(1)); // Order
1361 break;
1362 case Copy:
1363 case Arithmetic:
1364 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001365 SubExprs.push_back(TheCall->getArg(2)); // Order
1366 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001367 break;
1368 case GNUXchg:
1369 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1370 SubExprs.push_back(TheCall->getArg(3)); // Order
1371 SubExprs.push_back(TheCall->getArg(1)); // Val1
1372 SubExprs.push_back(TheCall->getArg(2)); // Val2
1373 break;
1374 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001375 SubExprs.push_back(TheCall->getArg(3)); // Order
1376 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001377 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001378 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001379 break;
1380 case GNUCmpXchg:
1381 SubExprs.push_back(TheCall->getArg(4)); // Order
1382 SubExprs.push_back(TheCall->getArg(1)); // Val1
1383 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1384 SubExprs.push_back(TheCall->getArg(2)); // Val2
1385 SubExprs.push_back(TheCall->getArg(3)); // Weak
1386 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001387 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001388
1389 if (SubExprs.size() >= 2 && Form != Init) {
1390 llvm::APSInt Result(32);
1391 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1392 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001393 Diag(SubExprs[1]->getLocStart(),
1394 diag::warn_atomic_op_has_invalid_memory_order)
1395 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001396 }
1397
Fariborz Jahanian615de762013-05-28 17:37:39 +00001398 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1399 SubExprs, ResultType, Op,
1400 TheCall->getRParenLoc());
1401
1402 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1403 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1404 Context.AtomicUsesUnsupportedLibcall(AE))
1405 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1406 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001407
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001408 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001409}
1410
1411
John McCall29ad95b2011-08-27 01:09:30 +00001412/// checkBuiltinArgument - Given a call to a builtin function, perform
1413/// normal type-checking on the given argument, updating the call in
1414/// place. This is useful when a builtin function requires custom
1415/// type-checking for some of its arguments but not necessarily all of
1416/// them.
1417///
1418/// Returns true on error.
1419static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1420 FunctionDecl *Fn = E->getDirectCallee();
1421 assert(Fn && "builtin call without direct callee!");
1422
1423 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1424 InitializedEntity Entity =
1425 InitializedEntity::InitializeParameter(S.Context, Param);
1426
1427 ExprResult Arg = E->getArg(0);
1428 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1429 if (Arg.isInvalid())
1430 return true;
1431
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001432 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001433 return false;
1434}
1435
Chris Lattnerdc046542009-05-08 06:58:22 +00001436/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1437/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1438/// type of its first argument. The main ActOnCallExpr routines have already
1439/// promoted the types of arguments because all of these calls are prototyped as
1440/// void(...).
1441///
1442/// This function goes through and does final semantic checking for these
1443/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001444ExprResult
1445Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001446 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001447 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1448 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1449
1450 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001451 if (TheCall->getNumArgs() < 1) {
1452 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1453 << 0 << 1 << TheCall->getNumArgs()
1454 << TheCall->getCallee()->getSourceRange();
1455 return ExprError();
1456 }
Mike Stump11289f42009-09-09 15:08:12 +00001457
Chris Lattnerdc046542009-05-08 06:58:22 +00001458 // Inspect the first argument of the atomic builtin. This should always be
1459 // a pointer type, whose element is an integral scalar or pointer type.
1460 // Because it is a pointer type, we don't have to worry about any implicit
1461 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001462 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001463 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001464 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1465 if (FirstArgResult.isInvalid())
1466 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001467 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001468 TheCall->setArg(0, FirstArg);
1469
John McCall31168b02011-06-15 23:02:42 +00001470 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1471 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001472 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1473 << FirstArg->getType() << FirstArg->getSourceRange();
1474 return ExprError();
1475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
John McCall31168b02011-06-15 23:02:42 +00001477 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001478 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001479 !ValType->isBlockPointerType()) {
1480 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1481 << FirstArg->getType() << FirstArg->getSourceRange();
1482 return ExprError();
1483 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001484
John McCall31168b02011-06-15 23:02:42 +00001485 switch (ValType.getObjCLifetime()) {
1486 case Qualifiers::OCL_None:
1487 case Qualifiers::OCL_ExplicitNone:
1488 // okay
1489 break;
1490
1491 case Qualifiers::OCL_Weak:
1492 case Qualifiers::OCL_Strong:
1493 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001494 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001495 << ValType << FirstArg->getSourceRange();
1496 return ExprError();
1497 }
1498
John McCallb50451a2011-10-05 07:41:44 +00001499 // Strip any qualifiers off ValType.
1500 ValType = ValType.getUnqualifiedType();
1501
Chandler Carruth3973af72010-07-18 20:54:12 +00001502 // The majority of builtins return a value, but a few have special return
1503 // types, so allow them to override appropriately below.
1504 QualType ResultType = ValType;
1505
Chris Lattnerdc046542009-05-08 06:58:22 +00001506 // We need to figure out which concrete builtin this maps onto. For example,
1507 // __sync_fetch_and_add with a 2 byte object turns into
1508 // __sync_fetch_and_add_2.
1509#define BUILTIN_ROW(x) \
1510 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1511 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001512
Chris Lattnerdc046542009-05-08 06:58:22 +00001513 static const unsigned BuiltinIndices[][5] = {
1514 BUILTIN_ROW(__sync_fetch_and_add),
1515 BUILTIN_ROW(__sync_fetch_and_sub),
1516 BUILTIN_ROW(__sync_fetch_and_or),
1517 BUILTIN_ROW(__sync_fetch_and_and),
1518 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001519
Chris Lattnerdc046542009-05-08 06:58:22 +00001520 BUILTIN_ROW(__sync_add_and_fetch),
1521 BUILTIN_ROW(__sync_sub_and_fetch),
1522 BUILTIN_ROW(__sync_and_and_fetch),
1523 BUILTIN_ROW(__sync_or_and_fetch),
1524 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001525
Chris Lattnerdc046542009-05-08 06:58:22 +00001526 BUILTIN_ROW(__sync_val_compare_and_swap),
1527 BUILTIN_ROW(__sync_bool_compare_and_swap),
1528 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001529 BUILTIN_ROW(__sync_lock_release),
1530 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001531 };
Mike Stump11289f42009-09-09 15:08:12 +00001532#undef BUILTIN_ROW
1533
Chris Lattnerdc046542009-05-08 06:58:22 +00001534 // Determine the index of the size.
1535 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001536 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001537 case 1: SizeIndex = 0; break;
1538 case 2: SizeIndex = 1; break;
1539 case 4: SizeIndex = 2; break;
1540 case 8: SizeIndex = 3; break;
1541 case 16: SizeIndex = 4; break;
1542 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001543 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1544 << FirstArg->getType() << FirstArg->getSourceRange();
1545 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001546 }
Mike Stump11289f42009-09-09 15:08:12 +00001547
Chris Lattnerdc046542009-05-08 06:58:22 +00001548 // Each of these builtins has one pointer argument, followed by some number of
1549 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1550 // that we ignore. Find out which row of BuiltinIndices to read from as well
1551 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001552 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001553 unsigned BuiltinIndex, NumFixed = 1;
1554 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001555 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001556 case Builtin::BI__sync_fetch_and_add:
1557 case Builtin::BI__sync_fetch_and_add_1:
1558 case Builtin::BI__sync_fetch_and_add_2:
1559 case Builtin::BI__sync_fetch_and_add_4:
1560 case Builtin::BI__sync_fetch_and_add_8:
1561 case Builtin::BI__sync_fetch_and_add_16:
1562 BuiltinIndex = 0;
1563 break;
1564
1565 case Builtin::BI__sync_fetch_and_sub:
1566 case Builtin::BI__sync_fetch_and_sub_1:
1567 case Builtin::BI__sync_fetch_and_sub_2:
1568 case Builtin::BI__sync_fetch_and_sub_4:
1569 case Builtin::BI__sync_fetch_and_sub_8:
1570 case Builtin::BI__sync_fetch_and_sub_16:
1571 BuiltinIndex = 1;
1572 break;
1573
1574 case Builtin::BI__sync_fetch_and_or:
1575 case Builtin::BI__sync_fetch_and_or_1:
1576 case Builtin::BI__sync_fetch_and_or_2:
1577 case Builtin::BI__sync_fetch_and_or_4:
1578 case Builtin::BI__sync_fetch_and_or_8:
1579 case Builtin::BI__sync_fetch_and_or_16:
1580 BuiltinIndex = 2;
1581 break;
1582
1583 case Builtin::BI__sync_fetch_and_and:
1584 case Builtin::BI__sync_fetch_and_and_1:
1585 case Builtin::BI__sync_fetch_and_and_2:
1586 case Builtin::BI__sync_fetch_and_and_4:
1587 case Builtin::BI__sync_fetch_and_and_8:
1588 case Builtin::BI__sync_fetch_and_and_16:
1589 BuiltinIndex = 3;
1590 break;
Mike Stump11289f42009-09-09 15:08:12 +00001591
Douglas Gregor73722482011-11-28 16:30:08 +00001592 case Builtin::BI__sync_fetch_and_xor:
1593 case Builtin::BI__sync_fetch_and_xor_1:
1594 case Builtin::BI__sync_fetch_and_xor_2:
1595 case Builtin::BI__sync_fetch_and_xor_4:
1596 case Builtin::BI__sync_fetch_and_xor_8:
1597 case Builtin::BI__sync_fetch_and_xor_16:
1598 BuiltinIndex = 4;
1599 break;
1600
1601 case Builtin::BI__sync_add_and_fetch:
1602 case Builtin::BI__sync_add_and_fetch_1:
1603 case Builtin::BI__sync_add_and_fetch_2:
1604 case Builtin::BI__sync_add_and_fetch_4:
1605 case Builtin::BI__sync_add_and_fetch_8:
1606 case Builtin::BI__sync_add_and_fetch_16:
1607 BuiltinIndex = 5;
1608 break;
1609
1610 case Builtin::BI__sync_sub_and_fetch:
1611 case Builtin::BI__sync_sub_and_fetch_1:
1612 case Builtin::BI__sync_sub_and_fetch_2:
1613 case Builtin::BI__sync_sub_and_fetch_4:
1614 case Builtin::BI__sync_sub_and_fetch_8:
1615 case Builtin::BI__sync_sub_and_fetch_16:
1616 BuiltinIndex = 6;
1617 break;
1618
1619 case Builtin::BI__sync_and_and_fetch:
1620 case Builtin::BI__sync_and_and_fetch_1:
1621 case Builtin::BI__sync_and_and_fetch_2:
1622 case Builtin::BI__sync_and_and_fetch_4:
1623 case Builtin::BI__sync_and_and_fetch_8:
1624 case Builtin::BI__sync_and_and_fetch_16:
1625 BuiltinIndex = 7;
1626 break;
1627
1628 case Builtin::BI__sync_or_and_fetch:
1629 case Builtin::BI__sync_or_and_fetch_1:
1630 case Builtin::BI__sync_or_and_fetch_2:
1631 case Builtin::BI__sync_or_and_fetch_4:
1632 case Builtin::BI__sync_or_and_fetch_8:
1633 case Builtin::BI__sync_or_and_fetch_16:
1634 BuiltinIndex = 8;
1635 break;
1636
1637 case Builtin::BI__sync_xor_and_fetch:
1638 case Builtin::BI__sync_xor_and_fetch_1:
1639 case Builtin::BI__sync_xor_and_fetch_2:
1640 case Builtin::BI__sync_xor_and_fetch_4:
1641 case Builtin::BI__sync_xor_and_fetch_8:
1642 case Builtin::BI__sync_xor_and_fetch_16:
1643 BuiltinIndex = 9;
1644 break;
Mike Stump11289f42009-09-09 15:08:12 +00001645
Chris Lattnerdc046542009-05-08 06:58:22 +00001646 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001647 case Builtin::BI__sync_val_compare_and_swap_1:
1648 case Builtin::BI__sync_val_compare_and_swap_2:
1649 case Builtin::BI__sync_val_compare_and_swap_4:
1650 case Builtin::BI__sync_val_compare_and_swap_8:
1651 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001652 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001653 NumFixed = 2;
1654 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001655
Chris Lattnerdc046542009-05-08 06:58:22 +00001656 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001657 case Builtin::BI__sync_bool_compare_and_swap_1:
1658 case Builtin::BI__sync_bool_compare_and_swap_2:
1659 case Builtin::BI__sync_bool_compare_and_swap_4:
1660 case Builtin::BI__sync_bool_compare_and_swap_8:
1661 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001662 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001663 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001664 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001665 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001666
1667 case Builtin::BI__sync_lock_test_and_set:
1668 case Builtin::BI__sync_lock_test_and_set_1:
1669 case Builtin::BI__sync_lock_test_and_set_2:
1670 case Builtin::BI__sync_lock_test_and_set_4:
1671 case Builtin::BI__sync_lock_test_and_set_8:
1672 case Builtin::BI__sync_lock_test_and_set_16:
1673 BuiltinIndex = 12;
1674 break;
1675
Chris Lattnerdc046542009-05-08 06:58:22 +00001676 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001677 case Builtin::BI__sync_lock_release_1:
1678 case Builtin::BI__sync_lock_release_2:
1679 case Builtin::BI__sync_lock_release_4:
1680 case Builtin::BI__sync_lock_release_8:
1681 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001682 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001683 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001684 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001685 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001686
1687 case Builtin::BI__sync_swap:
1688 case Builtin::BI__sync_swap_1:
1689 case Builtin::BI__sync_swap_2:
1690 case Builtin::BI__sync_swap_4:
1691 case Builtin::BI__sync_swap_8:
1692 case Builtin::BI__sync_swap_16:
1693 BuiltinIndex = 14;
1694 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001695 }
Mike Stump11289f42009-09-09 15:08:12 +00001696
Chris Lattnerdc046542009-05-08 06:58:22 +00001697 // Now that we know how many fixed arguments we expect, first check that we
1698 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001699 if (TheCall->getNumArgs() < 1+NumFixed) {
1700 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1701 << 0 << 1+NumFixed << TheCall->getNumArgs()
1702 << TheCall->getCallee()->getSourceRange();
1703 return ExprError();
1704 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
Chris Lattner5b9241b2009-05-08 15:36:58 +00001706 // Get the decl for the concrete builtin from this, we can tell what the
1707 // concrete integer type we should convert to is.
1708 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1709 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001710 FunctionDecl *NewBuiltinDecl;
1711 if (NewBuiltinID == BuiltinID)
1712 NewBuiltinDecl = FDecl;
1713 else {
1714 // Perform builtin lookup to avoid redeclaring it.
1715 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1716 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1717 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1718 assert(Res.getFoundDecl());
1719 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001720 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001721 return ExprError();
1722 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001723
John McCallcf142162010-08-07 06:22:56 +00001724 // The first argument --- the pointer --- has a fixed type; we
1725 // deduce the types of the rest of the arguments accordingly. Walk
1726 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001727 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001728 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001729
Chris Lattnerdc046542009-05-08 06:58:22 +00001730 // GCC does an implicit conversion to the pointer or integer ValType. This
1731 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001732 // Initialize the argument.
1733 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1734 ValType, /*consume*/ false);
1735 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001736 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001737 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001738
Chris Lattnerdc046542009-05-08 06:58:22 +00001739 // Okay, we have something that *can* be converted to the right type. Check
1740 // to see if there is a potentially weird extension going on here. This can
1741 // happen when you do an atomic operation on something like an char* and
1742 // pass in 42. The 42 gets converted to char. This is even more strange
1743 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001744 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001745 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001746 }
Mike Stump11289f42009-09-09 15:08:12 +00001747
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001748 ASTContext& Context = this->getASTContext();
1749
1750 // Create a new DeclRefExpr to refer to the new decl.
1751 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1752 Context,
1753 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001754 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001755 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001756 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001757 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001758 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001759 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001760
Chris Lattnerdc046542009-05-08 06:58:22 +00001761 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001762 // FIXME: This loses syntactic information.
1763 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1764 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1765 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001766 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001767
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001768 // Change the result type of the call to match the original value type. This
1769 // is arbitrary, but the codegen for these builtins ins design to handle it
1770 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001771 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001772
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001773 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001774}
1775
Chris Lattner6436fb62009-02-18 06:01:06 +00001776/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001777/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001778/// Note: It might also make sense to do the UTF-16 conversion here (would
1779/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001780bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001781 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001782 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1783
Douglas Gregorfb65e592011-07-27 05:40:30 +00001784 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001785 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1786 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001787 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001788 }
Mike Stump11289f42009-09-09 15:08:12 +00001789
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001790 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001791 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001792 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001793 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001794 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001795 UTF16 *ToPtr = &ToBuf[0];
1796
1797 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1798 &ToPtr, ToPtr + NumBytes,
1799 strictConversion);
1800 // Check for conversion failure.
1801 if (Result != conversionOK)
1802 Diag(Arg->getLocStart(),
1803 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1804 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001805 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001806}
1807
Chris Lattnere202e6a2007-12-20 00:05:45 +00001808/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1809/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001810bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1811 Expr *Fn = TheCall->getCallee();
1812 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001813 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001814 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001815 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1816 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001817 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001818 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001819 return true;
1820 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001821
1822 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001823 return Diag(TheCall->getLocEnd(),
1824 diag::err_typecheck_call_too_few_args_at_least)
1825 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001826 }
1827
John McCall29ad95b2011-08-27 01:09:30 +00001828 // Type-check the first argument normally.
1829 if (checkBuiltinArgument(*this, TheCall, 0))
1830 return true;
1831
Chris Lattnere202e6a2007-12-20 00:05:45 +00001832 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001833 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001834 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001835 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001836 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001837 else if (FunctionDecl *FD = getCurFunctionDecl())
1838 isVariadic = FD->isVariadic();
1839 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001840 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001841
Chris Lattnere202e6a2007-12-20 00:05:45 +00001842 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001843 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1844 return true;
1845 }
Mike Stump11289f42009-09-09 15:08:12 +00001846
Chris Lattner43be2e62007-12-19 23:59:04 +00001847 // Verify that the second argument to the builtin is the last argument of the
1848 // current function or method.
1849 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001850 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001851
Nico Weber9eea7642013-05-24 23:31:57 +00001852 // These are valid if SecondArgIsLastNamedArgument is false after the next
1853 // block.
1854 QualType Type;
1855 SourceLocation ParamLoc;
1856
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001857 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1858 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001859 // FIXME: This isn't correct for methods (results in bogus warning).
1860 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001861 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001862 if (CurBlock)
1863 LastArg = *(CurBlock->TheDecl->param_end()-1);
1864 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001865 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001866 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001867 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001868 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001869
1870 Type = PV->getType();
1871 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001872 }
1873 }
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattner43be2e62007-12-19 23:59:04 +00001875 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001876 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001877 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001878 else if (Type->isReferenceType()) {
1879 Diag(Arg->getLocStart(),
1880 diag::warn_va_start_of_reference_type_is_undefined);
1881 Diag(ParamLoc, diag::note_parameter_type) << Type;
1882 }
1883
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001884 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001885 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001886}
Chris Lattner43be2e62007-12-19 23:59:04 +00001887
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00001888bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
1889 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
1890 // const char *named_addr);
1891
1892 Expr *Func = Call->getCallee();
1893
1894 if (Call->getNumArgs() < 3)
1895 return Diag(Call->getLocEnd(),
1896 diag::err_typecheck_call_too_few_args_at_least)
1897 << 0 /*function call*/ << 3 << Call->getNumArgs();
1898
1899 // Determine whether the current function is variadic or not.
1900 bool IsVariadic;
1901 if (BlockScopeInfo *CurBlock = getCurBlock())
1902 IsVariadic = CurBlock->TheDecl->isVariadic();
1903 else if (FunctionDecl *FD = getCurFunctionDecl())
1904 IsVariadic = FD->isVariadic();
1905 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1906 IsVariadic = MD->isVariadic();
1907 else
1908 llvm_unreachable("unexpected statement type");
1909
1910 if (!IsVariadic) {
1911 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1912 return true;
1913 }
1914
1915 // Type-check the first argument normally.
1916 if (checkBuiltinArgument(*this, Call, 0))
1917 return true;
1918
1919 static const struct {
1920 unsigned ArgNo;
1921 QualType Type;
1922 } ArgumentTypes[] = {
1923 { 1, Context.getPointerType(Context.CharTy.withConst()) },
1924 { 2, Context.getSizeType() },
1925 };
1926
1927 for (const auto &AT : ArgumentTypes) {
1928 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
1929 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
1930 continue;
1931 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
1932 << Arg->getType() << AT.Type << 1 /* different class */
1933 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
1934 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
1935 }
1936
1937 return false;
1938}
1939
Chris Lattner2da14fb2007-12-20 00:26:33 +00001940/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1941/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001942bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1943 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001944 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001945 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001946 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001947 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001948 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001949 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001950 << SourceRange(TheCall->getArg(2)->getLocStart(),
1951 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001952
John Wiegley01296292011-04-08 18:41:53 +00001953 ExprResult OrigArg0 = TheCall->getArg(0);
1954 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001955
Chris Lattner2da14fb2007-12-20 00:26:33 +00001956 // Do standard promotions between the two arguments, returning their common
1957 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001958 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001959 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1960 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001961
1962 // Make sure any conversions are pushed back into the call; this is
1963 // type safe since unordered compare builtins are declared as "_Bool
1964 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001965 TheCall->setArg(0, OrigArg0.get());
1966 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001967
John Wiegley01296292011-04-08 18:41:53 +00001968 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001969 return false;
1970
Chris Lattner2da14fb2007-12-20 00:26:33 +00001971 // If the common type isn't a real floating type, then the arguments were
1972 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001973 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001974 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001975 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001976 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1977 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001978
Chris Lattner2da14fb2007-12-20 00:26:33 +00001979 return false;
1980}
1981
Benjamin Kramer634fc102010-02-15 22:42:31 +00001982/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1983/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001984/// to check everything. We expect the last argument to be a floating point
1985/// value.
1986bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1987 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001988 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001989 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001990 if (TheCall->getNumArgs() > NumArgs)
1991 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001992 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001993 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001994 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001995 (*(TheCall->arg_end()-1))->getLocEnd());
1996
Benjamin Kramer64aae502010-02-16 10:07:31 +00001997 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001998
Eli Friedman7e4faac2009-08-31 20:06:00 +00001999 if (OrigArg->isTypeDependent())
2000 return false;
2001
Chris Lattner68784ef2010-05-06 05:50:07 +00002002 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002003 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002004 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002005 diag::err_typecheck_call_invalid_unary_fp)
2006 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002007
Chris Lattner68784ef2010-05-06 05:50:07 +00002008 // If this is an implicit conversion from float -> double, remove it.
2009 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2010 Expr *CastArg = Cast->getSubExpr();
2011 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2012 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2013 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002014 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002015 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002016 }
2017 }
2018
Eli Friedman7e4faac2009-08-31 20:06:00 +00002019 return false;
2020}
2021
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002022/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2023// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002024ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002025 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002026 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002027 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002028 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2029 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002030
Nate Begemana0110022010-06-08 00:16:34 +00002031 // Determine which of the following types of shufflevector we're checking:
2032 // 1) unary, vector mask: (lhs, mask)
2033 // 2) binary, vector mask: (lhs, rhs, mask)
2034 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2035 QualType resType = TheCall->getArg(0)->getType();
2036 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002037
Douglas Gregorc25f7662009-05-19 22:10:17 +00002038 if (!TheCall->getArg(0)->isTypeDependent() &&
2039 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002040 QualType LHSType = TheCall->getArg(0)->getType();
2041 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002042
Craig Topperbaca3892013-07-29 06:47:04 +00002043 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2044 return ExprError(Diag(TheCall->getLocStart(),
2045 diag::err_shufflevector_non_vector)
2046 << SourceRange(TheCall->getArg(0)->getLocStart(),
2047 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002048
Nate Begemana0110022010-06-08 00:16:34 +00002049 numElements = LHSType->getAs<VectorType>()->getNumElements();
2050 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002051
Nate Begemana0110022010-06-08 00:16:34 +00002052 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2053 // with mask. If so, verify that RHS is an integer vector type with the
2054 // same number of elts as lhs.
2055 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002056 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002057 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002058 return ExprError(Diag(TheCall->getLocStart(),
2059 diag::err_shufflevector_incompatible_vector)
2060 << SourceRange(TheCall->getArg(1)->getLocStart(),
2061 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002062 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002063 return ExprError(Diag(TheCall->getLocStart(),
2064 diag::err_shufflevector_incompatible_vector)
2065 << SourceRange(TheCall->getArg(0)->getLocStart(),
2066 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002067 } else if (numElements != numResElements) {
2068 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002069 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002070 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002071 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002072 }
2073
2074 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002075 if (TheCall->getArg(i)->isTypeDependent() ||
2076 TheCall->getArg(i)->isValueDependent())
2077 continue;
2078
Nate Begemana0110022010-06-08 00:16:34 +00002079 llvm::APSInt Result(32);
2080 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2081 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002082 diag::err_shufflevector_nonconstant_argument)
2083 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002084
Craig Topper50ad5b72013-08-03 17:40:38 +00002085 // Allow -1 which will be translated to undef in the IR.
2086 if (Result.isSigned() && Result.isAllOnesValue())
2087 continue;
2088
Chris Lattner7ab824e2008-08-10 02:05:13 +00002089 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002090 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002091 diag::err_shufflevector_argument_too_large)
2092 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002093 }
2094
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002095 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002096
Chris Lattner7ab824e2008-08-10 02:05:13 +00002097 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002098 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002099 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002100 }
2101
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002102 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2103 TheCall->getCallee()->getLocStart(),
2104 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002105}
Chris Lattner43be2e62007-12-19 23:59:04 +00002106
Hal Finkelc4d7c822013-09-18 03:29:45 +00002107/// SemaConvertVectorExpr - Handle __builtin_convertvector
2108ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2109 SourceLocation BuiltinLoc,
2110 SourceLocation RParenLoc) {
2111 ExprValueKind VK = VK_RValue;
2112 ExprObjectKind OK = OK_Ordinary;
2113 QualType DstTy = TInfo->getType();
2114 QualType SrcTy = E->getType();
2115
2116 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2117 return ExprError(Diag(BuiltinLoc,
2118 diag::err_convertvector_non_vector)
2119 << E->getSourceRange());
2120 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2121 return ExprError(Diag(BuiltinLoc,
2122 diag::err_convertvector_non_vector_type));
2123
2124 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2125 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2126 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2127 if (SrcElts != DstElts)
2128 return ExprError(Diag(BuiltinLoc,
2129 diag::err_convertvector_incompatible_vector)
2130 << E->getSourceRange());
2131 }
2132
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002133 return new (Context)
2134 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002135}
2136
Daniel Dunbarb7257262008-07-21 22:59:13 +00002137/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2138// This is declared to take (const void*, ...) and can take two
2139// optional constant int args.
2140bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002141 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002142
Chris Lattner3b054132008-11-19 05:08:23 +00002143 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002144 return Diag(TheCall->getLocEnd(),
2145 diag::err_typecheck_call_too_many_args_at_most)
2146 << 0 /*function call*/ << 3 << NumArgs
2147 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002148
2149 // Argument 0 is checked for us and the remaining arguments must be
2150 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002151 for (unsigned i = 1; i != NumArgs; ++i)
2152 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002153 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002154
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002155 return false;
2156}
2157
Hal Finkelf0417332014-07-17 14:25:55 +00002158/// SemaBuiltinAssume - Handle __assume (MS Extension).
2159// __assume does not evaluate its arguments, and should warn if its argument
2160// has side effects.
2161bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2162 Expr *Arg = TheCall->getArg(0);
2163 if (Arg->isInstantiationDependent()) return false;
2164
2165 if (Arg->HasSideEffects(Context))
2166 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002167 << Arg->getSourceRange()
2168 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2169
2170 return false;
2171}
2172
2173/// Handle __builtin_assume_aligned. This is declared
2174/// as (const void*, size_t, ...) and can take one optional constant int arg.
2175bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2176 unsigned NumArgs = TheCall->getNumArgs();
2177
2178 if (NumArgs > 3)
2179 return Diag(TheCall->getLocEnd(),
2180 diag::err_typecheck_call_too_many_args_at_most)
2181 << 0 /*function call*/ << 3 << NumArgs
2182 << TheCall->getSourceRange();
2183
2184 // The alignment must be a constant integer.
2185 Expr *Arg = TheCall->getArg(1);
2186
2187 // We can't check the value of a dependent argument.
2188 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2189 llvm::APSInt Result;
2190 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2191 return true;
2192
2193 if (!Result.isPowerOf2())
2194 return Diag(TheCall->getLocStart(),
2195 diag::err_alignment_not_power_of_two)
2196 << Arg->getSourceRange();
2197 }
2198
2199 if (NumArgs > 2) {
2200 ExprResult Arg(TheCall->getArg(2));
2201 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2202 Context.getSizeType(), false);
2203 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2204 if (Arg.isInvalid()) return true;
2205 TheCall->setArg(2, Arg.get());
2206 }
Hal Finkelf0417332014-07-17 14:25:55 +00002207
2208 return false;
2209}
2210
Eric Christopher8d0c6212010-04-17 02:26:23 +00002211/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2212/// TheCall is a constant expression.
2213bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2214 llvm::APSInt &Result) {
2215 Expr *Arg = TheCall->getArg(ArgNum);
2216 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2217 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2218
2219 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2220
2221 if (!Arg->isIntegerConstantExpr(Result, Context))
2222 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002223 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002224
Chris Lattnerd545ad12009-09-23 06:06:36 +00002225 return false;
2226}
2227
Richard Sandiford28940af2014-04-16 08:47:51 +00002228/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2229/// TheCall is a constant expression in the range [Low, High].
2230bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2231 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002232 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002233
2234 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002235 Expr *Arg = TheCall->getArg(ArgNum);
2236 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002237 return false;
2238
Eric Christopher8d0c6212010-04-17 02:26:23 +00002239 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002240 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002241 return true;
2242
Richard Sandiford28940af2014-04-16 08:47:51 +00002243 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002244 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002245 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002246
2247 return false;
2248}
2249
Eli Friedmanc97d0142009-05-03 06:04:26 +00002250/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002251/// This checks that val is a constant 1.
2252bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2253 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002254 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002255
Eric Christopher8d0c6212010-04-17 02:26:23 +00002256 // TODO: This is less than ideal. Overload this to take a value.
2257 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2258 return true;
2259
2260 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002261 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2262 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2263
2264 return false;
2265}
2266
Richard Smithd7293d72013-08-05 18:49:43 +00002267namespace {
2268enum StringLiteralCheckType {
2269 SLCT_NotALiteral,
2270 SLCT_UncheckedLiteral,
2271 SLCT_CheckedLiteral
2272};
2273}
2274
Richard Smith55ce3522012-06-25 20:30:08 +00002275// Determine if an expression is a string literal or constant string.
2276// If this function returns false on the arguments to a function expecting a
2277// format string, we will usually need to emit a warning.
2278// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002279static StringLiteralCheckType
2280checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2281 bool HasVAListArg, unsigned format_idx,
2282 unsigned firstDataArg, Sema::FormatStringType Type,
2283 Sema::VariadicCallType CallType, bool InFunctionCall,
2284 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002285 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002286 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002287 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002288
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002289 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002290
Richard Smithd7293d72013-08-05 18:49:43 +00002291 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002292 // Technically -Wformat-nonliteral does not warn about this case.
2293 // The behavior of printf and friends in this case is implementation
2294 // dependent. Ideally if the format string cannot be null then
2295 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002296 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002297
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002298 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002299 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002300 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002301 // The expression is a literal if both sub-expressions were, and it was
2302 // completely checked only if both sub-expressions were checked.
2303 const AbstractConditionalOperator *C =
2304 cast<AbstractConditionalOperator>(E);
2305 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002306 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002307 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002308 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002309 if (Left == SLCT_NotALiteral)
2310 return SLCT_NotALiteral;
2311 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002312 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002313 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002314 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002315 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002316 }
2317
2318 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002319 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2320 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002321 }
2322
John McCallc07a0c72011-02-17 10:25:35 +00002323 case Stmt::OpaqueValueExprClass:
2324 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2325 E = src;
2326 goto tryAgain;
2327 }
Richard Smith55ce3522012-06-25 20:30:08 +00002328 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002329
Ted Kremeneka8890832011-02-24 23:03:04 +00002330 case Stmt::PredefinedExprClass:
2331 // While __func__, etc., are technically not string literals, they
2332 // cannot contain format specifiers and thus are not a security
2333 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002334 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002335
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002336 case Stmt::DeclRefExprClass: {
2337 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002338
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002339 // As an exception, do not flag errors for variables binding to
2340 // const string literals.
2341 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2342 bool isConstant = false;
2343 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002344
Richard Smithd7293d72013-08-05 18:49:43 +00002345 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2346 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002347 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002348 isConstant = T.isConstant(S.Context) &&
2349 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002350 } else if (T->isObjCObjectPointerType()) {
2351 // In ObjC, there is usually no "const ObjectPointer" type,
2352 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002353 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002354 }
Mike Stump11289f42009-09-09 15:08:12 +00002355
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002356 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002357 if (const Expr *Init = VD->getAnyInitializer()) {
2358 // Look through initializers like const char c[] = { "foo" }
2359 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2360 if (InitList->isStringLiteralInit())
2361 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2362 }
Richard Smithd7293d72013-08-05 18:49:43 +00002363 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002364 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002365 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002366 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002367 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002368 }
Mike Stump11289f42009-09-09 15:08:12 +00002369
Anders Carlssonb012ca92009-06-28 19:55:58 +00002370 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2371 // special check to see if the format string is a function parameter
2372 // of the function calling the printf function. If the function
2373 // has an attribute indicating it is a printf-like function, then we
2374 // should suppress warnings concerning non-literals being used in a call
2375 // to a vprintf function. For example:
2376 //
2377 // void
2378 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2379 // va_list ap;
2380 // va_start(ap, fmt);
2381 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2382 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002383 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002384 if (HasVAListArg) {
2385 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2386 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2387 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002388 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002389 // adjust for implicit parameter
2390 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2391 if (MD->isInstance())
2392 ++PVIndex;
2393 // We also check if the formats are compatible.
2394 // We can't pass a 'scanf' string to a 'printf' function.
2395 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002396 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002397 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002398 }
2399 }
2400 }
2401 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002402 }
Mike Stump11289f42009-09-09 15:08:12 +00002403
Richard Smith55ce3522012-06-25 20:30:08 +00002404 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002405 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002406
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002407 case Stmt::CallExprClass:
2408 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002409 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002410 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2411 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2412 unsigned ArgIndex = FA->getFormatIdx();
2413 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2414 if (MD->isInstance())
2415 --ArgIndex;
2416 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002417
Richard Smithd7293d72013-08-05 18:49:43 +00002418 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002419 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002420 Type, CallType, InFunctionCall,
2421 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002422 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2423 unsigned BuiltinID = FD->getBuiltinID();
2424 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2425 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2426 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002427 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002428 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002429 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002430 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002431 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002432 }
2433 }
Mike Stump11289f42009-09-09 15:08:12 +00002434
Richard Smith55ce3522012-06-25 20:30:08 +00002435 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002436 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002437 case Stmt::ObjCStringLiteralClass:
2438 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002439 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002440
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002441 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002442 StrE = ObjCFExpr->getString();
2443 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002444 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002445
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002446 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002447 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2448 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002449 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002450 }
Mike Stump11289f42009-09-09 15:08:12 +00002451
Richard Smith55ce3522012-06-25 20:30:08 +00002452 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002453 }
Mike Stump11289f42009-09-09 15:08:12 +00002454
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002455 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002456 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002457 }
2458}
2459
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002460Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002461 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002462 .Case("scanf", FST_Scanf)
2463 .Cases("printf", "printf0", FST_Printf)
2464 .Cases("NSString", "CFString", FST_NSString)
2465 .Case("strftime", FST_Strftime)
2466 .Case("strfmon", FST_Strfmon)
2467 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2468 .Default(FST_Unknown);
2469}
2470
Jordan Rose3e0ec582012-07-19 18:10:23 +00002471/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002472/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002473/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002474bool Sema::CheckFormatArguments(const FormatAttr *Format,
2475 ArrayRef<const Expr *> Args,
2476 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002477 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002478 SourceLocation Loc, SourceRange Range,
2479 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002480 FormatStringInfo FSI;
2481 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002482 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002483 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002484 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002485 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002486}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002487
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002488bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002489 bool HasVAListArg, unsigned format_idx,
2490 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002491 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002492 SourceLocation Loc, SourceRange Range,
2493 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002494 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002495 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002496 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002497 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002498 }
Mike Stump11289f42009-09-09 15:08:12 +00002499
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002500 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002501
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002502 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002503 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002504 // Dynamically generated format strings are difficult to
2505 // automatically vet at compile time. Requiring that format strings
2506 // are string literals: (1) permits the checking of format strings by
2507 // the compiler and thereby (2) can practically remove the source of
2508 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002509
Mike Stump11289f42009-09-09 15:08:12 +00002510 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002511 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002512 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002513 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002514 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002515 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2516 format_idx, firstDataArg, Type, CallType,
2517 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002518 if (CT != SLCT_NotALiteral)
2519 // Literal format string found, check done!
2520 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002521
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002522 // Strftime is particular as it always uses a single 'time' argument,
2523 // so it is safe to pass a non-literal string.
2524 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002525 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002526
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002527 // Do not emit diag when the string param is a macro expansion and the
2528 // format is either NSString or CFString. This is a hack to prevent
2529 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2530 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002531 if (Type == FST_NSString &&
2532 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002533 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002534
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002535 // If there are no arguments specified, warn with -Wformat-security, otherwise
2536 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002537 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002538 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002539 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002540 << OrigFormatExpr->getSourceRange();
2541 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002542 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002543 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002544 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002545 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002546}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002547
Ted Kremenekab278de2010-01-28 23:39:18 +00002548namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002549class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2550protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002551 Sema &S;
2552 const StringLiteral *FExpr;
2553 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002554 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002555 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002556 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002557 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002558 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002559 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002560 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002561 bool usesPositionalArgs;
2562 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002563 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002564 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002565 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002566public:
Ted Kremenek02087932010-07-16 02:11:22 +00002567 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002568 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002569 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002570 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002571 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002572 Sema::VariadicCallType callType,
2573 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002574 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002575 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2576 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002577 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002578 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002579 inFunctionCall(inFunctionCall), CallType(callType),
2580 CheckedVarArgs(CheckedVarArgs) {
2581 CoveredArgs.resize(numDataArgs);
2582 CoveredArgs.reset();
2583 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002584
Ted Kremenek019d2242010-01-29 01:50:07 +00002585 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002586
Ted Kremenek02087932010-07-16 02:11:22 +00002587 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002588 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002589
Jordan Rose92303592012-09-08 04:00:03 +00002590 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002591 const analyze_format_string::FormatSpecifier &FS,
2592 const analyze_format_string::ConversionSpecifier &CS,
2593 const char *startSpecifier, unsigned specifierLen,
2594 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002595
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002596 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002597 const analyze_format_string::FormatSpecifier &FS,
2598 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002599
2600 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002601 const analyze_format_string::ConversionSpecifier &CS,
2602 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002603
Craig Toppere14c0f82014-03-12 04:55:44 +00002604 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002605
Craig Toppere14c0f82014-03-12 04:55:44 +00002606 void HandleInvalidPosition(const char *startSpecifier,
2607 unsigned specifierLen,
2608 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002609
Craig Toppere14c0f82014-03-12 04:55:44 +00002610 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002611
Craig Toppere14c0f82014-03-12 04:55:44 +00002612 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002613
Richard Trieu03cf7b72011-10-28 00:41:25 +00002614 template <typename Range>
2615 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2616 const Expr *ArgumentExpr,
2617 PartialDiagnostic PDiag,
2618 SourceLocation StringLoc,
2619 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002620 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002621
Ted Kremenek02087932010-07-16 02:11:22 +00002622protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002623 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2624 const char *startSpec,
2625 unsigned specifierLen,
2626 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002627
2628 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2629 const char *startSpec,
2630 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002631
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002632 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002633 CharSourceRange getSpecifierRange(const char *startSpecifier,
2634 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002635 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002636
Ted Kremenek5739de72010-01-29 01:06:55 +00002637 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002638
2639 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2640 const analyze_format_string::ConversionSpecifier &CS,
2641 const char *startSpecifier, unsigned specifierLen,
2642 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002643
2644 template <typename Range>
2645 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2646 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002647 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002648};
2649}
2650
Ted Kremenek02087932010-07-16 02:11:22 +00002651SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002652 return OrigFormatExpr->getSourceRange();
2653}
2654
Ted Kremenek02087932010-07-16 02:11:22 +00002655CharSourceRange CheckFormatHandler::
2656getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002657 SourceLocation Start = getLocationOfByte(startSpecifier);
2658 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2659
2660 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002661 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002662
2663 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002664}
2665
Ted Kremenek02087932010-07-16 02:11:22 +00002666SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002667 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002668}
2669
Ted Kremenek02087932010-07-16 02:11:22 +00002670void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2671 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002672 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2673 getLocationOfByte(startSpecifier),
2674 /*IsStringLocation*/true,
2675 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002676}
2677
Jordan Rose92303592012-09-08 04:00:03 +00002678void CheckFormatHandler::HandleInvalidLengthModifier(
2679 const analyze_format_string::FormatSpecifier &FS,
2680 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002681 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002682 using namespace analyze_format_string;
2683
2684 const LengthModifier &LM = FS.getLengthModifier();
2685 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2686
2687 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002688 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002689 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002690 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002691 getLocationOfByte(LM.getStart()),
2692 /*IsStringLocation*/true,
2693 getSpecifierRange(startSpecifier, specifierLen));
2694
2695 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2696 << FixedLM->toString()
2697 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2698
2699 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002700 FixItHint Hint;
2701 if (DiagID == diag::warn_format_nonsensical_length)
2702 Hint = FixItHint::CreateRemoval(LMRange);
2703
2704 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002705 getLocationOfByte(LM.getStart()),
2706 /*IsStringLocation*/true,
2707 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002708 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002709 }
2710}
2711
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002712void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002713 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002714 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002715 using namespace analyze_format_string;
2716
2717 const LengthModifier &LM = FS.getLengthModifier();
2718 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2719
2720 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002721 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002722 if (FixedLM) {
2723 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2724 << LM.toString() << 0,
2725 getLocationOfByte(LM.getStart()),
2726 /*IsStringLocation*/true,
2727 getSpecifierRange(startSpecifier, specifierLen));
2728
2729 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2730 << FixedLM->toString()
2731 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2732
2733 } else {
2734 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2735 << LM.toString() << 0,
2736 getLocationOfByte(LM.getStart()),
2737 /*IsStringLocation*/true,
2738 getSpecifierRange(startSpecifier, specifierLen));
2739 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002740}
2741
2742void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2743 const analyze_format_string::ConversionSpecifier &CS,
2744 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002745 using namespace analyze_format_string;
2746
2747 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002748 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002749 if (FixedCS) {
2750 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2751 << CS.toString() << /*conversion specifier*/1,
2752 getLocationOfByte(CS.getStart()),
2753 /*IsStringLocation*/true,
2754 getSpecifierRange(startSpecifier, specifierLen));
2755
2756 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2757 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2758 << FixedCS->toString()
2759 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2760 } else {
2761 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2762 << CS.toString() << /*conversion specifier*/1,
2763 getLocationOfByte(CS.getStart()),
2764 /*IsStringLocation*/true,
2765 getSpecifierRange(startSpecifier, specifierLen));
2766 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002767}
2768
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002769void CheckFormatHandler::HandlePosition(const char *startPos,
2770 unsigned posLen) {
2771 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2772 getLocationOfByte(startPos),
2773 /*IsStringLocation*/true,
2774 getSpecifierRange(startPos, posLen));
2775}
2776
Ted Kremenekd1668192010-02-27 01:41:03 +00002777void
Ted Kremenek02087932010-07-16 02:11:22 +00002778CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2779 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002780 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2781 << (unsigned) p,
2782 getLocationOfByte(startPos), /*IsStringLocation*/true,
2783 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002784}
2785
Ted Kremenek02087932010-07-16 02:11:22 +00002786void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002787 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002788 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2789 getLocationOfByte(startPos),
2790 /*IsStringLocation*/true,
2791 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002792}
2793
Ted Kremenek02087932010-07-16 02:11:22 +00002794void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002795 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002796 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002797 EmitFormatDiagnostic(
2798 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2799 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2800 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002801 }
Ted Kremenek02087932010-07-16 02:11:22 +00002802}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002803
Jordan Rose58bbe422012-07-19 18:10:08 +00002804// Note that this may return NULL if there was an error parsing or building
2805// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002806const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002807 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002808}
2809
2810void CheckFormatHandler::DoneProcessing() {
2811 // Does the number of data arguments exceed the number of
2812 // format conversions in the format string?
2813 if (!HasVAListArg) {
2814 // Find any arguments that weren't covered.
2815 CoveredArgs.flip();
2816 signed notCoveredArg = CoveredArgs.find_first();
2817 if (notCoveredArg >= 0) {
2818 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002819 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2820 SourceLocation Loc = E->getLocStart();
2821 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2822 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2823 Loc, /*IsStringLocation*/false,
2824 getFormatStringRange());
2825 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002826 }
Ted Kremenek02087932010-07-16 02:11:22 +00002827 }
2828 }
2829}
2830
Ted Kremenekce815422010-07-19 21:25:57 +00002831bool
2832CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2833 SourceLocation Loc,
2834 const char *startSpec,
2835 unsigned specifierLen,
2836 const char *csStart,
2837 unsigned csLen) {
2838
2839 bool keepGoing = true;
2840 if (argIndex < NumDataArgs) {
2841 // Consider the argument coverered, even though the specifier doesn't
2842 // make sense.
2843 CoveredArgs.set(argIndex);
2844 }
2845 else {
2846 // If argIndex exceeds the number of data arguments we
2847 // don't issue a warning because that is just a cascade of warnings (and
2848 // they may have intended '%%' anyway). We don't want to continue processing
2849 // the format string after this point, however, as we will like just get
2850 // gibberish when trying to match arguments.
2851 keepGoing = false;
2852 }
2853
Richard Trieu03cf7b72011-10-28 00:41:25 +00002854 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2855 << StringRef(csStart, csLen),
2856 Loc, /*IsStringLocation*/true,
2857 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002858
2859 return keepGoing;
2860}
2861
Richard Trieu03cf7b72011-10-28 00:41:25 +00002862void
2863CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2864 const char *startSpec,
2865 unsigned specifierLen) {
2866 EmitFormatDiagnostic(
2867 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2868 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2869}
2870
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002871bool
2872CheckFormatHandler::CheckNumArgs(
2873 const analyze_format_string::FormatSpecifier &FS,
2874 const analyze_format_string::ConversionSpecifier &CS,
2875 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2876
2877 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002878 PartialDiagnostic PDiag = FS.usesPositionalArg()
2879 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2880 << (argIndex+1) << NumDataArgs)
2881 : S.PDiag(diag::warn_printf_insufficient_data_args);
2882 EmitFormatDiagnostic(
2883 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2884 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002885 return false;
2886 }
2887 return true;
2888}
2889
Richard Trieu03cf7b72011-10-28 00:41:25 +00002890template<typename Range>
2891void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2892 SourceLocation Loc,
2893 bool IsStringLocation,
2894 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002895 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002896 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002897 Loc, IsStringLocation, StringRange, FixIt);
2898}
2899
2900/// \brief If the format string is not within the funcion call, emit a note
2901/// so that the function call and string are in diagnostic messages.
2902///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002903/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002904/// call and only one diagnostic message will be produced. Otherwise, an
2905/// extra note will be emitted pointing to location of the format string.
2906///
2907/// \param ArgumentExpr the expression that is passed as the format string
2908/// argument in the function call. Used for getting locations when two
2909/// diagnostics are emitted.
2910///
2911/// \param PDiag the callee should already have provided any strings for the
2912/// diagnostic message. This function only adds locations and fixits
2913/// to diagnostics.
2914///
2915/// \param Loc primary location for diagnostic. If two diagnostics are
2916/// required, one will be at Loc and a new SourceLocation will be created for
2917/// the other one.
2918///
2919/// \param IsStringLocation if true, Loc points to the format string should be
2920/// used for the note. Otherwise, Loc points to the argument list and will
2921/// be used with PDiag.
2922///
2923/// \param StringRange some or all of the string to highlight. This is
2924/// templated so it can accept either a CharSourceRange or a SourceRange.
2925///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002926/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002927template<typename Range>
2928void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2929 const Expr *ArgumentExpr,
2930 PartialDiagnostic PDiag,
2931 SourceLocation Loc,
2932 bool IsStringLocation,
2933 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002934 ArrayRef<FixItHint> FixIt) {
2935 if (InFunctionCall) {
2936 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2937 D << StringRange;
2938 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2939 I != E; ++I) {
2940 D << *I;
2941 }
2942 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002943 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2944 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002945
2946 const Sema::SemaDiagnosticBuilder &Note =
2947 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2948 diag::note_format_string_defined);
2949
2950 Note << StringRange;
2951 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2952 I != E; ++I) {
2953 Note << *I;
2954 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002955 }
2956}
2957
Ted Kremenek02087932010-07-16 02:11:22 +00002958//===--- CHECK: Printf format string checking ------------------------------===//
2959
2960namespace {
2961class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002962 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002963public:
2964 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2965 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002966 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002967 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002968 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002969 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002970 Sema::VariadicCallType CallType,
2971 llvm::SmallBitVector &CheckedVarArgs)
2972 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2973 numDataArgs, beg, hasVAListArg, Args,
2974 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2975 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002976 {}
2977
Craig Toppere14c0f82014-03-12 04:55:44 +00002978
Ted Kremenek02087932010-07-16 02:11:22 +00002979 bool HandleInvalidPrintfConversionSpecifier(
2980 const analyze_printf::PrintfSpecifier &FS,
2981 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002982 unsigned specifierLen) override;
2983
Ted Kremenek02087932010-07-16 02:11:22 +00002984 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2985 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002986 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002987 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2988 const char *StartSpecifier,
2989 unsigned SpecifierLen,
2990 const Expr *E);
2991
Ted Kremenek02087932010-07-16 02:11:22 +00002992 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2993 const char *startSpecifier, unsigned specifierLen);
2994 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2995 const analyze_printf::OptionalAmount &Amt,
2996 unsigned type,
2997 const char *startSpecifier, unsigned specifierLen);
2998 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2999 const analyze_printf::OptionalFlag &flag,
3000 const char *startSpecifier, unsigned specifierLen);
3001 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3002 const analyze_printf::OptionalFlag &ignoredFlag,
3003 const analyze_printf::OptionalFlag &flag,
3004 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003005 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003006 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003007
Ted Kremenek02087932010-07-16 02:11:22 +00003008};
3009}
3010
3011bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3012 const analyze_printf::PrintfSpecifier &FS,
3013 const char *startSpecifier,
3014 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003015 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003016 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003017
Ted Kremenekce815422010-07-19 21:25:57 +00003018 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3019 getLocationOfByte(CS.getStart()),
3020 startSpecifier, specifierLen,
3021 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003022}
3023
Ted Kremenek02087932010-07-16 02:11:22 +00003024bool CheckPrintfHandler::HandleAmount(
3025 const analyze_format_string::OptionalAmount &Amt,
3026 unsigned k, const char *startSpecifier,
3027 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003028
3029 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003030 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003031 unsigned argIndex = Amt.getArgIndex();
3032 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003033 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3034 << k,
3035 getLocationOfByte(Amt.getStart()),
3036 /*IsStringLocation*/true,
3037 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003038 // Don't do any more checking. We will just emit
3039 // spurious errors.
3040 return false;
3041 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003042
Ted Kremenek5739de72010-01-29 01:06:55 +00003043 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003044 // Although not in conformance with C99, we also allow the argument to be
3045 // an 'unsigned int' as that is a reasonably safe case. GCC also
3046 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003047 CoveredArgs.set(argIndex);
3048 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003049 if (!Arg)
3050 return false;
3051
Ted Kremenek5739de72010-01-29 01:06:55 +00003052 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003053
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003054 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3055 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003056
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003057 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003058 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003059 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003060 << T << Arg->getSourceRange(),
3061 getLocationOfByte(Amt.getStart()),
3062 /*IsStringLocation*/true,
3063 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003064 // Don't do any more checking. We will just emit
3065 // spurious errors.
3066 return false;
3067 }
3068 }
3069 }
3070 return true;
3071}
Ted Kremenek5739de72010-01-29 01:06:55 +00003072
Tom Careb49ec692010-06-17 19:00:27 +00003073void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003074 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003075 const analyze_printf::OptionalAmount &Amt,
3076 unsigned type,
3077 const char *startSpecifier,
3078 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003079 const analyze_printf::PrintfConversionSpecifier &CS =
3080 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003081
Richard Trieu03cf7b72011-10-28 00:41:25 +00003082 FixItHint fixit =
3083 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3084 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3085 Amt.getConstantLength()))
3086 : FixItHint();
3087
3088 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3089 << type << CS.toString(),
3090 getLocationOfByte(Amt.getStart()),
3091 /*IsStringLocation*/true,
3092 getSpecifierRange(startSpecifier, specifierLen),
3093 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003094}
3095
Ted Kremenek02087932010-07-16 02:11:22 +00003096void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003097 const analyze_printf::OptionalFlag &flag,
3098 const char *startSpecifier,
3099 unsigned specifierLen) {
3100 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003101 const analyze_printf::PrintfConversionSpecifier &CS =
3102 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003103 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3104 << flag.toString() << CS.toString(),
3105 getLocationOfByte(flag.getPosition()),
3106 /*IsStringLocation*/true,
3107 getSpecifierRange(startSpecifier, specifierLen),
3108 FixItHint::CreateRemoval(
3109 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003110}
3111
3112void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003113 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003114 const analyze_printf::OptionalFlag &ignoredFlag,
3115 const analyze_printf::OptionalFlag &flag,
3116 const char *startSpecifier,
3117 unsigned specifierLen) {
3118 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003119 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3120 << ignoredFlag.toString() << flag.toString(),
3121 getLocationOfByte(ignoredFlag.getPosition()),
3122 /*IsStringLocation*/true,
3123 getSpecifierRange(startSpecifier, specifierLen),
3124 FixItHint::CreateRemoval(
3125 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003126}
3127
Richard Smith55ce3522012-06-25 20:30:08 +00003128// Determines if the specified is a C++ class or struct containing
3129// a member with the specified name and kind (e.g. a CXXMethodDecl named
3130// "c_str()").
3131template<typename MemberKind>
3132static llvm::SmallPtrSet<MemberKind*, 1>
3133CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3134 const RecordType *RT = Ty->getAs<RecordType>();
3135 llvm::SmallPtrSet<MemberKind*, 1> Results;
3136
3137 if (!RT)
3138 return Results;
3139 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003140 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003141 return Results;
3142
Alp Tokerb6cc5922014-05-03 03:45:55 +00003143 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003144 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003145 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003146
3147 // We just need to include all members of the right kind turned up by the
3148 // filter, at this point.
3149 if (S.LookupQualifiedName(R, RT->getDecl()))
3150 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3151 NamedDecl *decl = (*I)->getUnderlyingDecl();
3152 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3153 Results.insert(FK);
3154 }
3155 return Results;
3156}
3157
Richard Smith2868a732014-02-28 01:36:39 +00003158/// Check if we could call '.c_str()' on an object.
3159///
3160/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3161/// allow the call, or if it would be ambiguous).
3162bool Sema::hasCStrMethod(const Expr *E) {
3163 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3164 MethodSet Results =
3165 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3166 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3167 MI != ME; ++MI)
3168 if ((*MI)->getMinRequiredArguments() == 0)
3169 return true;
3170 return false;
3171}
3172
Richard Smith55ce3522012-06-25 20:30:08 +00003173// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003174// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003175// Returns true when a c_str() conversion method is found.
3176bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003177 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003178 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3179
3180 MethodSet Results =
3181 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3182
3183 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3184 MI != ME; ++MI) {
3185 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003186 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003187 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003188 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003189 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003190 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3191 << "c_str()"
3192 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3193 return true;
3194 }
3195 }
3196
3197 return false;
3198}
3199
Ted Kremenekab278de2010-01-28 23:39:18 +00003200bool
Ted Kremenek02087932010-07-16 02:11:22 +00003201CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003202 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003203 const char *startSpecifier,
3204 unsigned specifierLen) {
3205
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003206 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003207 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003208 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003209
Ted Kremenek6cd69422010-07-19 22:01:06 +00003210 if (FS.consumesDataArgument()) {
3211 if (atFirstArg) {
3212 atFirstArg = false;
3213 usesPositionalArgs = FS.usesPositionalArg();
3214 }
3215 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003216 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3217 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003218 return false;
3219 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003220 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003221
Ted Kremenekd1668192010-02-27 01:41:03 +00003222 // First check if the field width, precision, and conversion specifier
3223 // have matching data arguments.
3224 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3225 startSpecifier, specifierLen)) {
3226 return false;
3227 }
3228
3229 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3230 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003231 return false;
3232 }
3233
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003234 if (!CS.consumesDataArgument()) {
3235 // FIXME: Technically specifying a precision or field width here
3236 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003237 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003238 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003239
Ted Kremenek4a49d982010-02-26 19:18:41 +00003240 // Consume the argument.
3241 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003242 if (argIndex < NumDataArgs) {
3243 // The check to see if the argIndex is valid will come later.
3244 // We set the bit here because we may exit early from this
3245 // function if we encounter some other error.
3246 CoveredArgs.set(argIndex);
3247 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003248
3249 // Check for using an Objective-C specific conversion specifier
3250 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003251 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003252 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3253 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003254 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003255
Tom Careb49ec692010-06-17 19:00:27 +00003256 // Check for invalid use of field width
3257 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003258 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003259 startSpecifier, specifierLen);
3260 }
3261
3262 // Check for invalid use of precision
3263 if (!FS.hasValidPrecision()) {
3264 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3265 startSpecifier, specifierLen);
3266 }
3267
3268 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003269 if (!FS.hasValidThousandsGroupingPrefix())
3270 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003271 if (!FS.hasValidLeadingZeros())
3272 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3273 if (!FS.hasValidPlusPrefix())
3274 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003275 if (!FS.hasValidSpacePrefix())
3276 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003277 if (!FS.hasValidAlternativeForm())
3278 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3279 if (!FS.hasValidLeftJustified())
3280 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3281
3282 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003283 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3284 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3285 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003286 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3287 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3288 startSpecifier, specifierLen);
3289
3290 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003291 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003292 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3293 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003294 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003295 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003296 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003297 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3298 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003299
Jordan Rose92303592012-09-08 04:00:03 +00003300 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3301 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3302
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003303 // The remaining checks depend on the data arguments.
3304 if (HasVAListArg)
3305 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003306
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003307 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003308 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003309
Jordan Rose58bbe422012-07-19 18:10:08 +00003310 const Expr *Arg = getDataArg(argIndex);
3311 if (!Arg)
3312 return true;
3313
3314 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003315}
3316
Jordan Roseaee34382012-09-05 22:56:26 +00003317static bool requiresParensToAddCast(const Expr *E) {
3318 // FIXME: We should have a general way to reason about operator
3319 // precedence and whether parens are actually needed here.
3320 // Take care of a few common cases where they aren't.
3321 const Expr *Inside = E->IgnoreImpCasts();
3322 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3323 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3324
3325 switch (Inside->getStmtClass()) {
3326 case Stmt::ArraySubscriptExprClass:
3327 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003328 case Stmt::CharacterLiteralClass:
3329 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003330 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003331 case Stmt::FloatingLiteralClass:
3332 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003333 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003334 case Stmt::ObjCArrayLiteralClass:
3335 case Stmt::ObjCBoolLiteralExprClass:
3336 case Stmt::ObjCBoxedExprClass:
3337 case Stmt::ObjCDictionaryLiteralClass:
3338 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003339 case Stmt::ObjCIvarRefExprClass:
3340 case Stmt::ObjCMessageExprClass:
3341 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003342 case Stmt::ObjCStringLiteralClass:
3343 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003344 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003345 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003346 case Stmt::UnaryOperatorClass:
3347 return false;
3348 default:
3349 return true;
3350 }
3351}
3352
Richard Smith55ce3522012-06-25 20:30:08 +00003353bool
3354CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3355 const char *StartSpecifier,
3356 unsigned SpecifierLen,
3357 const Expr *E) {
3358 using namespace analyze_format_string;
3359 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003360 // Now type check the data expression that matches the
3361 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003362 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3363 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003364 if (!AT.isValid())
3365 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003366
Jordan Rose598ec092012-12-05 18:44:40 +00003367 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003368 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3369 ExprTy = TET->getUnderlyingExpr()->getType();
3370 }
3371
Jordan Rose598ec092012-12-05 18:44:40 +00003372 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003373 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003374
Jordan Rose22b74712012-09-05 22:56:19 +00003375 // Look through argument promotions for our error message's reported type.
3376 // This includes the integral and floating promotions, but excludes array
3377 // and function pointer decay; seeing that an argument intended to be a
3378 // string has type 'char [6]' is probably more confusing than 'char *'.
3379 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3380 if (ICE->getCastKind() == CK_IntegralCast ||
3381 ICE->getCastKind() == CK_FloatingCast) {
3382 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003383 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003384
3385 // Check if we didn't match because of an implicit cast from a 'char'
3386 // or 'short' to an 'int'. This is done because printf is a varargs
3387 // function.
3388 if (ICE->getType() == S.Context.IntTy ||
3389 ICE->getType() == S.Context.UnsignedIntTy) {
3390 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003391 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003392 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003393 }
Jordan Rose98709982012-06-04 22:48:57 +00003394 }
Jordan Rose598ec092012-12-05 18:44:40 +00003395 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3396 // Special case for 'a', which has type 'int' in C.
3397 // Note, however, that we do /not/ want to treat multibyte constants like
3398 // 'MooV' as characters! This form is deprecated but still exists.
3399 if (ExprTy == S.Context.IntTy)
3400 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3401 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003402 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003403
Jordan Rosebc53ed12014-05-31 04:12:14 +00003404 // Look through enums to their underlying type.
3405 bool IsEnum = false;
3406 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3407 ExprTy = EnumTy->getDecl()->getIntegerType();
3408 IsEnum = true;
3409 }
3410
Jordan Rose0e5badd2012-12-05 18:44:49 +00003411 // %C in an Objective-C context prints a unichar, not a wchar_t.
3412 // If the argument is an integer of some kind, believe the %C and suggest
3413 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003414 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003415 if (ObjCContext &&
3416 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3417 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3418 !ExprTy->isCharType()) {
3419 // 'unichar' is defined as a typedef of unsigned short, but we should
3420 // prefer using the typedef if it is visible.
3421 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003422
3423 // While we are here, check if the value is an IntegerLiteral that happens
3424 // to be within the valid range.
3425 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3426 const llvm::APInt &V = IL->getValue();
3427 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3428 return true;
3429 }
3430
Jordan Rose0e5badd2012-12-05 18:44:49 +00003431 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3432 Sema::LookupOrdinaryName);
3433 if (S.LookupName(Result, S.getCurScope())) {
3434 NamedDecl *ND = Result.getFoundDecl();
3435 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3436 if (TD->getUnderlyingType() == IntendedTy)
3437 IntendedTy = S.Context.getTypedefType(TD);
3438 }
3439 }
3440 }
3441
3442 // Special-case some of Darwin's platform-independence types by suggesting
3443 // casts to primitive types that are known to be large enough.
3444 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003445 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003446 // Use a 'while' to peel off layers of typedefs.
3447 QualType TyTy = IntendedTy;
3448 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003449 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003450 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003451 .Case("NSInteger", S.Context.LongTy)
3452 .Case("NSUInteger", S.Context.UnsignedLongTy)
3453 .Case("SInt32", S.Context.IntTy)
3454 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003455 .Default(QualType());
3456
3457 if (!CastTy.isNull()) {
3458 ShouldNotPrintDirectly = true;
3459 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003460 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003461 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003462 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003463 }
3464 }
3465
Jordan Rose22b74712012-09-05 22:56:19 +00003466 // We may be able to offer a FixItHint if it is a supported type.
3467 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003468 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003469 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003470
Jordan Rose22b74712012-09-05 22:56:19 +00003471 if (success) {
3472 // Get the fix string from the fixed format specifier
3473 SmallString<16> buf;
3474 llvm::raw_svector_ostream os(buf);
3475 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003476
Jordan Roseaee34382012-09-05 22:56:26 +00003477 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3478
Jordan Rose0e5badd2012-12-05 18:44:49 +00003479 if (IntendedTy == ExprTy) {
3480 // In this case, the specifier is wrong and should be changed to match
3481 // the argument.
3482 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003483 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3484 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003485 << E->getSourceRange(),
3486 E->getLocStart(),
3487 /*IsStringLocation*/false,
3488 SpecRange,
3489 FixItHint::CreateReplacement(SpecRange, os.str()));
3490
3491 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003492 // The canonical type for formatting this value is different from the
3493 // actual type of the expression. (This occurs, for example, with Darwin's
3494 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3495 // should be printed as 'long' for 64-bit compatibility.)
3496 // Rather than emitting a normal format/argument mismatch, we want to
3497 // add a cast to the recommended type (and correct the format string
3498 // if necessary).
3499 SmallString<16> CastBuf;
3500 llvm::raw_svector_ostream CastFix(CastBuf);
3501 CastFix << "(";
3502 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3503 CastFix << ")";
3504
3505 SmallVector<FixItHint,4> Hints;
3506 if (!AT.matchesType(S.Context, IntendedTy))
3507 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3508
3509 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3510 // If there's already a cast present, just replace it.
3511 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3512 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3513
3514 } else if (!requiresParensToAddCast(E)) {
3515 // If the expression has high enough precedence,
3516 // just write the C-style cast.
3517 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3518 CastFix.str()));
3519 } else {
3520 // Otherwise, add parens around the expression as well as the cast.
3521 CastFix << "(";
3522 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3523 CastFix.str()));
3524
Alp Tokerb6cc5922014-05-03 03:45:55 +00003525 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003526 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3527 }
3528
Jordan Rose0e5badd2012-12-05 18:44:49 +00003529 if (ShouldNotPrintDirectly) {
3530 // The expression has a type that should not be printed directly.
3531 // We extract the name from the typedef because we don't want to show
3532 // the underlying type in the diagnostic.
3533 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003534
Jordan Rose0e5badd2012-12-05 18:44:49 +00003535 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003536 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003537 << E->getSourceRange(),
3538 E->getLocStart(), /*IsStringLocation=*/false,
3539 SpecRange, Hints);
3540 } else {
3541 // In this case, the expression could be printed using a different
3542 // specifier, but we've decided that the specifier is probably correct
3543 // and we should cast instead. Just use the normal warning message.
3544 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003545 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3546 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003547 << E->getSourceRange(),
3548 E->getLocStart(), /*IsStringLocation*/false,
3549 SpecRange, Hints);
3550 }
Jordan Roseaee34382012-09-05 22:56:26 +00003551 }
Jordan Rose22b74712012-09-05 22:56:19 +00003552 } else {
3553 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3554 SpecifierLen);
3555 // Since the warning for passing non-POD types to variadic functions
3556 // was deferred until now, we emit a warning for non-POD
3557 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003558 switch (S.isValidVarArgType(ExprTy)) {
3559 case Sema::VAK_Valid:
3560 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003561 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003562 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3563 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003564 << CSR
3565 << E->getSourceRange(),
3566 E->getLocStart(), /*IsStringLocation*/false, CSR);
3567 break;
3568
3569 case Sema::VAK_Undefined:
3570 EmitFormatDiagnostic(
3571 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003572 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003573 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003574 << CallType
3575 << AT.getRepresentativeTypeName(S.Context)
3576 << CSR
3577 << E->getSourceRange(),
3578 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003579 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003580 break;
3581
3582 case Sema::VAK_Invalid:
3583 if (ExprTy->isObjCObjectType())
3584 EmitFormatDiagnostic(
3585 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3586 << S.getLangOpts().CPlusPlus11
3587 << ExprTy
3588 << CallType
3589 << AT.getRepresentativeTypeName(S.Context)
3590 << CSR
3591 << E->getSourceRange(),
3592 E->getLocStart(), /*IsStringLocation*/false, CSR);
3593 else
3594 // FIXME: If this is an initializer list, suggest removing the braces
3595 // or inserting a cast to the target type.
3596 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3597 << isa<InitListExpr>(E) << ExprTy << CallType
3598 << AT.getRepresentativeTypeName(S.Context)
3599 << E->getSourceRange();
3600 break;
3601 }
3602
3603 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3604 "format string specifier index out of range");
3605 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003606 }
3607
Ted Kremenekab278de2010-01-28 23:39:18 +00003608 return true;
3609}
3610
Ted Kremenek02087932010-07-16 02:11:22 +00003611//===--- CHECK: Scanf format string checking ------------------------------===//
3612
3613namespace {
3614class CheckScanfHandler : public CheckFormatHandler {
3615public:
3616 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3617 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003618 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003619 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003620 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003621 Sema::VariadicCallType CallType,
3622 llvm::SmallBitVector &CheckedVarArgs)
3623 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3624 numDataArgs, beg, hasVAListArg,
3625 Args, formatIdx, inFunctionCall, CallType,
3626 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003627 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003628
3629 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3630 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003631 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003632
3633 bool HandleInvalidScanfConversionSpecifier(
3634 const analyze_scanf::ScanfSpecifier &FS,
3635 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003636 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003637
Craig Toppere14c0f82014-03-12 04:55:44 +00003638 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003639};
Ted Kremenek019d2242010-01-29 01:50:07 +00003640}
Ted Kremenekab278de2010-01-28 23:39:18 +00003641
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003642void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3643 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003644 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3645 getLocationOfByte(end), /*IsStringLocation*/true,
3646 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003647}
3648
Ted Kremenekce815422010-07-19 21:25:57 +00003649bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3650 const analyze_scanf::ScanfSpecifier &FS,
3651 const char *startSpecifier,
3652 unsigned specifierLen) {
3653
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003654 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003655 FS.getConversionSpecifier();
3656
3657 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3658 getLocationOfByte(CS.getStart()),
3659 startSpecifier, specifierLen,
3660 CS.getStart(), CS.getLength());
3661}
3662
Ted Kremenek02087932010-07-16 02:11:22 +00003663bool CheckScanfHandler::HandleScanfSpecifier(
3664 const analyze_scanf::ScanfSpecifier &FS,
3665 const char *startSpecifier,
3666 unsigned specifierLen) {
3667
3668 using namespace analyze_scanf;
3669 using namespace analyze_format_string;
3670
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003671 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003672
Ted Kremenek6cd69422010-07-19 22:01:06 +00003673 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3674 // be used to decide if we are using positional arguments consistently.
3675 if (FS.consumesDataArgument()) {
3676 if (atFirstArg) {
3677 atFirstArg = false;
3678 usesPositionalArgs = FS.usesPositionalArg();
3679 }
3680 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003681 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3682 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003683 return false;
3684 }
Ted Kremenek02087932010-07-16 02:11:22 +00003685 }
3686
3687 // Check if the field with is non-zero.
3688 const OptionalAmount &Amt = FS.getFieldWidth();
3689 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3690 if (Amt.getConstantAmount() == 0) {
3691 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3692 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003693 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3694 getLocationOfByte(Amt.getStart()),
3695 /*IsStringLocation*/true, R,
3696 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003697 }
3698 }
3699
3700 if (!FS.consumesDataArgument()) {
3701 // FIXME: Technically specifying a precision or field width here
3702 // makes no sense. Worth issuing a warning at some point.
3703 return true;
3704 }
3705
3706 // Consume the argument.
3707 unsigned argIndex = FS.getArgIndex();
3708 if (argIndex < NumDataArgs) {
3709 // The check to see if the argIndex is valid will come later.
3710 // We set the bit here because we may exit early from this
3711 // function if we encounter some other error.
3712 CoveredArgs.set(argIndex);
3713 }
3714
Ted Kremenek4407ea42010-07-20 20:04:47 +00003715 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003716 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003717 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3718 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003719 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003720 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003721 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003722 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3723 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003724
Jordan Rose92303592012-09-08 04:00:03 +00003725 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3726 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3727
Ted Kremenek02087932010-07-16 02:11:22 +00003728 // The remaining checks depend on the data arguments.
3729 if (HasVAListArg)
3730 return true;
3731
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003732 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003733 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003734
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003735 // Check that the argument type matches the format specifier.
3736 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003737 if (!Ex)
3738 return true;
3739
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003740 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3741 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003742 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003743 bool success = fixedFS.fixType(Ex->getType(),
3744 Ex->IgnoreImpCasts()->getType(),
3745 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003746
3747 if (success) {
3748 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003749 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003750 llvm::raw_svector_ostream os(buf);
3751 fixedFS.toString(os);
3752
3753 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003754 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3755 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003756 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003757 Ex->getLocStart(),
3758 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003759 getSpecifierRange(startSpecifier, specifierLen),
3760 FixItHint::CreateReplacement(
3761 getSpecifierRange(startSpecifier, specifierLen),
3762 os.str()));
3763 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003764 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003765 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3766 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003767 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003768 Ex->getLocStart(),
3769 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003770 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003771 }
3772 }
3773
Ted Kremenek02087932010-07-16 02:11:22 +00003774 return true;
3775}
3776
3777void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003778 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003779 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003780 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003781 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003782 bool inFunctionCall, VariadicCallType CallType,
3783 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003784
Ted Kremenekab278de2010-01-28 23:39:18 +00003785 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003786 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003787 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003788 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003789 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3790 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003791 return;
3792 }
Ted Kremenek02087932010-07-16 02:11:22 +00003793
Ted Kremenekab278de2010-01-28 23:39:18 +00003794 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003795 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003796 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003797 // Account for cases where the string literal is truncated in a declaration.
3798 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3799 assert(T && "String literal not of constant array type!");
3800 size_t TypeSize = T->getSize().getZExtValue();
3801 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003802 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003803
3804 // Emit a warning if the string literal is truncated and does not contain an
3805 // embedded null character.
3806 if (TypeSize <= StrRef.size() &&
3807 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3808 CheckFormatHandler::EmitFormatDiagnostic(
3809 *this, inFunctionCall, Args[format_idx],
3810 PDiag(diag::warn_printf_format_string_not_null_terminated),
3811 FExpr->getLocStart(),
3812 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3813 return;
3814 }
3815
Ted Kremenekab278de2010-01-28 23:39:18 +00003816 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003817 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003818 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003819 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003820 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3821 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003822 return;
3823 }
Ted Kremenek02087932010-07-16 02:11:22 +00003824
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003825 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003826 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003827 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003828 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003829 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003830
Hans Wennborg23926bd2011-12-15 10:25:47 +00003831 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003832 getLangOpts(),
3833 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003834 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003835 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003836 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003837 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003838 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003839
Hans Wennborg23926bd2011-12-15 10:25:47 +00003840 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003841 getLangOpts(),
3842 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003843 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003844 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003845}
3846
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003847bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
3848 // Str - The format string. NOTE: this is NOT null-terminated!
3849 StringRef StrRef = FExpr->getString();
3850 const char *Str = StrRef.data();
3851 // Account for cases where the string literal is truncated in a declaration.
3852 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3853 assert(T && "String literal not of constant array type!");
3854 size_t TypeSize = T->getSize().getZExtValue();
3855 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3856 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
3857 getLangOpts(),
3858 Context.getTargetInfo());
3859}
3860
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003861//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3862
3863// Returns the related absolute value function that is larger, of 0 if one
3864// does not exist.
3865static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3866 switch (AbsFunction) {
3867 default:
3868 return 0;
3869
3870 case Builtin::BI__builtin_abs:
3871 return Builtin::BI__builtin_labs;
3872 case Builtin::BI__builtin_labs:
3873 return Builtin::BI__builtin_llabs;
3874 case Builtin::BI__builtin_llabs:
3875 return 0;
3876
3877 case Builtin::BI__builtin_fabsf:
3878 return Builtin::BI__builtin_fabs;
3879 case Builtin::BI__builtin_fabs:
3880 return Builtin::BI__builtin_fabsl;
3881 case Builtin::BI__builtin_fabsl:
3882 return 0;
3883
3884 case Builtin::BI__builtin_cabsf:
3885 return Builtin::BI__builtin_cabs;
3886 case Builtin::BI__builtin_cabs:
3887 return Builtin::BI__builtin_cabsl;
3888 case Builtin::BI__builtin_cabsl:
3889 return 0;
3890
3891 case Builtin::BIabs:
3892 return Builtin::BIlabs;
3893 case Builtin::BIlabs:
3894 return Builtin::BIllabs;
3895 case Builtin::BIllabs:
3896 return 0;
3897
3898 case Builtin::BIfabsf:
3899 return Builtin::BIfabs;
3900 case Builtin::BIfabs:
3901 return Builtin::BIfabsl;
3902 case Builtin::BIfabsl:
3903 return 0;
3904
3905 case Builtin::BIcabsf:
3906 return Builtin::BIcabs;
3907 case Builtin::BIcabs:
3908 return Builtin::BIcabsl;
3909 case Builtin::BIcabsl:
3910 return 0;
3911 }
3912}
3913
3914// Returns the argument type of the absolute value function.
3915static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3916 unsigned AbsType) {
3917 if (AbsType == 0)
3918 return QualType();
3919
3920 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3921 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3922 if (Error != ASTContext::GE_None)
3923 return QualType();
3924
3925 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3926 if (!FT)
3927 return QualType();
3928
3929 if (FT->getNumParams() != 1)
3930 return QualType();
3931
3932 return FT->getParamType(0);
3933}
3934
3935// Returns the best absolute value function, or zero, based on type and
3936// current absolute value function.
3937static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3938 unsigned AbsFunctionKind) {
3939 unsigned BestKind = 0;
3940 uint64_t ArgSize = Context.getTypeSize(ArgType);
3941 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3942 Kind = getLargerAbsoluteValueFunction(Kind)) {
3943 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3944 if (Context.getTypeSize(ParamType) >= ArgSize) {
3945 if (BestKind == 0)
3946 BestKind = Kind;
3947 else if (Context.hasSameType(ParamType, ArgType)) {
3948 BestKind = Kind;
3949 break;
3950 }
3951 }
3952 }
3953 return BestKind;
3954}
3955
3956enum AbsoluteValueKind {
3957 AVK_Integer,
3958 AVK_Floating,
3959 AVK_Complex
3960};
3961
3962static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3963 if (T->isIntegralOrEnumerationType())
3964 return AVK_Integer;
3965 if (T->isRealFloatingType())
3966 return AVK_Floating;
3967 if (T->isAnyComplexType())
3968 return AVK_Complex;
3969
3970 llvm_unreachable("Type not integer, floating, or complex");
3971}
3972
3973// Changes the absolute value function to a different type. Preserves whether
3974// the function is a builtin.
3975static unsigned changeAbsFunction(unsigned AbsKind,
3976 AbsoluteValueKind ValueKind) {
3977 switch (ValueKind) {
3978 case AVK_Integer:
3979 switch (AbsKind) {
3980 default:
3981 return 0;
3982 case Builtin::BI__builtin_fabsf:
3983 case Builtin::BI__builtin_fabs:
3984 case Builtin::BI__builtin_fabsl:
3985 case Builtin::BI__builtin_cabsf:
3986 case Builtin::BI__builtin_cabs:
3987 case Builtin::BI__builtin_cabsl:
3988 return Builtin::BI__builtin_abs;
3989 case Builtin::BIfabsf:
3990 case Builtin::BIfabs:
3991 case Builtin::BIfabsl:
3992 case Builtin::BIcabsf:
3993 case Builtin::BIcabs:
3994 case Builtin::BIcabsl:
3995 return Builtin::BIabs;
3996 }
3997 case AVK_Floating:
3998 switch (AbsKind) {
3999 default:
4000 return 0;
4001 case Builtin::BI__builtin_abs:
4002 case Builtin::BI__builtin_labs:
4003 case Builtin::BI__builtin_llabs:
4004 case Builtin::BI__builtin_cabsf:
4005 case Builtin::BI__builtin_cabs:
4006 case Builtin::BI__builtin_cabsl:
4007 return Builtin::BI__builtin_fabsf;
4008 case Builtin::BIabs:
4009 case Builtin::BIlabs:
4010 case Builtin::BIllabs:
4011 case Builtin::BIcabsf:
4012 case Builtin::BIcabs:
4013 case Builtin::BIcabsl:
4014 return Builtin::BIfabsf;
4015 }
4016 case AVK_Complex:
4017 switch (AbsKind) {
4018 default:
4019 return 0;
4020 case Builtin::BI__builtin_abs:
4021 case Builtin::BI__builtin_labs:
4022 case Builtin::BI__builtin_llabs:
4023 case Builtin::BI__builtin_fabsf:
4024 case Builtin::BI__builtin_fabs:
4025 case Builtin::BI__builtin_fabsl:
4026 return Builtin::BI__builtin_cabsf;
4027 case Builtin::BIabs:
4028 case Builtin::BIlabs:
4029 case Builtin::BIllabs:
4030 case Builtin::BIfabsf:
4031 case Builtin::BIfabs:
4032 case Builtin::BIfabsl:
4033 return Builtin::BIcabsf;
4034 }
4035 }
4036 llvm_unreachable("Unable to convert function");
4037}
4038
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004039static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004040 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4041 if (!FnInfo)
4042 return 0;
4043
4044 switch (FDecl->getBuiltinID()) {
4045 default:
4046 return 0;
4047 case Builtin::BI__builtin_abs:
4048 case Builtin::BI__builtin_fabs:
4049 case Builtin::BI__builtin_fabsf:
4050 case Builtin::BI__builtin_fabsl:
4051 case Builtin::BI__builtin_labs:
4052 case Builtin::BI__builtin_llabs:
4053 case Builtin::BI__builtin_cabs:
4054 case Builtin::BI__builtin_cabsf:
4055 case Builtin::BI__builtin_cabsl:
4056 case Builtin::BIabs:
4057 case Builtin::BIlabs:
4058 case Builtin::BIllabs:
4059 case Builtin::BIfabs:
4060 case Builtin::BIfabsf:
4061 case Builtin::BIfabsl:
4062 case Builtin::BIcabs:
4063 case Builtin::BIcabsf:
4064 case Builtin::BIcabsl:
4065 return FDecl->getBuiltinID();
4066 }
4067 llvm_unreachable("Unknown Builtin type");
4068}
4069
4070// If the replacement is valid, emit a note with replacement function.
4071// Additionally, suggest including the proper header if not already included.
4072static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004073 unsigned AbsKind, QualType ArgType) {
4074 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004075 const char *HeaderName = nullptr;
4076 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004077 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4078 FunctionName = "std::abs";
4079 if (ArgType->isIntegralOrEnumerationType()) {
4080 HeaderName = "cstdlib";
4081 } else if (ArgType->isRealFloatingType()) {
4082 HeaderName = "cmath";
4083 } else {
4084 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004085 }
Richard Trieubeffb832014-04-15 23:47:53 +00004086
4087 // Lookup all std::abs
4088 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004089 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004090 R.suppressDiagnostics();
4091 S.LookupQualifiedName(R, Std);
4092
4093 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004094 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004095 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4096 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4097 } else {
4098 FDecl = dyn_cast<FunctionDecl>(I);
4099 }
4100 if (!FDecl)
4101 continue;
4102
4103 // Found std::abs(), check that they are the right ones.
4104 if (FDecl->getNumParams() != 1)
4105 continue;
4106
4107 // Check that the parameter type can handle the argument.
4108 QualType ParamType = FDecl->getParamDecl(0)->getType();
4109 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4110 S.Context.getTypeSize(ArgType) <=
4111 S.Context.getTypeSize(ParamType)) {
4112 // Found a function, don't need the header hint.
4113 EmitHeaderHint = false;
4114 break;
4115 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004116 }
Richard Trieubeffb832014-04-15 23:47:53 +00004117 }
4118 } else {
4119 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4120 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4121
4122 if (HeaderName) {
4123 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4124 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4125 R.suppressDiagnostics();
4126 S.LookupName(R, S.getCurScope());
4127
4128 if (R.isSingleResult()) {
4129 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4130 if (FD && FD->getBuiltinID() == AbsKind) {
4131 EmitHeaderHint = false;
4132 } else {
4133 return;
4134 }
4135 } else if (!R.empty()) {
4136 return;
4137 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004138 }
4139 }
4140
4141 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004142 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004143
Richard Trieubeffb832014-04-15 23:47:53 +00004144 if (!HeaderName)
4145 return;
4146
4147 if (!EmitHeaderHint)
4148 return;
4149
Alp Toker5d96e0a2014-07-11 20:53:51 +00004150 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4151 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004152}
4153
4154static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4155 if (!FDecl)
4156 return false;
4157
4158 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4159 return false;
4160
4161 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4162
4163 while (ND && ND->isInlineNamespace()) {
4164 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004165 }
Richard Trieubeffb832014-04-15 23:47:53 +00004166
4167 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4168 return false;
4169
4170 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4171 return false;
4172
4173 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004174}
4175
4176// Warn when using the wrong abs() function.
4177void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4178 const FunctionDecl *FDecl,
4179 IdentifierInfo *FnInfo) {
4180 if (Call->getNumArgs() != 1)
4181 return;
4182
4183 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004184 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4185 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004186 return;
4187
4188 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4189 QualType ParamType = Call->getArg(0)->getType();
4190
Alp Toker5d96e0a2014-07-11 20:53:51 +00004191 // Unsigned types cannot be negative. Suggest removing the absolute value
4192 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004193 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004194 const char *FunctionName =
4195 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004196 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4197 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004198 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004199 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4200 return;
4201 }
4202
Richard Trieubeffb832014-04-15 23:47:53 +00004203 // std::abs has overloads which prevent most of the absolute value problems
4204 // from occurring.
4205 if (IsStdAbs)
4206 return;
4207
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004208 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4209 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4210
4211 // The argument and parameter are the same kind. Check if they are the right
4212 // size.
4213 if (ArgValueKind == ParamValueKind) {
4214 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4215 return;
4216
4217 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4218 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4219 << FDecl << ArgType << ParamType;
4220
4221 if (NewAbsKind == 0)
4222 return;
4223
4224 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004225 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004226 return;
4227 }
4228
4229 // ArgValueKind != ParamValueKind
4230 // The wrong type of absolute value function was used. Attempt to find the
4231 // proper one.
4232 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4233 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4234 if (NewAbsKind == 0)
4235 return;
4236
4237 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4238 << FDecl << ParamValueKind << ArgValueKind;
4239
4240 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004241 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004242 return;
4243}
4244
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004245//===--- CHECK: Standard memory functions ---------------------------------===//
4246
Nico Weber0e6daef2013-12-26 23:38:39 +00004247/// \brief Takes the expression passed to the size_t parameter of functions
4248/// such as memcmp, strncat, etc and warns if it's a comparison.
4249///
4250/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4251static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4252 IdentifierInfo *FnName,
4253 SourceLocation FnLoc,
4254 SourceLocation RParenLoc) {
4255 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4256 if (!Size)
4257 return false;
4258
4259 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4260 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4261 return false;
4262
Nico Weber0e6daef2013-12-26 23:38:39 +00004263 SourceRange SizeRange = Size->getSourceRange();
4264 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4265 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004266 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004267 << FnName << FixItHint::CreateInsertion(
4268 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004269 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004270 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004271 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004272 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4273 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004274
4275 return true;
4276}
4277
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004278/// \brief Determine whether the given type is or contains a dynamic class type
4279/// (e.g., whether it has a vtable).
4280static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4281 bool &IsContained) {
4282 // Look through array types while ignoring qualifiers.
4283 const Type *Ty = T->getBaseElementTypeUnsafe();
4284 IsContained = false;
4285
4286 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4287 RD = RD ? RD->getDefinition() : nullptr;
4288 if (!RD)
4289 return nullptr;
4290
4291 if (RD->isDynamicClass())
4292 return RD;
4293
4294 // Check all the fields. If any bases were dynamic, the class is dynamic.
4295 // It's impossible for a class to transitively contain itself by value, so
4296 // infinite recursion is impossible.
4297 for (auto *FD : RD->fields()) {
4298 bool SubContained;
4299 if (const CXXRecordDecl *ContainedRD =
4300 getContainedDynamicClass(FD->getType(), SubContained)) {
4301 IsContained = true;
4302 return ContainedRD;
4303 }
4304 }
4305
4306 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004307}
4308
Chandler Carruth889ed862011-06-21 23:04:20 +00004309/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004310/// otherwise returns NULL.
4311static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004312 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004313 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4314 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4315 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004316
Craig Topperc3ec1492014-05-26 06:22:03 +00004317 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004318}
4319
Chandler Carruth889ed862011-06-21 23:04:20 +00004320/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004321static QualType getSizeOfArgType(const Expr* E) {
4322 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4323 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4324 if (SizeOf->getKind() == clang::UETT_SizeOf)
4325 return SizeOf->getTypeOfArgument();
4326
4327 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004328}
4329
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004330/// \brief Check for dangerous or invalid arguments to memset().
4331///
Chandler Carruthac687262011-06-03 06:23:57 +00004332/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004333/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4334/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004335///
4336/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004337void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004338 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004339 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004340 assert(BId != 0);
4341
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004342 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004343 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004344 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004345 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004346 return;
4347
Anna Zaks22122702012-01-17 00:37:07 +00004348 unsigned LastArg = (BId == Builtin::BImemset ||
4349 BId == Builtin::BIstrndup ? 1 : 2);
4350 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004351 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004352
Nico Weber0e6daef2013-12-26 23:38:39 +00004353 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4354 Call->getLocStart(), Call->getRParenLoc()))
4355 return;
4356
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004357 // We have special checking when the length is a sizeof expression.
4358 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4359 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4360 llvm::FoldingSetNodeID SizeOfArgID;
4361
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004362 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4363 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004364 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004365
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004366 QualType DestTy = Dest->getType();
4367 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4368 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004369
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004370 // Never warn about void type pointers. This can be used to suppress
4371 // false positives.
4372 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004373 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004374
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004375 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4376 // actually comparing the expressions for equality. Because computing the
4377 // expression IDs can be expensive, we only do this if the diagnostic is
4378 // enabled.
4379 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004380 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4381 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004382 // We only compute IDs for expressions if the warning is enabled, and
4383 // cache the sizeof arg's ID.
4384 if (SizeOfArgID == llvm::FoldingSetNodeID())
4385 SizeOfArg->Profile(SizeOfArgID, Context, true);
4386 llvm::FoldingSetNodeID DestID;
4387 Dest->Profile(DestID, Context, true);
4388 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004389 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4390 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004391 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004392 StringRef ReadableName = FnName->getName();
4393
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004394 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004395 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004396 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004397 if (!PointeeTy->isIncompleteType() &&
4398 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004399 ActionIdx = 2; // If the pointee's size is sizeof(char),
4400 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004401
4402 // If the function is defined as a builtin macro, do not show macro
4403 // expansion.
4404 SourceLocation SL = SizeOfArg->getExprLoc();
4405 SourceRange DSR = Dest->getSourceRange();
4406 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004407 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004408
4409 if (SM.isMacroArgExpansion(SL)) {
4410 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4411 SL = SM.getSpellingLoc(SL);
4412 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4413 SM.getSpellingLoc(DSR.getEnd()));
4414 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4415 SM.getSpellingLoc(SSR.getEnd()));
4416 }
4417
Anna Zaksd08d9152012-05-30 23:14:52 +00004418 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004419 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004420 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004421 << PointeeTy
4422 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004423 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004424 << SSR);
4425 DiagRuntimeBehavior(SL, SizeOfArg,
4426 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4427 << ActionIdx
4428 << SSR);
4429
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004430 break;
4431 }
4432 }
4433
4434 // Also check for cases where the sizeof argument is the exact same
4435 // type as the memory argument, and where it points to a user-defined
4436 // record type.
4437 if (SizeOfArgTy != QualType()) {
4438 if (PointeeTy->isRecordType() &&
4439 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4440 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4441 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4442 << FnName << SizeOfArgTy << ArgIdx
4443 << PointeeTy << Dest->getSourceRange()
4444 << LenExpr->getSourceRange());
4445 break;
4446 }
Nico Weberc5e73862011-06-14 16:14:58 +00004447 }
4448
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004449 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004450 bool IsContained;
4451 if (const CXXRecordDecl *ContainedRD =
4452 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004453
4454 unsigned OperationType = 0;
4455 // "overwritten" if we're warning about the destination for any call
4456 // but memcmp; otherwise a verb appropriate to the call.
4457 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4458 if (BId == Builtin::BImemcpy)
4459 OperationType = 1;
4460 else if(BId == Builtin::BImemmove)
4461 OperationType = 2;
4462 else if (BId == Builtin::BImemcmp)
4463 OperationType = 3;
4464 }
4465
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004466 DiagRuntimeBehavior(
4467 Dest->getExprLoc(), Dest,
4468 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004469 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004470 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004471 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004472 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4473 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004474 DiagRuntimeBehavior(
4475 Dest->getExprLoc(), Dest,
4476 PDiag(diag::warn_arc_object_memaccess)
4477 << ArgIdx << FnName << PointeeTy
4478 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004479 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004480 continue;
John McCall31168b02011-06-15 23:02:42 +00004481
4482 DiagRuntimeBehavior(
4483 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004484 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004485 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4486 break;
4487 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004488 }
4489}
4490
Ted Kremenek6865f772011-08-18 20:55:45 +00004491// A little helper routine: ignore addition and subtraction of integer literals.
4492// This intentionally does not ignore all integer constant expressions because
4493// we don't want to remove sizeof().
4494static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4495 Ex = Ex->IgnoreParenCasts();
4496
4497 for (;;) {
4498 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4499 if (!BO || !BO->isAdditiveOp())
4500 break;
4501
4502 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4503 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4504
4505 if (isa<IntegerLiteral>(RHS))
4506 Ex = LHS;
4507 else if (isa<IntegerLiteral>(LHS))
4508 Ex = RHS;
4509 else
4510 break;
4511 }
4512
4513 return Ex;
4514}
4515
Anna Zaks13b08572012-08-08 21:42:23 +00004516static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4517 ASTContext &Context) {
4518 // Only handle constant-sized or VLAs, but not flexible members.
4519 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4520 // Only issue the FIXIT for arrays of size > 1.
4521 if (CAT->getSize().getSExtValue() <= 1)
4522 return false;
4523 } else if (!Ty->isVariableArrayType()) {
4524 return false;
4525 }
4526 return true;
4527}
4528
Ted Kremenek6865f772011-08-18 20:55:45 +00004529// Warn if the user has made the 'size' argument to strlcpy or strlcat
4530// be the size of the source, instead of the destination.
4531void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4532 IdentifierInfo *FnName) {
4533
4534 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004535 unsigned NumArgs = Call->getNumArgs();
4536 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004537 return;
4538
4539 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4540 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004541 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004542
4543 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4544 Call->getLocStart(), Call->getRParenLoc()))
4545 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004546
4547 // Look for 'strlcpy(dst, x, sizeof(x))'
4548 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4549 CompareWithSrc = Ex;
4550 else {
4551 // Look for 'strlcpy(dst, x, strlen(x))'
4552 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004553 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4554 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004555 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4556 }
4557 }
4558
4559 if (!CompareWithSrc)
4560 return;
4561
4562 // Determine if the argument to sizeof/strlen is equal to the source
4563 // argument. In principle there's all kinds of things you could do
4564 // here, for instance creating an == expression and evaluating it with
4565 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4566 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4567 if (!SrcArgDRE)
4568 return;
4569
4570 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4571 if (!CompareWithSrcDRE ||
4572 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4573 return;
4574
4575 const Expr *OriginalSizeArg = Call->getArg(2);
4576 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4577 << OriginalSizeArg->getSourceRange() << FnName;
4578
4579 // Output a FIXIT hint if the destination is an array (rather than a
4580 // pointer to an array). This could be enhanced to handle some
4581 // pointers if we know the actual size, like if DstArg is 'array+2'
4582 // we could say 'sizeof(array)-2'.
4583 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004584 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004585 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004586
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004587 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004588 llvm::raw_svector_ostream OS(sizeString);
4589 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004590 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004591 OS << ")";
4592
4593 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4594 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4595 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004596}
4597
Anna Zaks314cd092012-02-01 19:08:57 +00004598/// Check if two expressions refer to the same declaration.
4599static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4600 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4601 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4602 return D1->getDecl() == D2->getDecl();
4603 return false;
4604}
4605
4606static const Expr *getStrlenExprArg(const Expr *E) {
4607 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4608 const FunctionDecl *FD = CE->getDirectCallee();
4609 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004610 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004611 return CE->getArg(0)->IgnoreParenCasts();
4612 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004613 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004614}
4615
4616// Warn on anti-patterns as the 'size' argument to strncat.
4617// The correct size argument should look like following:
4618// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4619void Sema::CheckStrncatArguments(const CallExpr *CE,
4620 IdentifierInfo *FnName) {
4621 // Don't crash if the user has the wrong number of arguments.
4622 if (CE->getNumArgs() < 3)
4623 return;
4624 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4625 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4626 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4627
Nico Weber0e6daef2013-12-26 23:38:39 +00004628 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4629 CE->getRParenLoc()))
4630 return;
4631
Anna Zaks314cd092012-02-01 19:08:57 +00004632 // Identify common expressions, which are wrongly used as the size argument
4633 // to strncat and may lead to buffer overflows.
4634 unsigned PatternType = 0;
4635 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4636 // - sizeof(dst)
4637 if (referToTheSameDecl(SizeOfArg, DstArg))
4638 PatternType = 1;
4639 // - sizeof(src)
4640 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4641 PatternType = 2;
4642 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4643 if (BE->getOpcode() == BO_Sub) {
4644 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4645 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4646 // - sizeof(dst) - strlen(dst)
4647 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4648 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4649 PatternType = 1;
4650 // - sizeof(src) - (anything)
4651 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4652 PatternType = 2;
4653 }
4654 }
4655
4656 if (PatternType == 0)
4657 return;
4658
Anna Zaks5069aa32012-02-03 01:27:37 +00004659 // Generate the diagnostic.
4660 SourceLocation SL = LenArg->getLocStart();
4661 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004662 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004663
4664 // If the function is defined as a builtin macro, do not show macro expansion.
4665 if (SM.isMacroArgExpansion(SL)) {
4666 SL = SM.getSpellingLoc(SL);
4667 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4668 SM.getSpellingLoc(SR.getEnd()));
4669 }
4670
Anna Zaks13b08572012-08-08 21:42:23 +00004671 // Check if the destination is an array (rather than a pointer to an array).
4672 QualType DstTy = DstArg->getType();
4673 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4674 Context);
4675 if (!isKnownSizeArray) {
4676 if (PatternType == 1)
4677 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4678 else
4679 Diag(SL, diag::warn_strncat_src_size) << SR;
4680 return;
4681 }
4682
Anna Zaks314cd092012-02-01 19:08:57 +00004683 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004684 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004685 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004686 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004687
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004688 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004689 llvm::raw_svector_ostream OS(sizeString);
4690 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004691 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004692 OS << ") - ";
4693 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004694 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004695 OS << ") - 1";
4696
Anna Zaks5069aa32012-02-03 01:27:37 +00004697 Diag(SL, diag::note_strncat_wrong_size)
4698 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004699}
4700
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004701//===--- CHECK: Return Address of Stack Variable --------------------------===//
4702
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004703static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4704 Decl *ParentDecl);
4705static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4706 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004707
4708/// CheckReturnStackAddr - Check if a return statement returns the address
4709/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004710static void
4711CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4712 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004713
Craig Topperc3ec1492014-05-26 06:22:03 +00004714 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004715 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004716
4717 // Perform checking for returned stack addresses, local blocks,
4718 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004719 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004720 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004721 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004722 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004723 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004724 }
4725
Craig Topperc3ec1492014-05-26 06:22:03 +00004726 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004727 return; // Nothing suspicious was found.
4728
4729 SourceLocation diagLoc;
4730 SourceRange diagRange;
4731 if (refVars.empty()) {
4732 diagLoc = stackE->getLocStart();
4733 diagRange = stackE->getSourceRange();
4734 } else {
4735 // We followed through a reference variable. 'stackE' contains the
4736 // problematic expression but we will warn at the return statement pointing
4737 // at the reference variable. We will later display the "trail" of
4738 // reference variables using notes.
4739 diagLoc = refVars[0]->getLocStart();
4740 diagRange = refVars[0]->getSourceRange();
4741 }
4742
4743 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004744 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004745 : diag::warn_ret_stack_addr)
4746 << DR->getDecl()->getDeclName() << diagRange;
4747 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004748 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004749 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004750 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004751 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004752 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4753 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004754 << diagRange;
4755 }
4756
4757 // Display the "trail" of reference variables that we followed until we
4758 // found the problematic expression using notes.
4759 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4760 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4761 // If this var binds to another reference var, show the range of the next
4762 // var, otherwise the var binds to the problematic expression, in which case
4763 // show the range of the expression.
4764 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4765 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004766 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4767 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004768 }
4769}
4770
4771/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4772/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004773/// to a location on the stack, a local block, an address of a label, or a
4774/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004775/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004776/// encounter a subexpression that (1) clearly does not lead to one of the
4777/// above problematic expressions (2) is something we cannot determine leads to
4778/// a problematic expression based on such local checking.
4779///
4780/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4781/// the expression that they point to. Such variables are added to the
4782/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004783///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004784/// EvalAddr processes expressions that are pointers that are used as
4785/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004786/// At the base case of the recursion is a check for the above problematic
4787/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004788///
4789/// This implementation handles:
4790///
4791/// * pointer-to-pointer casts
4792/// * implicit conversions from array references to pointers
4793/// * taking the address of fields
4794/// * arbitrary interplay between "&" and "*" operators
4795/// * pointer arithmetic from an address of a stack variable
4796/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004797static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4798 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004799 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004800 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004801
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004802 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004803 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004804 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004805 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004806 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004807
Peter Collingbourne91147592011-04-15 00:35:48 +00004808 E = E->IgnoreParens();
4809
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004810 // Our "symbolic interpreter" is just a dispatch off the currently
4811 // viewed AST node. We then recursively traverse the AST by calling
4812 // EvalAddr and EvalVal appropriately.
4813 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004814 case Stmt::DeclRefExprClass: {
4815 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4816
Richard Smith40f08eb2014-01-30 22:05:38 +00004817 // If we leave the immediate function, the lifetime isn't about to end.
4818 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004819 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004820
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004821 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4822 // If this is a reference variable, follow through to the expression that
4823 // it points to.
4824 if (V->hasLocalStorage() &&
4825 V->getType()->isReferenceType() && V->hasInit()) {
4826 // Add the reference variable to the "trail".
4827 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004828 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004829 }
4830
Craig Topperc3ec1492014-05-26 06:22:03 +00004831 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004832 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004833
Chris Lattner934edb22007-12-28 05:31:15 +00004834 case Stmt::UnaryOperatorClass: {
4835 // The only unary operator that make sense to handle here
4836 // is AddrOf. All others don't make sense as pointers.
4837 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004838
John McCalle3027922010-08-25 11:45:40 +00004839 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004840 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004841 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004842 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004843 }
Mike Stump11289f42009-09-09 15:08:12 +00004844
Chris Lattner934edb22007-12-28 05:31:15 +00004845 case Stmt::BinaryOperatorClass: {
4846 // Handle pointer arithmetic. All other binary operators are not valid
4847 // in this context.
4848 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004849 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004850
John McCalle3027922010-08-25 11:45:40 +00004851 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004852 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004853
Chris Lattner934edb22007-12-28 05:31:15 +00004854 Expr *Base = B->getLHS();
4855
4856 // Determine which argument is the real pointer base. It could be
4857 // the RHS argument instead of the LHS.
4858 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004859
Chris Lattner934edb22007-12-28 05:31:15 +00004860 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004861 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004862 }
Steve Naroff2752a172008-09-10 19:17:48 +00004863
Chris Lattner934edb22007-12-28 05:31:15 +00004864 // For conditional operators we need to see if either the LHS or RHS are
4865 // valid DeclRefExpr*s. If one of them is valid, we return it.
4866 case Stmt::ConditionalOperatorClass: {
4867 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004868
Chris Lattner934edb22007-12-28 05:31:15 +00004869 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004870 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4871 if (Expr *LHSExpr = C->getLHS()) {
4872 // In C++, we can have a throw-expression, which has 'void' type.
4873 if (!LHSExpr->getType()->isVoidType())
4874 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004875 return LHS;
4876 }
Chris Lattner934edb22007-12-28 05:31:15 +00004877
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004878 // In C++, we can have a throw-expression, which has 'void' type.
4879 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004880 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004881
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004882 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004883 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004884
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004885 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004886 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004887 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004888 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004889
4890 case Stmt::AddrLabelExprClass:
4891 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004892
John McCall28fc7092011-11-10 05:35:25 +00004893 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004894 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4895 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004896
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004897 // For casts, we need to handle conversions from arrays to
4898 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004899 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004900 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004901 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004902 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004903 case Stmt::CXXStaticCastExprClass:
4904 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004905 case Stmt::CXXConstCastExprClass:
4906 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004907 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4908 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00004909 case CK_LValueToRValue:
4910 case CK_NoOp:
4911 case CK_BaseToDerived:
4912 case CK_DerivedToBase:
4913 case CK_UncheckedDerivedToBase:
4914 case CK_Dynamic:
4915 case CK_CPointerToObjCPointerCast:
4916 case CK_BlockPointerToObjCPointerCast:
4917 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004918 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004919
4920 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004921 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004922
Richard Trieudadefde2014-07-02 04:39:38 +00004923 case CK_BitCast:
4924 if (SubExpr->getType()->isAnyPointerType() ||
4925 SubExpr->getType()->isBlockPointerType() ||
4926 SubExpr->getType()->isObjCQualifiedIdType())
4927 return EvalAddr(SubExpr, refVars, ParentDecl);
4928 else
4929 return nullptr;
4930
Eli Friedman8195ad72012-02-23 23:04:32 +00004931 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004932 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004933 }
Chris Lattner934edb22007-12-28 05:31:15 +00004934 }
Mike Stump11289f42009-09-09 15:08:12 +00004935
Douglas Gregorfe314812011-06-21 17:03:29 +00004936 case Stmt::MaterializeTemporaryExprClass:
4937 if (Expr *Result = EvalAddr(
4938 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004939 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004940 return Result;
4941
4942 return E;
4943
Chris Lattner934edb22007-12-28 05:31:15 +00004944 // Everything else: we simply don't reason about them.
4945 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004946 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004947 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004948}
Mike Stump11289f42009-09-09 15:08:12 +00004949
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004950
4951/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4952/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004953static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4954 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004955do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004956 // We should only be called for evaluating non-pointer expressions, or
4957 // expressions with a pointer type that are not used as references but instead
4958 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004959
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004960 // Our "symbolic interpreter" is just a dispatch off the currently
4961 // viewed AST node. We then recursively traverse the AST by calling
4962 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004963
4964 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004965 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004966 case Stmt::ImplicitCastExprClass: {
4967 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004968 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004969 E = IE->getSubExpr();
4970 continue;
4971 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004972 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004973 }
4974
John McCall28fc7092011-11-10 05:35:25 +00004975 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004976 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004977
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004978 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004979 // When we hit a DeclRefExpr we are looking at code that refers to a
4980 // variable's name. If it's not a reference variable we check if it has
4981 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004982 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004983
Richard Smith40f08eb2014-01-30 22:05:38 +00004984 // If we leave the immediate function, the lifetime isn't about to end.
4985 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004986 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004987
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004988 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4989 // Check if it refers to itself, e.g. "int& i = i;".
4990 if (V == ParentDecl)
4991 return DR;
4992
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004993 if (V->hasLocalStorage()) {
4994 if (!V->getType()->isReferenceType())
4995 return DR;
4996
4997 // Reference variable, follow through to the expression that
4998 // it points to.
4999 if (V->hasInit()) {
5000 // Add the reference variable to the "trail".
5001 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005002 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005003 }
5004 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005005 }
Mike Stump11289f42009-09-09 15:08:12 +00005006
Craig Topperc3ec1492014-05-26 06:22:03 +00005007 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005008 }
Mike Stump11289f42009-09-09 15:08:12 +00005009
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005010 case Stmt::UnaryOperatorClass: {
5011 // The only unary operator that make sense to handle here
5012 // is Deref. All others don't resolve to a "name." This includes
5013 // handling all sorts of rvalues passed to a unary operator.
5014 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005015
John McCalle3027922010-08-25 11:45:40 +00005016 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005017 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005018
Craig Topperc3ec1492014-05-26 06:22:03 +00005019 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005020 }
Mike Stump11289f42009-09-09 15:08:12 +00005021
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005022 case Stmt::ArraySubscriptExprClass: {
5023 // Array subscripts are potential references to data on the stack. We
5024 // retrieve the DeclRefExpr* for the array variable if it indeed
5025 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005026 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005027 }
Mike Stump11289f42009-09-09 15:08:12 +00005028
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005029 case Stmt::ConditionalOperatorClass: {
5030 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005031 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005032 ConditionalOperator *C = cast<ConditionalOperator>(E);
5033
Anders Carlsson801c5c72007-11-30 19:04:31 +00005034 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005035 if (Expr *LHSExpr = C->getLHS()) {
5036 // In C++, we can have a throw-expression, which has 'void' type.
5037 if (!LHSExpr->getType()->isVoidType())
5038 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5039 return LHS;
5040 }
5041
5042 // In C++, we can have a throw-expression, which has 'void' type.
5043 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005044 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005045
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005046 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005047 }
Mike Stump11289f42009-09-09 15:08:12 +00005048
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005049 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005050 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005051 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005052
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005053 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005054 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005055 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005056
5057 // Check whether the member type is itself a reference, in which case
5058 // we're not going to refer to the member, but to what the member refers to.
5059 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005060 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005061
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005062 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005063 }
Mike Stump11289f42009-09-09 15:08:12 +00005064
Douglas Gregorfe314812011-06-21 17:03:29 +00005065 case Stmt::MaterializeTemporaryExprClass:
5066 if (Expr *Result = EvalVal(
5067 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005068 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005069 return Result;
5070
5071 return E;
5072
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005073 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005074 // Check that we don't return or take the address of a reference to a
5075 // temporary. This is only useful in C++.
5076 if (!E->isTypeDependent() && E->isRValue())
5077 return E;
5078
5079 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005080 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005081 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005082} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005083}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005084
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005085void
5086Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5087 SourceLocation ReturnLoc,
5088 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005089 const AttrVec *Attrs,
5090 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005091 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5092
5093 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005094 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5095 CheckNonNullExpr(*this, RetValExp))
5096 Diag(ReturnLoc, diag::warn_null_ret)
5097 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005098
5099 // C++11 [basic.stc.dynamic.allocation]p4:
5100 // If an allocation function declared with a non-throwing
5101 // exception-specification fails to allocate storage, it shall return
5102 // a null pointer. Any other allocation function that fails to allocate
5103 // storage shall indicate failure only by throwing an exception [...]
5104 if (FD) {
5105 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5106 if (Op == OO_New || Op == OO_Array_New) {
5107 const FunctionProtoType *Proto
5108 = FD->getType()->castAs<FunctionProtoType>();
5109 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5110 CheckNonNullExpr(*this, RetValExp))
5111 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5112 << FD << getLangOpts().CPlusPlus11;
5113 }
5114 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005115}
5116
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005117//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5118
5119/// Check for comparisons of floating point operands using != and ==.
5120/// Issue a warning if these are no self-comparisons, as they are not likely
5121/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005122void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005123 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5124 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005125
5126 // Special case: check for x == x (which is OK).
5127 // Do not emit warnings for such cases.
5128 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5129 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5130 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005131 return;
Mike Stump11289f42009-09-09 15:08:12 +00005132
5133
Ted Kremenekeda40e22007-11-29 00:59:04 +00005134 // Special case: check for comparisons against literals that can be exactly
5135 // represented by APFloat. In such cases, do not emit a warning. This
5136 // is a heuristic: often comparison against such literals are used to
5137 // detect if a value in a variable has not changed. This clearly can
5138 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005139 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5140 if (FLL->isExact())
5141 return;
5142 } else
5143 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5144 if (FLR->isExact())
5145 return;
Mike Stump11289f42009-09-09 15:08:12 +00005146
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005147 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005148 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005149 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005150 return;
Mike Stump11289f42009-09-09 15:08:12 +00005151
David Blaikie1f4ff152012-07-16 20:47:22 +00005152 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005153 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005154 return;
Mike Stump11289f42009-09-09 15:08:12 +00005155
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005156 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005157 Diag(Loc, diag::warn_floatingpoint_eq)
5158 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005159}
John McCallca01b222010-01-04 23:21:16 +00005160
John McCall70aa5392010-01-06 05:24:50 +00005161//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5162//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005163
John McCall70aa5392010-01-06 05:24:50 +00005164namespace {
John McCallca01b222010-01-04 23:21:16 +00005165
John McCall70aa5392010-01-06 05:24:50 +00005166/// Structure recording the 'active' range of an integer-valued
5167/// expression.
5168struct IntRange {
5169 /// The number of bits active in the int.
5170 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005171
John McCall70aa5392010-01-06 05:24:50 +00005172 /// True if the int is known not to have negative values.
5173 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005174
John McCall70aa5392010-01-06 05:24:50 +00005175 IntRange(unsigned Width, bool NonNegative)
5176 : Width(Width), NonNegative(NonNegative)
5177 {}
John McCallca01b222010-01-04 23:21:16 +00005178
John McCall817d4af2010-11-10 23:38:19 +00005179 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005180 static IntRange forBoolType() {
5181 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005182 }
5183
John McCall817d4af2010-11-10 23:38:19 +00005184 /// Returns the range of an opaque value of the given integral type.
5185 static IntRange forValueOfType(ASTContext &C, QualType T) {
5186 return forValueOfCanonicalType(C,
5187 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005188 }
5189
John McCall817d4af2010-11-10 23:38:19 +00005190 /// Returns the range of an opaque value of a canonical integral type.
5191 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005192 assert(T->isCanonicalUnqualified());
5193
5194 if (const VectorType *VT = dyn_cast<VectorType>(T))
5195 T = VT->getElementType().getTypePtr();
5196 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5197 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005198 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5199 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005200
David Majnemer6a426652013-06-07 22:07:20 +00005201 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005202 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005203 EnumDecl *Enum = ET->getDecl();
5204 if (!Enum->isCompleteDefinition())
5205 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005206
David Majnemer6a426652013-06-07 22:07:20 +00005207 unsigned NumPositive = Enum->getNumPositiveBits();
5208 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005209
David Majnemer6a426652013-06-07 22:07:20 +00005210 if (NumNegative == 0)
5211 return IntRange(NumPositive, true/*NonNegative*/);
5212 else
5213 return IntRange(std::max(NumPositive + 1, NumNegative),
5214 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005215 }
John McCall70aa5392010-01-06 05:24:50 +00005216
5217 const BuiltinType *BT = cast<BuiltinType>(T);
5218 assert(BT->isInteger());
5219
5220 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5221 }
5222
John McCall817d4af2010-11-10 23:38:19 +00005223 /// Returns the "target" range of a canonical integral type, i.e.
5224 /// the range of values expressible in the type.
5225 ///
5226 /// This matches forValueOfCanonicalType except that enums have the
5227 /// full range of their type, not the range of their enumerators.
5228 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5229 assert(T->isCanonicalUnqualified());
5230
5231 if (const VectorType *VT = dyn_cast<VectorType>(T))
5232 T = VT->getElementType().getTypePtr();
5233 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5234 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005235 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5236 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005237 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005238 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005239
5240 const BuiltinType *BT = cast<BuiltinType>(T);
5241 assert(BT->isInteger());
5242
5243 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5244 }
5245
5246 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005247 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005248 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005249 L.NonNegative && R.NonNegative);
5250 }
5251
John McCall817d4af2010-11-10 23:38:19 +00005252 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005253 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005254 return IntRange(std::min(L.Width, R.Width),
5255 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005256 }
5257};
5258
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005259static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5260 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005261 if (value.isSigned() && value.isNegative())
5262 return IntRange(value.getMinSignedBits(), false);
5263
5264 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005265 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005266
5267 // isNonNegative() just checks the sign bit without considering
5268 // signedness.
5269 return IntRange(value.getActiveBits(), true);
5270}
5271
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005272static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5273 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005274 if (result.isInt())
5275 return GetValueRange(C, result.getInt(), MaxWidth);
5276
5277 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005278 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5279 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5280 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5281 R = IntRange::join(R, El);
5282 }
John McCall70aa5392010-01-06 05:24:50 +00005283 return R;
5284 }
5285
5286 if (result.isComplexInt()) {
5287 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5288 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5289 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005290 }
5291
5292 // This can happen with lossless casts to intptr_t of "based" lvalues.
5293 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005294 // FIXME: The only reason we need to pass the type in here is to get
5295 // the sign right on this one case. It would be nice if APValue
5296 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005297 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005298 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005299}
John McCall70aa5392010-01-06 05:24:50 +00005300
Eli Friedmane6d33952013-07-08 20:20:06 +00005301static QualType GetExprType(Expr *E) {
5302 QualType Ty = E->getType();
5303 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5304 Ty = AtomicRHS->getValueType();
5305 return Ty;
5306}
5307
John McCall70aa5392010-01-06 05:24:50 +00005308/// Pseudo-evaluate the given integer expression, estimating the
5309/// range of values it might take.
5310///
5311/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005312static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005313 E = E->IgnoreParens();
5314
5315 // Try a full evaluation first.
5316 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005317 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005318 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005319
5320 // I think we only want to look through implicit casts here; if the
5321 // user has an explicit widening cast, we should treat the value as
5322 // being of the new, wider type.
5323 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005324 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005325 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5326
Eli Friedmane6d33952013-07-08 20:20:06 +00005327 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005328
John McCalle3027922010-08-25 11:45:40 +00005329 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005330
John McCall70aa5392010-01-06 05:24:50 +00005331 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005332 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005333 return OutputTypeRange;
5334
5335 IntRange SubRange
5336 = GetExprRange(C, CE->getSubExpr(),
5337 std::min(MaxWidth, OutputTypeRange.Width));
5338
5339 // Bail out if the subexpr's range is as wide as the cast type.
5340 if (SubRange.Width >= OutputTypeRange.Width)
5341 return OutputTypeRange;
5342
5343 // Otherwise, we take the smaller width, and we're non-negative if
5344 // either the output type or the subexpr is.
5345 return IntRange(SubRange.Width,
5346 SubRange.NonNegative || OutputTypeRange.NonNegative);
5347 }
5348
5349 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5350 // If we can fold the condition, just take that operand.
5351 bool CondResult;
5352 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5353 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5354 : CO->getFalseExpr(),
5355 MaxWidth);
5356
5357 // Otherwise, conservatively merge.
5358 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5359 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5360 return IntRange::join(L, R);
5361 }
5362
5363 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5364 switch (BO->getOpcode()) {
5365
5366 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005367 case BO_LAnd:
5368 case BO_LOr:
5369 case BO_LT:
5370 case BO_GT:
5371 case BO_LE:
5372 case BO_GE:
5373 case BO_EQ:
5374 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005375 return IntRange::forBoolType();
5376
John McCallc3688382011-07-13 06:35:24 +00005377 // The type of the assignments is the type of the LHS, so the RHS
5378 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005379 case BO_MulAssign:
5380 case BO_DivAssign:
5381 case BO_RemAssign:
5382 case BO_AddAssign:
5383 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005384 case BO_XorAssign:
5385 case BO_OrAssign:
5386 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005387 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005388
John McCallc3688382011-07-13 06:35:24 +00005389 // Simple assignments just pass through the RHS, which will have
5390 // been coerced to the LHS type.
5391 case BO_Assign:
5392 // TODO: bitfields?
5393 return GetExprRange(C, BO->getRHS(), MaxWidth);
5394
John McCall70aa5392010-01-06 05:24:50 +00005395 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005396 case BO_PtrMemD:
5397 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005398 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005399
John McCall2ce81ad2010-01-06 22:07:33 +00005400 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005401 case BO_And:
5402 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005403 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5404 GetExprRange(C, BO->getRHS(), MaxWidth));
5405
John McCall70aa5392010-01-06 05:24:50 +00005406 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005407 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005408 // ...except that we want to treat '1 << (blah)' as logically
5409 // positive. It's an important idiom.
5410 if (IntegerLiteral *I
5411 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5412 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005413 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005414 return IntRange(R.Width, /*NonNegative*/ true);
5415 }
5416 }
5417 // fallthrough
5418
John McCalle3027922010-08-25 11:45:40 +00005419 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005420 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005421
John McCall2ce81ad2010-01-06 22:07:33 +00005422 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005423 case BO_Shr:
5424 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005425 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5426
5427 // If the shift amount is a positive constant, drop the width by
5428 // that much.
5429 llvm::APSInt shift;
5430 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5431 shift.isNonNegative()) {
5432 unsigned zext = shift.getZExtValue();
5433 if (zext >= L.Width)
5434 L.Width = (L.NonNegative ? 0 : 1);
5435 else
5436 L.Width -= zext;
5437 }
5438
5439 return L;
5440 }
5441
5442 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005443 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005444 return GetExprRange(C, BO->getRHS(), MaxWidth);
5445
John McCall2ce81ad2010-01-06 22:07:33 +00005446 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005447 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005448 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005449 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005450 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005451
John McCall51431812011-07-14 22:39:48 +00005452 // The width of a division result is mostly determined by the size
5453 // of the LHS.
5454 case BO_Div: {
5455 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005456 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005457 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5458
5459 // If the divisor is constant, use that.
5460 llvm::APSInt divisor;
5461 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5462 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5463 if (log2 >= L.Width)
5464 L.Width = (L.NonNegative ? 0 : 1);
5465 else
5466 L.Width = std::min(L.Width - log2, MaxWidth);
5467 return L;
5468 }
5469
5470 // Otherwise, just use the LHS's width.
5471 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5472 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5473 }
5474
5475 // The result of a remainder can't be larger than the result of
5476 // either side.
5477 case BO_Rem: {
5478 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005479 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005480 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5481 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5482
5483 IntRange meet = IntRange::meet(L, R);
5484 meet.Width = std::min(meet.Width, MaxWidth);
5485 return meet;
5486 }
5487
5488 // The default behavior is okay for these.
5489 case BO_Mul:
5490 case BO_Add:
5491 case BO_Xor:
5492 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005493 break;
5494 }
5495
John McCall51431812011-07-14 22:39:48 +00005496 // The default case is to treat the operation as if it were closed
5497 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005498 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5499 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5500 return IntRange::join(L, R);
5501 }
5502
5503 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5504 switch (UO->getOpcode()) {
5505 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005506 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005507 return IntRange::forBoolType();
5508
5509 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005510 case UO_Deref:
5511 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005512 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005513
5514 default:
5515 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5516 }
5517 }
5518
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005519 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5520 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5521
John McCalld25db7e2013-05-06 21:39:12 +00005522 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005523 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005524 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005525
Eli Friedmane6d33952013-07-08 20:20:06 +00005526 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005527}
John McCall263a48b2010-01-04 23:31:57 +00005528
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005529static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005530 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005531}
5532
John McCall263a48b2010-01-04 23:31:57 +00005533/// Checks whether the given value, which currently has the given
5534/// source semantics, has the same value when coerced through the
5535/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005536static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5537 const llvm::fltSemantics &Src,
5538 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005539 llvm::APFloat truncated = value;
5540
5541 bool ignored;
5542 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5543 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5544
5545 return truncated.bitwiseIsEqual(value);
5546}
5547
5548/// Checks whether the given value, which currently has the given
5549/// source semantics, has the same value when coerced through the
5550/// target semantics.
5551///
5552/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005553static bool IsSameFloatAfterCast(const APValue &value,
5554 const llvm::fltSemantics &Src,
5555 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005556 if (value.isFloat())
5557 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5558
5559 if (value.isVector()) {
5560 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5561 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5562 return false;
5563 return true;
5564 }
5565
5566 assert(value.isComplexFloat());
5567 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5568 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5569}
5570
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005571static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005572
Ted Kremenek6274be42010-09-23 21:43:44 +00005573static bool IsZero(Sema &S, Expr *E) {
5574 // Suppress cases where we are comparing against an enum constant.
5575 if (const DeclRefExpr *DR =
5576 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5577 if (isa<EnumConstantDecl>(DR->getDecl()))
5578 return false;
5579
5580 // Suppress cases where the '0' value is expanded from a macro.
5581 if (E->getLocStart().isMacroID())
5582 return false;
5583
John McCallcc7e5bf2010-05-06 08:58:33 +00005584 llvm::APSInt Value;
5585 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5586}
5587
John McCall2551c1b2010-10-06 00:25:24 +00005588static bool HasEnumType(Expr *E) {
5589 // Strip off implicit integral promotions.
5590 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005591 if (ICE->getCastKind() != CK_IntegralCast &&
5592 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005593 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005594 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005595 }
5596
5597 return E->getType()->isEnumeralType();
5598}
5599
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005600static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005601 // Disable warning in template instantiations.
5602 if (!S.ActiveTemplateInstantiations.empty())
5603 return;
5604
John McCalle3027922010-08-25 11:45:40 +00005605 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005606 if (E->isValueDependent())
5607 return;
5608
John McCalle3027922010-08-25 11:45:40 +00005609 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005610 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005611 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005612 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005613 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005614 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005615 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005616 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005617 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005618 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005619 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005620 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005621 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005622 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005623 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005624 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5625 }
5626}
5627
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005628static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005629 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005630 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005631 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005632 // Disable warning in template instantiations.
5633 if (!S.ActiveTemplateInstantiations.empty())
5634 return;
5635
Richard Trieu0f097742014-04-04 04:13:47 +00005636 // TODO: Investigate using GetExprRange() to get tighter bounds
5637 // on the bit ranges.
5638 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005639 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5640 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005641 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5642 unsigned OtherWidth = OtherRange.Width;
5643
5644 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5645
Richard Trieu560910c2012-11-14 22:50:24 +00005646 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005647 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005648 return;
5649
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005650 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005651 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005652
Richard Trieu0f097742014-04-04 04:13:47 +00005653 // Used for diagnostic printout.
5654 enum {
5655 LiteralConstant = 0,
5656 CXXBoolLiteralTrue,
5657 CXXBoolLiteralFalse
5658 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005659
Richard Trieu0f097742014-04-04 04:13:47 +00005660 if (!OtherIsBooleanType) {
5661 QualType ConstantT = Constant->getType();
5662 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005663
Richard Trieu0f097742014-04-04 04:13:47 +00005664 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5665 return;
5666 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5667 "comparison with non-integer type");
5668
5669 bool ConstantSigned = ConstantT->isSignedIntegerType();
5670 bool CommonSigned = CommonT->isSignedIntegerType();
5671
5672 bool EqualityOnly = false;
5673
5674 if (CommonSigned) {
5675 // The common type is signed, therefore no signed to unsigned conversion.
5676 if (!OtherRange.NonNegative) {
5677 // Check that the constant is representable in type OtherT.
5678 if (ConstantSigned) {
5679 if (OtherWidth >= Value.getMinSignedBits())
5680 return;
5681 } else { // !ConstantSigned
5682 if (OtherWidth >= Value.getActiveBits() + 1)
5683 return;
5684 }
5685 } else { // !OtherSigned
5686 // Check that the constant is representable in type OtherT.
5687 // Negative values are out of range.
5688 if (ConstantSigned) {
5689 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5690 return;
5691 } else { // !ConstantSigned
5692 if (OtherWidth >= Value.getActiveBits())
5693 return;
5694 }
Richard Trieu560910c2012-11-14 22:50:24 +00005695 }
Richard Trieu0f097742014-04-04 04:13:47 +00005696 } else { // !CommonSigned
5697 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005698 if (OtherWidth >= Value.getActiveBits())
5699 return;
Craig Toppercf360162014-06-18 05:13:11 +00005700 } else { // OtherSigned
5701 assert(!ConstantSigned &&
5702 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005703 // Check to see if the constant is representable in OtherT.
5704 if (OtherWidth > Value.getActiveBits())
5705 return;
5706 // Check to see if the constant is equivalent to a negative value
5707 // cast to CommonT.
5708 if (S.Context.getIntWidth(ConstantT) ==
5709 S.Context.getIntWidth(CommonT) &&
5710 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5711 return;
5712 // The constant value rests between values that OtherT can represent
5713 // after conversion. Relational comparison still works, but equality
5714 // comparisons will be tautological.
5715 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005716 }
5717 }
Richard Trieu0f097742014-04-04 04:13:47 +00005718
5719 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5720
5721 if (op == BO_EQ || op == BO_NE) {
5722 IsTrue = op == BO_NE;
5723 } else if (EqualityOnly) {
5724 return;
5725 } else if (RhsConstant) {
5726 if (op == BO_GT || op == BO_GE)
5727 IsTrue = !PositiveConstant;
5728 else // op == BO_LT || op == BO_LE
5729 IsTrue = PositiveConstant;
5730 } else {
5731 if (op == BO_LT || op == BO_LE)
5732 IsTrue = !PositiveConstant;
5733 else // op == BO_GT || op == BO_GE
5734 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005735 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005736 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005737 // Other isKnownToHaveBooleanValue
5738 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5739 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5740 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5741
5742 static const struct LinkedConditions {
5743 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5744 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5745 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5746 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5747 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5748 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5749
5750 } TruthTable = {
5751 // Constant on LHS. | Constant on RHS. |
5752 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5753 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5754 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5755 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5756 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5757 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5758 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5759 };
5760
5761 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5762
5763 enum ConstantValue ConstVal = Zero;
5764 if (Value.isUnsigned() || Value.isNonNegative()) {
5765 if (Value == 0) {
5766 LiteralOrBoolConstant =
5767 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5768 ConstVal = Zero;
5769 } else if (Value == 1) {
5770 LiteralOrBoolConstant =
5771 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5772 ConstVal = One;
5773 } else {
5774 LiteralOrBoolConstant = LiteralConstant;
5775 ConstVal = GT_One;
5776 }
5777 } else {
5778 ConstVal = LT_Zero;
5779 }
5780
5781 CompareBoolWithConstantResult CmpRes;
5782
5783 switch (op) {
5784 case BO_LT:
5785 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5786 break;
5787 case BO_GT:
5788 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5789 break;
5790 case BO_LE:
5791 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5792 break;
5793 case BO_GE:
5794 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5795 break;
5796 case BO_EQ:
5797 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5798 break;
5799 case BO_NE:
5800 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5801 break;
5802 default:
5803 CmpRes = Unkwn;
5804 break;
5805 }
5806
5807 if (CmpRes == AFals) {
5808 IsTrue = false;
5809 } else if (CmpRes == ATrue) {
5810 IsTrue = true;
5811 } else {
5812 return;
5813 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005814 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005815
5816 // If this is a comparison to an enum constant, include that
5817 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005818 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005819 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5820 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5821
5822 SmallString<64> PrettySourceValue;
5823 llvm::raw_svector_ostream OS(PrettySourceValue);
5824 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005825 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005826 else
5827 OS << Value;
5828
Richard Trieu0f097742014-04-04 04:13:47 +00005829 S.DiagRuntimeBehavior(
5830 E->getOperatorLoc(), E,
5831 S.PDiag(diag::warn_out_of_range_compare)
5832 << OS.str() << LiteralOrBoolConstant
5833 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5834 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005835}
5836
John McCallcc7e5bf2010-05-06 08:58:33 +00005837/// Analyze the operands of the given comparison. Implements the
5838/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005839static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005840 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5841 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005842}
John McCall263a48b2010-01-04 23:31:57 +00005843
John McCallca01b222010-01-04 23:21:16 +00005844/// \brief Implements -Wsign-compare.
5845///
Richard Trieu82402a02011-09-15 21:56:47 +00005846/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005847static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005848 // The type the comparison is being performed in.
5849 QualType T = E->getLHS()->getType();
5850 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5851 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005852 if (E->isValueDependent())
5853 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005854
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005855 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5856 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005857
5858 bool IsComparisonConstant = false;
5859
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005860 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005861 // of 'true' or 'false'.
5862 if (T->isIntegralType(S.Context)) {
5863 llvm::APSInt RHSValue;
5864 bool IsRHSIntegralLiteral =
5865 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5866 llvm::APSInt LHSValue;
5867 bool IsLHSIntegralLiteral =
5868 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5869 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5870 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5871 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5872 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5873 else
5874 IsComparisonConstant =
5875 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005876 } else if (!T->hasUnsignedIntegerRepresentation())
5877 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005878
John McCallcc7e5bf2010-05-06 08:58:33 +00005879 // We don't do anything special if this isn't an unsigned integral
5880 // comparison: we're only interested in integral comparisons, and
5881 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005882 //
5883 // We also don't care about value-dependent expressions or expressions
5884 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005885 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005886 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005887
John McCallcc7e5bf2010-05-06 08:58:33 +00005888 // Check to see if one of the (unmodified) operands is of different
5889 // signedness.
5890 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005891 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5892 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005893 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005894 signedOperand = LHS;
5895 unsignedOperand = RHS;
5896 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5897 signedOperand = RHS;
5898 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005899 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005900 CheckTrivialUnsignedComparison(S, E);
5901 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005902 }
5903
John McCallcc7e5bf2010-05-06 08:58:33 +00005904 // Otherwise, calculate the effective range of the signed operand.
5905 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005906
John McCallcc7e5bf2010-05-06 08:58:33 +00005907 // Go ahead and analyze implicit conversions in the operands. Note
5908 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005909 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5910 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005911
John McCallcc7e5bf2010-05-06 08:58:33 +00005912 // If the signed range is non-negative, -Wsign-compare won't fire,
5913 // but we should still check for comparisons which are always true
5914 // or false.
5915 if (signedRange.NonNegative)
5916 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005917
5918 // For (in)equality comparisons, if the unsigned operand is a
5919 // constant which cannot collide with a overflowed signed operand,
5920 // then reinterpreting the signed operand as unsigned will not
5921 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005922 if (E->isEqualityOp()) {
5923 unsigned comparisonWidth = S.Context.getIntWidth(T);
5924 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005925
John McCallcc7e5bf2010-05-06 08:58:33 +00005926 // We should never be unable to prove that the unsigned operand is
5927 // non-negative.
5928 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5929
5930 if (unsignedRange.Width < comparisonWidth)
5931 return;
5932 }
5933
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005934 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5935 S.PDiag(diag::warn_mixed_sign_comparison)
5936 << LHS->getType() << RHS->getType()
5937 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005938}
5939
John McCall1f425642010-11-11 03:21:53 +00005940/// Analyzes an attempt to assign the given value to a bitfield.
5941///
5942/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005943static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5944 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005945 assert(Bitfield->isBitField());
5946 if (Bitfield->isInvalidDecl())
5947 return false;
5948
John McCalldeebbcf2010-11-11 05:33:51 +00005949 // White-list bool bitfields.
5950 if (Bitfield->getType()->isBooleanType())
5951 return false;
5952
Douglas Gregor789adec2011-02-04 13:09:01 +00005953 // Ignore value- or type-dependent expressions.
5954 if (Bitfield->getBitWidth()->isValueDependent() ||
5955 Bitfield->getBitWidth()->isTypeDependent() ||
5956 Init->isValueDependent() ||
5957 Init->isTypeDependent())
5958 return false;
5959
John McCall1f425642010-11-11 03:21:53 +00005960 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5961
Richard Smith5fab0c92011-12-28 19:48:30 +00005962 llvm::APSInt Value;
5963 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005964 return false;
5965
John McCall1f425642010-11-11 03:21:53 +00005966 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005967 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005968
5969 if (OriginalWidth <= FieldWidth)
5970 return false;
5971
Eli Friedmanc267a322012-01-26 23:11:39 +00005972 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005973 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005974 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005975
Eli Friedmanc267a322012-01-26 23:11:39 +00005976 // Check whether the stored value is equal to the original value.
5977 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005978 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005979 return false;
5980
Eli Friedmanc267a322012-01-26 23:11:39 +00005981 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005982 // therefore don't strictly fit into a signed bitfield of width 1.
5983 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005984 return false;
5985
John McCall1f425642010-11-11 03:21:53 +00005986 std::string PrettyValue = Value.toString(10);
5987 std::string PrettyTrunc = TruncatedValue.toString(10);
5988
5989 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5990 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5991 << Init->getSourceRange();
5992
5993 return true;
5994}
5995
John McCalld2a53122010-11-09 23:24:47 +00005996/// Analyze the given simple or compound assignment for warning-worthy
5997/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005998static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005999 // Just recurse on the LHS.
6000 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6001
6002 // We want to recurse on the RHS as normal unless we're assigning to
6003 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006004 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006005 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006006 E->getOperatorLoc())) {
6007 // Recurse, ignoring any implicit conversions on the RHS.
6008 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6009 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006010 }
6011 }
6012
6013 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6014}
6015
John McCall263a48b2010-01-04 23:31:57 +00006016/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006017static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006018 SourceLocation CContext, unsigned diag,
6019 bool pruneControlFlow = false) {
6020 if (pruneControlFlow) {
6021 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6022 S.PDiag(diag)
6023 << SourceType << T << E->getSourceRange()
6024 << SourceRange(CContext));
6025 return;
6026 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006027 S.Diag(E->getExprLoc(), diag)
6028 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6029}
6030
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006031/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006032static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006033 SourceLocation CContext, unsigned diag,
6034 bool pruneControlFlow = false) {
6035 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006036}
6037
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006038/// Diagnose an implicit cast from a literal expression. Does not warn when the
6039/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006040void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6041 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006042 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006043 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006044 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006045 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6046 T->hasUnsignedIntegerRepresentation());
6047 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006048 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006049 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006050 return;
6051
Eli Friedman07185912013-08-29 23:44:43 +00006052 // FIXME: Force the precision of the source value down so we don't print
6053 // digits which are usually useless (we don't really care here if we
6054 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6055 // would automatically print the shortest representation, but it's a bit
6056 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006057 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006058 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6059 precision = (precision * 59 + 195) / 196;
6060 Value.toString(PrettySourceValue, precision);
6061
David Blaikie9b88cc02012-05-15 17:18:27 +00006062 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006063 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6064 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6065 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006066 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006067
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006068 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006069 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6070 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006071}
6072
John McCall18a2c2c2010-11-09 22:22:12 +00006073std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6074 if (!Range.Width) return "0";
6075
6076 llvm::APSInt ValueInRange = Value;
6077 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006078 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006079 return ValueInRange.toString(10);
6080}
6081
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006082static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6083 if (!isa<ImplicitCastExpr>(Ex))
6084 return false;
6085
6086 Expr *InnerE = Ex->IgnoreParenImpCasts();
6087 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6088 const Type *Source =
6089 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6090 if (Target->isDependentType())
6091 return false;
6092
6093 const BuiltinType *FloatCandidateBT =
6094 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6095 const Type *BoolCandidateType = ToBool ? Target : Source;
6096
6097 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6098 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6099}
6100
6101void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6102 SourceLocation CC) {
6103 unsigned NumArgs = TheCall->getNumArgs();
6104 for (unsigned i = 0; i < NumArgs; ++i) {
6105 Expr *CurrA = TheCall->getArg(i);
6106 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6107 continue;
6108
6109 bool IsSwapped = ((i > 0) &&
6110 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6111 IsSwapped |= ((i < (NumArgs - 1)) &&
6112 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6113 if (IsSwapped) {
6114 // Warn on this floating-point to bool conversion.
6115 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6116 CurrA->getType(), CC,
6117 diag::warn_impcast_floating_point_to_bool);
6118 }
6119 }
6120}
6121
John McCallcc7e5bf2010-05-06 08:58:33 +00006122void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006123 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006124 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006125
John McCallcc7e5bf2010-05-06 08:58:33 +00006126 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6127 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6128 if (Source == Target) return;
6129 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006130
Chandler Carruthc22845a2011-07-26 05:40:03 +00006131 // If the conversion context location is invalid don't complain. We also
6132 // don't want to emit a warning if the issue occurs from the expansion of
6133 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6134 // delay this check as long as possible. Once we detect we are in that
6135 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006136 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006137 return;
6138
Richard Trieu021baa32011-09-23 20:10:00 +00006139 // Diagnose implicit casts to bool.
6140 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6141 if (isa<StringLiteral>(E))
6142 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006143 // and expressions, for instance, assert(0 && "error here"), are
6144 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006145 return DiagnoseImpCast(S, E, T, CC,
6146 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006147 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6148 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6149 // This covers the literal expressions that evaluate to Objective-C
6150 // objects.
6151 return DiagnoseImpCast(S, E, T, CC,
6152 diag::warn_impcast_objective_c_literal_to_bool);
6153 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006154 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6155 // Warn on pointer to bool conversion that is always true.
6156 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6157 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006158 }
Richard Trieu021baa32011-09-23 20:10:00 +00006159 }
John McCall263a48b2010-01-04 23:31:57 +00006160
6161 // Strip vector types.
6162 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006163 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006164 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006165 return;
John McCallacf0ee52010-10-08 02:01:28 +00006166 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006167 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006168
6169 // If the vector cast is cast between two vectors of the same size, it is
6170 // a bitcast, not a conversion.
6171 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6172 return;
John McCall263a48b2010-01-04 23:31:57 +00006173
6174 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6175 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6176 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006177 if (auto VecTy = dyn_cast<VectorType>(Target))
6178 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006179
6180 // Strip complex types.
6181 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006182 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006183 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006184 return;
6185
John McCallacf0ee52010-10-08 02:01:28 +00006186 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006187 }
John McCall263a48b2010-01-04 23:31:57 +00006188
6189 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6190 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6191 }
6192
6193 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6194 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6195
6196 // If the source is floating point...
6197 if (SourceBT && SourceBT->isFloatingPoint()) {
6198 // ...and the target is floating point...
6199 if (TargetBT && TargetBT->isFloatingPoint()) {
6200 // ...then warn if we're dropping FP rank.
6201
6202 // Builtin FP kinds are ordered by increasing FP rank.
6203 if (SourceBT->getKind() > TargetBT->getKind()) {
6204 // Don't warn about float constants that are precisely
6205 // representable in the target type.
6206 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006207 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006208 // Value might be a float, a float vector, or a float complex.
6209 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006210 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6211 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006212 return;
6213 }
6214
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006215 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006216 return;
6217
John McCallacf0ee52010-10-08 02:01:28 +00006218 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006219 }
6220 return;
6221 }
6222
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006223 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006224 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006225 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006226 return;
6227
Chandler Carruth22c7a792011-02-17 11:05:49 +00006228 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006229 // We also want to warn on, e.g., "int i = -1.234"
6230 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6231 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6232 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6233
Chandler Carruth016ef402011-04-10 08:36:24 +00006234 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6235 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006236 } else {
6237 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6238 }
6239 }
John McCall263a48b2010-01-04 23:31:57 +00006240
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006241 // If the target is bool, warn if expr is a function or method call.
6242 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6243 isa<CallExpr>(E)) {
6244 // Check last argument of function call to see if it is an
6245 // implicit cast from a type matching the type the result
6246 // is being cast to.
6247 CallExpr *CEx = cast<CallExpr>(E);
6248 unsigned NumArgs = CEx->getNumArgs();
6249 if (NumArgs > 0) {
6250 Expr *LastA = CEx->getArg(NumArgs - 1);
6251 Expr *InnerE = LastA->IgnoreParenImpCasts();
6252 const Type *InnerType =
6253 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6254 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6255 // Warn on this floating-point to bool conversion
6256 DiagnoseImpCast(S, E, T, CC,
6257 diag::warn_impcast_floating_point_to_bool);
6258 }
6259 }
6260 }
John McCall263a48b2010-01-04 23:31:57 +00006261 return;
6262 }
6263
Richard Trieubeaf3452011-05-29 19:59:02 +00006264 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00006265 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00006266 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00006267 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00006268 SourceLocation Loc = E->getSourceRange().getBegin();
6269 if (Loc.isMacroID())
6270 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00006271 if (!Loc.isMacroID() || CC.isMacroID())
6272 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6273 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00006274 << FixItHint::CreateReplacement(Loc,
6275 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00006276 }
6277
David Blaikie9366d2b2012-06-19 21:19:06 +00006278 if (!Source->isIntegerType() || !Target->isIntegerType())
6279 return;
6280
David Blaikie7555b6a2012-05-15 16:56:36 +00006281 // TODO: remove this early return once the false positives for constant->bool
6282 // in templates, macros, etc, are reduced or removed.
6283 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6284 return;
6285
John McCallcc7e5bf2010-05-06 08:58:33 +00006286 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006287 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006288
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006289 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006290 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006291 // TODO: this should happen for bitfield stores, too.
6292 llvm::APSInt Value(32);
6293 if (E->isIntegerConstantExpr(Value, S.Context)) {
6294 if (S.SourceMgr.isInSystemMacro(CC))
6295 return;
6296
John McCall18a2c2c2010-11-09 22:22:12 +00006297 std::string PrettySourceValue = Value.toString(10);
6298 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006299
Ted Kremenek33ba9952011-10-22 02:37:33 +00006300 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6301 S.PDiag(diag::warn_impcast_integer_precision_constant)
6302 << PrettySourceValue << PrettyTargetValue
6303 << E->getType() << T << E->getSourceRange()
6304 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006305 return;
6306 }
6307
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006308 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6309 if (S.SourceMgr.isInSystemMacro(CC))
6310 return;
6311
David Blaikie9455da02012-04-12 22:40:54 +00006312 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006313 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6314 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006315 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006316 }
6317
6318 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6319 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6320 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006321
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006322 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006323 return;
6324
John McCallcc7e5bf2010-05-06 08:58:33 +00006325 unsigned DiagID = diag::warn_impcast_integer_sign;
6326
6327 // Traditionally, gcc has warned about this under -Wsign-compare.
6328 // We also want to warn about it in -Wconversion.
6329 // So if -Wconversion is off, use a completely identical diagnostic
6330 // in the sign-compare group.
6331 // The conditional-checking code will
6332 if (ICContext) {
6333 DiagID = diag::warn_impcast_integer_sign_conditional;
6334 *ICContext = true;
6335 }
6336
John McCallacf0ee52010-10-08 02:01:28 +00006337 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006338 }
6339
Douglas Gregora78f1932011-02-22 02:45:07 +00006340 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006341 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6342 // type, to give us better diagnostics.
6343 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006344 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006345 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6346 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6347 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6348 SourceType = S.Context.getTypeDeclType(Enum);
6349 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6350 }
6351 }
6352
Douglas Gregora78f1932011-02-22 02:45:07 +00006353 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6354 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006355 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6356 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006357 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006358 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006359 return;
6360
Douglas Gregor364f7db2011-03-12 00:14:31 +00006361 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006362 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006363 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006364
John McCall263a48b2010-01-04 23:31:57 +00006365 return;
6366}
6367
David Blaikie18e9ac72012-05-15 21:57:38 +00006368void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6369 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006370
6371void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006372 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006373 E = E->IgnoreParenImpCasts();
6374
6375 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006376 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006377
John McCallacf0ee52010-10-08 02:01:28 +00006378 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006379 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006380 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006381 return;
6382}
6383
David Blaikie18e9ac72012-05-15 21:57:38 +00006384void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6385 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006386 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006387
6388 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006389 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6390 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006391
6392 // If -Wconversion would have warned about either of the candidates
6393 // for a signedness conversion to the context type...
6394 if (!Suspicious) return;
6395
6396 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006397 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006398 return;
6399
John McCallcc7e5bf2010-05-06 08:58:33 +00006400 // ...then check whether it would have warned about either of the
6401 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006402 if (E->getType() == T) return;
6403
6404 Suspicious = false;
6405 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6406 E->getType(), CC, &Suspicious);
6407 if (!Suspicious)
6408 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006409 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006410}
6411
6412/// AnalyzeImplicitConversions - Find and report any interesting
6413/// implicit conversions in the given expression. There are a couple
6414/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006415void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006416 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006417 Expr *E = OrigE->IgnoreParenImpCasts();
6418
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006419 if (E->isTypeDependent() || E->isValueDependent())
6420 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006421
John McCallcc7e5bf2010-05-06 08:58:33 +00006422 // For conditional operators, we analyze the arguments as if they
6423 // were being fed directly into the output.
6424 if (isa<ConditionalOperator>(E)) {
6425 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006426 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006427 return;
6428 }
6429
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006430 // Check implicit argument conversions for function calls.
6431 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6432 CheckImplicitArgumentConversions(S, Call, CC);
6433
John McCallcc7e5bf2010-05-06 08:58:33 +00006434 // Go ahead and check any implicit conversions we might have skipped.
6435 // The non-canonical typecheck is just an optimization;
6436 // CheckImplicitConversion will filter out dead implicit conversions.
6437 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006438 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006439
6440 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006441
6442 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006443 if (POE->getResultExpr())
6444 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006445 }
6446
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006447 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6448 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6449
John McCallcc7e5bf2010-05-06 08:58:33 +00006450 // Skip past explicit casts.
6451 if (isa<ExplicitCastExpr>(E)) {
6452 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006453 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006454 }
6455
John McCalld2a53122010-11-09 23:24:47 +00006456 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6457 // Do a somewhat different check with comparison operators.
6458 if (BO->isComparisonOp())
6459 return AnalyzeComparison(S, BO);
6460
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006461 // And with simple assignments.
6462 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006463 return AnalyzeAssignment(S, BO);
6464 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006465
6466 // These break the otherwise-useful invariant below. Fortunately,
6467 // we don't really need to recurse into them, because any internal
6468 // expressions should have been analyzed already when they were
6469 // built into statements.
6470 if (isa<StmtExpr>(E)) return;
6471
6472 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006473 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006474
6475 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006476 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006477 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006478 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006479 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006480 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006481 if (!ChildExpr)
6482 continue;
6483
Richard Trieu955231d2014-01-25 01:10:35 +00006484 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006485 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006486 // Ignore checking string literals that are in logical and operators.
6487 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006488 continue;
6489 AnalyzeImplicitConversions(S, ChildExpr, CC);
6490 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006491}
6492
6493} // end anonymous namespace
6494
Richard Trieu3bb8b562014-02-26 02:36:06 +00006495enum {
6496 AddressOf,
6497 FunctionPointer,
6498 ArrayPointer
6499};
6500
Richard Trieuc1888e02014-06-28 23:25:37 +00006501// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6502// Returns true when emitting a warning about taking the address of a reference.
6503static bool CheckForReference(Sema &SemaRef, const Expr *E,
6504 PartialDiagnostic PD) {
6505 E = E->IgnoreParenImpCasts();
6506
6507 const FunctionDecl *FD = nullptr;
6508
6509 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6510 if (!DRE->getDecl()->getType()->isReferenceType())
6511 return false;
6512 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6513 if (!M->getMemberDecl()->getType()->isReferenceType())
6514 return false;
6515 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6516 if (!Call->getCallReturnType()->isReferenceType())
6517 return false;
6518 FD = Call->getDirectCallee();
6519 } else {
6520 return false;
6521 }
6522
6523 SemaRef.Diag(E->getExprLoc(), PD);
6524
6525 // If possible, point to location of function.
6526 if (FD) {
6527 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6528 }
6529
6530 return true;
6531}
6532
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006533// Returns true if the SourceLocation is expanded from any macro body.
6534// Returns false if the SourceLocation is invalid, is from not in a macro
6535// expansion, or is from expanded from a top-level macro argument.
6536static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6537 if (Loc.isInvalid())
6538 return false;
6539
6540 while (Loc.isMacroID()) {
6541 if (SM.isMacroBodyExpansion(Loc))
6542 return true;
6543 Loc = SM.getImmediateMacroCallerLoc(Loc);
6544 }
6545
6546 return false;
6547}
6548
Richard Trieu3bb8b562014-02-26 02:36:06 +00006549/// \brief Diagnose pointers that are always non-null.
6550/// \param E the expression containing the pointer
6551/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6552/// compared to a null pointer
6553/// \param IsEqual True when the comparison is equal to a null pointer
6554/// \param Range Extra SourceRange to highlight in the diagnostic
6555void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6556 Expr::NullPointerConstantKind NullKind,
6557 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006558 if (!E)
6559 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006560
6561 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006562 if (E->getExprLoc().isMacroID()) {
6563 const SourceManager &SM = getSourceManager();
6564 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6565 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006566 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006567 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006568 E = E->IgnoreImpCasts();
6569
6570 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6571
Richard Trieuf7432752014-06-06 21:39:26 +00006572 if (isa<CXXThisExpr>(E)) {
6573 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6574 : diag::warn_this_bool_conversion;
6575 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6576 return;
6577 }
6578
Richard Trieu3bb8b562014-02-26 02:36:06 +00006579 bool IsAddressOf = false;
6580
6581 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6582 if (UO->getOpcode() != UO_AddrOf)
6583 return;
6584 IsAddressOf = true;
6585 E = UO->getSubExpr();
6586 }
6587
Richard Trieuc1888e02014-06-28 23:25:37 +00006588 if (IsAddressOf) {
6589 unsigned DiagID = IsCompare
6590 ? diag::warn_address_of_reference_null_compare
6591 : diag::warn_address_of_reference_bool_conversion;
6592 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6593 << IsEqual;
6594 if (CheckForReference(*this, E, PD)) {
6595 return;
6596 }
6597 }
6598
Richard Trieu3bb8b562014-02-26 02:36:06 +00006599 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006600 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006601 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6602 D = R->getDecl();
6603 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6604 D = M->getMemberDecl();
6605 }
6606
6607 // Weak Decls can be null.
6608 if (!D || D->isWeak())
6609 return;
6610
6611 QualType T = D->getType();
6612 const bool IsArray = T->isArrayType();
6613 const bool IsFunction = T->isFunctionType();
6614
Richard Trieuc1888e02014-06-28 23:25:37 +00006615 // Address of function is used to silence the function warning.
6616 if (IsAddressOf && IsFunction) {
6617 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006618 }
6619
6620 // Found nothing.
6621 if (!IsAddressOf && !IsFunction && !IsArray)
6622 return;
6623
6624 // Pretty print the expression for the diagnostic.
6625 std::string Str;
6626 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006627 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006628
6629 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6630 : diag::warn_impcast_pointer_to_bool;
6631 unsigned DiagType;
6632 if (IsAddressOf)
6633 DiagType = AddressOf;
6634 else if (IsFunction)
6635 DiagType = FunctionPointer;
6636 else if (IsArray)
6637 DiagType = ArrayPointer;
6638 else
6639 llvm_unreachable("Could not determine diagnostic.");
6640 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6641 << Range << IsEqual;
6642
6643 if (!IsFunction)
6644 return;
6645
6646 // Suggest '&' to silence the function warning.
6647 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6648 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6649
6650 // Check to see if '()' fixit should be emitted.
6651 QualType ReturnType;
6652 UnresolvedSet<4> NonTemplateOverloads;
6653 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6654 if (ReturnType.isNull())
6655 return;
6656
6657 if (IsCompare) {
6658 // There are two cases here. If there is null constant, the only suggest
6659 // for a pointer return type. If the null is 0, then suggest if the return
6660 // type is a pointer or an integer type.
6661 if (!ReturnType->isPointerType()) {
6662 if (NullKind == Expr::NPCK_ZeroExpression ||
6663 NullKind == Expr::NPCK_ZeroLiteral) {
6664 if (!ReturnType->isIntegerType())
6665 return;
6666 } else {
6667 return;
6668 }
6669 }
6670 } else { // !IsCompare
6671 // For function to bool, only suggest if the function pointer has bool
6672 // return type.
6673 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6674 return;
6675 }
6676 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006677 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006678}
6679
6680
John McCallcc7e5bf2010-05-06 08:58:33 +00006681/// Diagnoses "dangerous" implicit conversions within the given
6682/// expression (which is a full expression). Implements -Wconversion
6683/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006684///
6685/// \param CC the "context" location of the implicit conversion, i.e.
6686/// the most location of the syntactic entity requiring the implicit
6687/// conversion
6688void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006689 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006690 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006691 return;
6692
6693 // Don't diagnose for value- or type-dependent expressions.
6694 if (E->isTypeDependent() || E->isValueDependent())
6695 return;
6696
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006697 // Check for array bounds violations in cases where the check isn't triggered
6698 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6699 // ArraySubscriptExpr is on the RHS of a variable initialization.
6700 CheckArrayAccess(E);
6701
John McCallacf0ee52010-10-08 02:01:28 +00006702 // This is not the right CC for (e.g.) a variable initialization.
6703 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006704}
6705
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006706/// Diagnose when expression is an integer constant expression and its evaluation
6707/// results in integer overflow
6708void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006709 if (isa<BinaryOperator>(E->IgnoreParens()))
6710 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006711}
6712
Richard Smithc406cb72013-01-17 01:17:56 +00006713namespace {
6714/// \brief Visitor for expressions which looks for unsequenced operations on the
6715/// same object.
6716class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006717 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6718
Richard Smithc406cb72013-01-17 01:17:56 +00006719 /// \brief A tree of sequenced regions within an expression. Two regions are
6720 /// unsequenced if one is an ancestor or a descendent of the other. When we
6721 /// finish processing an expression with sequencing, such as a comma
6722 /// expression, we fold its tree nodes into its parent, since they are
6723 /// unsequenced with respect to nodes we will visit later.
6724 class SequenceTree {
6725 struct Value {
6726 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6727 unsigned Parent : 31;
6728 bool Merged : 1;
6729 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006730 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006731
6732 public:
6733 /// \brief A region within an expression which may be sequenced with respect
6734 /// to some other region.
6735 class Seq {
6736 explicit Seq(unsigned N) : Index(N) {}
6737 unsigned Index;
6738 friend class SequenceTree;
6739 public:
6740 Seq() : Index(0) {}
6741 };
6742
6743 SequenceTree() { Values.push_back(Value(0)); }
6744 Seq root() const { return Seq(0); }
6745
6746 /// \brief Create a new sequence of operations, which is an unsequenced
6747 /// subset of \p Parent. This sequence of operations is sequenced with
6748 /// respect to other children of \p Parent.
6749 Seq allocate(Seq Parent) {
6750 Values.push_back(Value(Parent.Index));
6751 return Seq(Values.size() - 1);
6752 }
6753
6754 /// \brief Merge a sequence of operations into its parent.
6755 void merge(Seq S) {
6756 Values[S.Index].Merged = true;
6757 }
6758
6759 /// \brief Determine whether two operations are unsequenced. This operation
6760 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6761 /// should have been merged into its parent as appropriate.
6762 bool isUnsequenced(Seq Cur, Seq Old) {
6763 unsigned C = representative(Cur.Index);
6764 unsigned Target = representative(Old.Index);
6765 while (C >= Target) {
6766 if (C == Target)
6767 return true;
6768 C = Values[C].Parent;
6769 }
6770 return false;
6771 }
6772
6773 private:
6774 /// \brief Pick a representative for a sequence.
6775 unsigned representative(unsigned K) {
6776 if (Values[K].Merged)
6777 // Perform path compression as we go.
6778 return Values[K].Parent = representative(Values[K].Parent);
6779 return K;
6780 }
6781 };
6782
6783 /// An object for which we can track unsequenced uses.
6784 typedef NamedDecl *Object;
6785
6786 /// Different flavors of object usage which we track. We only track the
6787 /// least-sequenced usage of each kind.
6788 enum UsageKind {
6789 /// A read of an object. Multiple unsequenced reads are OK.
6790 UK_Use,
6791 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006792 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006793 UK_ModAsValue,
6794 /// A modification of an object which is not sequenced before the value
6795 /// computation of the expression, such as n++.
6796 UK_ModAsSideEffect,
6797
6798 UK_Count = UK_ModAsSideEffect + 1
6799 };
6800
6801 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006802 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006803 Expr *Use;
6804 SequenceTree::Seq Seq;
6805 };
6806
6807 struct UsageInfo {
6808 UsageInfo() : Diagnosed(false) {}
6809 Usage Uses[UK_Count];
6810 /// Have we issued a diagnostic for this variable already?
6811 bool Diagnosed;
6812 };
6813 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6814
6815 Sema &SemaRef;
6816 /// Sequenced regions within the expression.
6817 SequenceTree Tree;
6818 /// Declaration modifications and references which we have seen.
6819 UsageInfoMap UsageMap;
6820 /// The region we are currently within.
6821 SequenceTree::Seq Region;
6822 /// Filled in with declarations which were modified as a side-effect
6823 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006824 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006825 /// Expressions to check later. We defer checking these to reduce
6826 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006827 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006828
6829 /// RAII object wrapping the visitation of a sequenced subexpression of an
6830 /// expression. At the end of this process, the side-effects of the evaluation
6831 /// become sequenced with respect to the value computation of the result, so
6832 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6833 /// UK_ModAsValue.
6834 struct SequencedSubexpression {
6835 SequencedSubexpression(SequenceChecker &Self)
6836 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6837 Self.ModAsSideEffect = &ModAsSideEffect;
6838 }
6839 ~SequencedSubexpression() {
6840 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6841 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6842 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6843 Self.addUsage(U, ModAsSideEffect[I].first,
6844 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6845 }
6846 Self.ModAsSideEffect = OldModAsSideEffect;
6847 }
6848
6849 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006850 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6851 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006852 };
6853
Richard Smith40238f02013-06-20 22:21:56 +00006854 /// RAII object wrapping the visitation of a subexpression which we might
6855 /// choose to evaluate as a constant. If any subexpression is evaluated and
6856 /// found to be non-constant, this allows us to suppress the evaluation of
6857 /// the outer expression.
6858 class EvaluationTracker {
6859 public:
6860 EvaluationTracker(SequenceChecker &Self)
6861 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6862 Self.EvalTracker = this;
6863 }
6864 ~EvaluationTracker() {
6865 Self.EvalTracker = Prev;
6866 if (Prev)
6867 Prev->EvalOK &= EvalOK;
6868 }
6869
6870 bool evaluate(const Expr *E, bool &Result) {
6871 if (!EvalOK || E->isValueDependent())
6872 return false;
6873 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6874 return EvalOK;
6875 }
6876
6877 private:
6878 SequenceChecker &Self;
6879 EvaluationTracker *Prev;
6880 bool EvalOK;
6881 } *EvalTracker;
6882
Richard Smithc406cb72013-01-17 01:17:56 +00006883 /// \brief Find the object which is produced by the specified expression,
6884 /// if any.
6885 Object getObject(Expr *E, bool Mod) const {
6886 E = E->IgnoreParenCasts();
6887 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6888 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6889 return getObject(UO->getSubExpr(), Mod);
6890 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6891 if (BO->getOpcode() == BO_Comma)
6892 return getObject(BO->getRHS(), Mod);
6893 if (Mod && BO->isAssignmentOp())
6894 return getObject(BO->getLHS(), Mod);
6895 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6896 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6897 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6898 return ME->getMemberDecl();
6899 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6900 // FIXME: If this is a reference, map through to its value.
6901 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006902 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006903 }
6904
6905 /// \brief Note that an object was modified or used by an expression.
6906 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6907 Usage &U = UI.Uses[UK];
6908 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6909 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6910 ModAsSideEffect->push_back(std::make_pair(O, U));
6911 U.Use = Ref;
6912 U.Seq = Region;
6913 }
6914 }
6915 /// \brief Check whether a modification or use conflicts with a prior usage.
6916 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6917 bool IsModMod) {
6918 if (UI.Diagnosed)
6919 return;
6920
6921 const Usage &U = UI.Uses[OtherKind];
6922 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6923 return;
6924
6925 Expr *Mod = U.Use;
6926 Expr *ModOrUse = Ref;
6927 if (OtherKind == UK_Use)
6928 std::swap(Mod, ModOrUse);
6929
6930 SemaRef.Diag(Mod->getExprLoc(),
6931 IsModMod ? diag::warn_unsequenced_mod_mod
6932 : diag::warn_unsequenced_mod_use)
6933 << O << SourceRange(ModOrUse->getExprLoc());
6934 UI.Diagnosed = true;
6935 }
6936
6937 void notePreUse(Object O, Expr *Use) {
6938 UsageInfo &U = UsageMap[O];
6939 // Uses conflict with other modifications.
6940 checkUsage(O, U, Use, UK_ModAsValue, false);
6941 }
6942 void notePostUse(Object O, Expr *Use) {
6943 UsageInfo &U = UsageMap[O];
6944 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6945 addUsage(U, O, Use, UK_Use);
6946 }
6947
6948 void notePreMod(Object O, Expr *Mod) {
6949 UsageInfo &U = UsageMap[O];
6950 // Modifications conflict with other modifications and with uses.
6951 checkUsage(O, U, Mod, UK_ModAsValue, true);
6952 checkUsage(O, U, Mod, UK_Use, false);
6953 }
6954 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6955 UsageInfo &U = UsageMap[O];
6956 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6957 addUsage(U, O, Use, UK);
6958 }
6959
6960public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006961 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006962 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6963 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006964 Visit(E);
6965 }
6966
6967 void VisitStmt(Stmt *S) {
6968 // Skip all statements which aren't expressions for now.
6969 }
6970
6971 void VisitExpr(Expr *E) {
6972 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006973 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006974 }
6975
6976 void VisitCastExpr(CastExpr *E) {
6977 Object O = Object();
6978 if (E->getCastKind() == CK_LValueToRValue)
6979 O = getObject(E->getSubExpr(), false);
6980
6981 if (O)
6982 notePreUse(O, E);
6983 VisitExpr(E);
6984 if (O)
6985 notePostUse(O, E);
6986 }
6987
6988 void VisitBinComma(BinaryOperator *BO) {
6989 // C++11 [expr.comma]p1:
6990 // Every value computation and side effect associated with the left
6991 // expression is sequenced before every value computation and side
6992 // effect associated with the right expression.
6993 SequenceTree::Seq LHS = Tree.allocate(Region);
6994 SequenceTree::Seq RHS = Tree.allocate(Region);
6995 SequenceTree::Seq OldRegion = Region;
6996
6997 {
6998 SequencedSubexpression SeqLHS(*this);
6999 Region = LHS;
7000 Visit(BO->getLHS());
7001 }
7002
7003 Region = RHS;
7004 Visit(BO->getRHS());
7005
7006 Region = OldRegion;
7007
7008 // Forget that LHS and RHS are sequenced. They are both unsequenced
7009 // with respect to other stuff.
7010 Tree.merge(LHS);
7011 Tree.merge(RHS);
7012 }
7013
7014 void VisitBinAssign(BinaryOperator *BO) {
7015 // The modification is sequenced after the value computation of the LHS
7016 // and RHS, so check it before inspecting the operands and update the
7017 // map afterwards.
7018 Object O = getObject(BO->getLHS(), true);
7019 if (!O)
7020 return VisitExpr(BO);
7021
7022 notePreMod(O, BO);
7023
7024 // C++11 [expr.ass]p7:
7025 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7026 // only once.
7027 //
7028 // Therefore, for a compound assignment operator, O is considered used
7029 // everywhere except within the evaluation of E1 itself.
7030 if (isa<CompoundAssignOperator>(BO))
7031 notePreUse(O, BO);
7032
7033 Visit(BO->getLHS());
7034
7035 if (isa<CompoundAssignOperator>(BO))
7036 notePostUse(O, BO);
7037
7038 Visit(BO->getRHS());
7039
Richard Smith83e37bee2013-06-26 23:16:51 +00007040 // C++11 [expr.ass]p1:
7041 // the assignment is sequenced [...] before the value computation of the
7042 // assignment expression.
7043 // C11 6.5.16/3 has no such rule.
7044 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7045 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007046 }
7047 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7048 VisitBinAssign(CAO);
7049 }
7050
7051 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7052 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7053 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7054 Object O = getObject(UO->getSubExpr(), true);
7055 if (!O)
7056 return VisitExpr(UO);
7057
7058 notePreMod(O, UO);
7059 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007060 // C++11 [expr.pre.incr]p1:
7061 // the expression ++x is equivalent to x+=1
7062 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7063 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007064 }
7065
7066 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7067 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7068 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7069 Object O = getObject(UO->getSubExpr(), true);
7070 if (!O)
7071 return VisitExpr(UO);
7072
7073 notePreMod(O, UO);
7074 Visit(UO->getSubExpr());
7075 notePostMod(O, UO, UK_ModAsSideEffect);
7076 }
7077
7078 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7079 void VisitBinLOr(BinaryOperator *BO) {
7080 // The side-effects of the LHS of an '&&' are sequenced before the
7081 // value computation of the RHS, and hence before the value computation
7082 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7083 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007084 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007085 {
7086 SequencedSubexpression Sequenced(*this);
7087 Visit(BO->getLHS());
7088 }
7089
7090 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007091 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007092 if (!Result)
7093 Visit(BO->getRHS());
7094 } else {
7095 // Check for unsequenced operations in the RHS, treating it as an
7096 // entirely separate evaluation.
7097 //
7098 // FIXME: If there are operations in the RHS which are unsequenced
7099 // with respect to operations outside the RHS, and those operations
7100 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007101 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007102 }
Richard Smithc406cb72013-01-17 01:17:56 +00007103 }
7104 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007105 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007106 {
7107 SequencedSubexpression Sequenced(*this);
7108 Visit(BO->getLHS());
7109 }
7110
7111 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007112 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007113 if (Result)
7114 Visit(BO->getRHS());
7115 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007116 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007117 }
Richard Smithc406cb72013-01-17 01:17:56 +00007118 }
7119
7120 // Only visit the condition, unless we can be sure which subexpression will
7121 // be chosen.
7122 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007123 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007124 {
7125 SequencedSubexpression Sequenced(*this);
7126 Visit(CO->getCond());
7127 }
Richard Smithc406cb72013-01-17 01:17:56 +00007128
7129 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007130 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007131 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007132 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007133 WorkList.push_back(CO->getTrueExpr());
7134 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007135 }
Richard Smithc406cb72013-01-17 01:17:56 +00007136 }
7137
Richard Smithe3dbfe02013-06-30 10:40:20 +00007138 void VisitCallExpr(CallExpr *CE) {
7139 // C++11 [intro.execution]p15:
7140 // When calling a function [...], every value computation and side effect
7141 // associated with any argument expression, or with the postfix expression
7142 // designating the called function, is sequenced before execution of every
7143 // expression or statement in the body of the function [and thus before
7144 // the value computation of its result].
7145 SequencedSubexpression Sequenced(*this);
7146 Base::VisitCallExpr(CE);
7147
7148 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7149 }
7150
Richard Smithc406cb72013-01-17 01:17:56 +00007151 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007152 // This is a call, so all subexpressions are sequenced before the result.
7153 SequencedSubexpression Sequenced(*this);
7154
Richard Smithc406cb72013-01-17 01:17:56 +00007155 if (!CCE->isListInitialization())
7156 return VisitExpr(CCE);
7157
7158 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007159 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007160 SequenceTree::Seq Parent = Region;
7161 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7162 E = CCE->arg_end();
7163 I != E; ++I) {
7164 Region = Tree.allocate(Parent);
7165 Elts.push_back(Region);
7166 Visit(*I);
7167 }
7168
7169 // Forget that the initializers are sequenced.
7170 Region = Parent;
7171 for (unsigned I = 0; I < Elts.size(); ++I)
7172 Tree.merge(Elts[I]);
7173 }
7174
7175 void VisitInitListExpr(InitListExpr *ILE) {
7176 if (!SemaRef.getLangOpts().CPlusPlus11)
7177 return VisitExpr(ILE);
7178
7179 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007180 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007181 SequenceTree::Seq Parent = Region;
7182 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7183 Expr *E = ILE->getInit(I);
7184 if (!E) continue;
7185 Region = Tree.allocate(Parent);
7186 Elts.push_back(Region);
7187 Visit(E);
7188 }
7189
7190 // Forget that the initializers are sequenced.
7191 Region = Parent;
7192 for (unsigned I = 0; I < Elts.size(); ++I)
7193 Tree.merge(Elts[I]);
7194 }
7195};
7196}
7197
7198void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007199 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007200 WorkList.push_back(E);
7201 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007202 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007203 SequenceChecker(*this, Item, WorkList);
7204 }
Richard Smithc406cb72013-01-17 01:17:56 +00007205}
7206
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007207void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7208 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007209 CheckImplicitConversions(E, CheckLoc);
7210 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007211 if (!IsConstexpr && !E->isValueDependent())
7212 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007213}
7214
John McCall1f425642010-11-11 03:21:53 +00007215void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7216 FieldDecl *BitField,
7217 Expr *Init) {
7218 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7219}
7220
Mike Stump0c2ec772010-01-21 03:59:47 +00007221/// CheckParmsForFunctionDef - Check that the parameters of the given
7222/// function are appropriate for the definition of a function. This
7223/// takes care of any checks that cannot be performed on the
7224/// declaration itself, e.g., that the types of each of the function
7225/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007226bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7227 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007228 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007229 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007230 for (; P != PEnd; ++P) {
7231 ParmVarDecl *Param = *P;
7232
Mike Stump0c2ec772010-01-21 03:59:47 +00007233 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7234 // function declarator that is part of a function definition of
7235 // that function shall not have incomplete type.
7236 //
7237 // This is also C++ [dcl.fct]p6.
7238 if (!Param->isInvalidDecl() &&
7239 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007240 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007241 Param->setInvalidDecl();
7242 HasInvalidParm = true;
7243 }
7244
7245 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7246 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007247 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007248 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007249 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007250 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007251 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007252
7253 // C99 6.7.5.3p12:
7254 // If the function declarator is not part of a definition of that
7255 // function, parameters may have incomplete type and may use the [*]
7256 // notation in their sequences of declarator specifiers to specify
7257 // variable length array types.
7258 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007259 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007260 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007261 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007262 // information is added for it.
7263 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007264 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007265 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007266 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007267 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007268
7269 // MSVC destroys objects passed by value in the callee. Therefore a
7270 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007271 // object's destructor. However, we don't perform any direct access check
7272 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007273 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7274 .getCXXABI()
7275 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007276 if (!Param->isInvalidDecl()) {
7277 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7278 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7279 if (!ClassDecl->isInvalidDecl() &&
7280 !ClassDecl->hasIrrelevantDestructor() &&
7281 !ClassDecl->isDependentContext()) {
7282 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7283 MarkFunctionReferenced(Param->getLocation(), Destructor);
7284 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7285 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007286 }
7287 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007288 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007289 }
7290
7291 return HasInvalidParm;
7292}
John McCall2b5c1b22010-08-12 21:44:57 +00007293
7294/// CheckCastAlign - Implements -Wcast-align, which warns when a
7295/// pointer cast increases the alignment requirements.
7296void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7297 // This is actually a lot of work to potentially be doing on every
7298 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007299 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007300 return;
7301
7302 // Ignore dependent types.
7303 if (T->isDependentType() || Op->getType()->isDependentType())
7304 return;
7305
7306 // Require that the destination be a pointer type.
7307 const PointerType *DestPtr = T->getAs<PointerType>();
7308 if (!DestPtr) return;
7309
7310 // If the destination has alignment 1, we're done.
7311 QualType DestPointee = DestPtr->getPointeeType();
7312 if (DestPointee->isIncompleteType()) return;
7313 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7314 if (DestAlign.isOne()) return;
7315
7316 // Require that the source be a pointer type.
7317 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7318 if (!SrcPtr) return;
7319 QualType SrcPointee = SrcPtr->getPointeeType();
7320
7321 // Whitelist casts from cv void*. We already implicitly
7322 // whitelisted casts to cv void*, since they have alignment 1.
7323 // Also whitelist casts involving incomplete types, which implicitly
7324 // includes 'void'.
7325 if (SrcPointee->isIncompleteType()) return;
7326
7327 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7328 if (SrcAlign >= DestAlign) return;
7329
7330 Diag(TRange.getBegin(), diag::warn_cast_align)
7331 << Op->getType() << T
7332 << static_cast<unsigned>(SrcAlign.getQuantity())
7333 << static_cast<unsigned>(DestAlign.getQuantity())
7334 << TRange << Op->getSourceRange();
7335}
7336
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007337static const Type* getElementType(const Expr *BaseExpr) {
7338 const Type* EltType = BaseExpr->getType().getTypePtr();
7339 if (EltType->isAnyPointerType())
7340 return EltType->getPointeeType().getTypePtr();
7341 else if (EltType->isArrayType())
7342 return EltType->getBaseElementTypeUnsafe();
7343 return EltType;
7344}
7345
Chandler Carruth28389f02011-08-05 09:10:50 +00007346/// \brief Check whether this array fits the idiom of a size-one tail padded
7347/// array member of a struct.
7348///
7349/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7350/// commonly used to emulate flexible arrays in C89 code.
7351static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7352 const NamedDecl *ND) {
7353 if (Size != 1 || !ND) return false;
7354
7355 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7356 if (!FD) return false;
7357
7358 // Don't consider sizes resulting from macro expansions or template argument
7359 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007360
7361 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007362 while (TInfo) {
7363 TypeLoc TL = TInfo->getTypeLoc();
7364 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007365 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7366 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007367 TInfo = TDL->getTypeSourceInfo();
7368 continue;
7369 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007370 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7371 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007372 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7373 return false;
7374 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007375 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007376 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007377
7378 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007379 if (!RD) return false;
7380 if (RD->isUnion()) return false;
7381 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7382 if (!CRD->isStandardLayout()) return false;
7383 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007384
Benjamin Kramer8c543672011-08-06 03:04:42 +00007385 // See if this is the last field decl in the record.
7386 const Decl *D = FD;
7387 while ((D = D->getNextDeclInContext()))
7388 if (isa<FieldDecl>(D))
7389 return false;
7390 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007391}
7392
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007393void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007394 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007395 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007396 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007397 if (IndexExpr->isValueDependent())
7398 return;
7399
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007400 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007401 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007402 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007403 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007404 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007405 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007406
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007407 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007408 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007409 return;
Richard Smith13f67182011-12-16 19:31:14 +00007410 if (IndexNegated)
7411 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007412
Craig Topperc3ec1492014-05-26 06:22:03 +00007413 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007414 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7415 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007416 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007417 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007418
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007419 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007420 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007421 if (!size.isStrictlyPositive())
7422 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007423
7424 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007425 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007426 // Make sure we're comparing apples to apples when comparing index to size
7427 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7428 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007429 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007430 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007431 if (ptrarith_typesize != array_typesize) {
7432 // There's a cast to a different size type involved
7433 uint64_t ratio = array_typesize / ptrarith_typesize;
7434 // TODO: Be smarter about handling cases where array_typesize is not a
7435 // multiple of ptrarith_typesize
7436 if (ptrarith_typesize * ratio == array_typesize)
7437 size *= llvm::APInt(size.getBitWidth(), ratio);
7438 }
7439 }
7440
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007441 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007442 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007443 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007444 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007445
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007446 // For array subscripting the index must be less than size, but for pointer
7447 // arithmetic also allow the index (offset) to be equal to size since
7448 // computing the next address after the end of the array is legal and
7449 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007450 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007451 return;
7452
7453 // Also don't warn for arrays of size 1 which are members of some
7454 // structure. These are often used to approximate flexible arrays in C89
7455 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007456 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007457 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007458
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007459 // Suppress the warning if the subscript expression (as identified by the
7460 // ']' location) and the index expression are both from macro expansions
7461 // within a system header.
7462 if (ASE) {
7463 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7464 ASE->getRBracketLoc());
7465 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7466 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7467 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007468 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007469 return;
7470 }
7471 }
7472
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007473 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007474 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007475 DiagID = diag::warn_array_index_exceeds_bounds;
7476
7477 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7478 PDiag(DiagID) << index.toString(10, true)
7479 << size.toString(10, true)
7480 << (unsigned)size.getLimitedValue(~0U)
7481 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007482 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007483 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007484 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007485 DiagID = diag::warn_ptr_arith_precedes_bounds;
7486 if (index.isNegative()) index = -index;
7487 }
7488
7489 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7490 PDiag(DiagID) << index.toString(10, true)
7491 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007492 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007493
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007494 if (!ND) {
7495 // Try harder to find a NamedDecl to point at in the note.
7496 while (const ArraySubscriptExpr *ASE =
7497 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7498 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7499 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7500 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7501 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7502 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7503 }
7504
Chandler Carruth1af88f12011-02-17 21:10:52 +00007505 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007506 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7507 PDiag(diag::note_array_index_out_of_bounds)
7508 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007509}
7510
Ted Kremenekdf26df72011-03-01 18:41:00 +00007511void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007512 int AllowOnePastEnd = 0;
7513 while (expr) {
7514 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007515 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007516 case Stmt::ArraySubscriptExprClass: {
7517 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007518 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007519 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007520 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007521 }
7522 case Stmt::UnaryOperatorClass: {
7523 // Only unwrap the * and & unary operators
7524 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7525 expr = UO->getSubExpr();
7526 switch (UO->getOpcode()) {
7527 case UO_AddrOf:
7528 AllowOnePastEnd++;
7529 break;
7530 case UO_Deref:
7531 AllowOnePastEnd--;
7532 break;
7533 default:
7534 return;
7535 }
7536 break;
7537 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007538 case Stmt::ConditionalOperatorClass: {
7539 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7540 if (const Expr *lhs = cond->getLHS())
7541 CheckArrayAccess(lhs);
7542 if (const Expr *rhs = cond->getRHS())
7543 CheckArrayAccess(rhs);
7544 return;
7545 }
7546 default:
7547 return;
7548 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007549 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007550}
John McCall31168b02011-06-15 23:02:42 +00007551
7552//===--- CHECK: Objective-C retain cycles ----------------------------------//
7553
7554namespace {
7555 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007556 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007557 VarDecl *Variable;
7558 SourceRange Range;
7559 SourceLocation Loc;
7560 bool Indirect;
7561
7562 void setLocsFrom(Expr *e) {
7563 Loc = e->getExprLoc();
7564 Range = e->getSourceRange();
7565 }
7566 };
7567}
7568
7569/// Consider whether capturing the given variable can possibly lead to
7570/// a retain cycle.
7571static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007572 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007573 // lifetime. In MRR, it's captured strongly if the variable is
7574 // __block and has an appropriate type.
7575 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7576 return false;
7577
7578 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007579 if (ref)
7580 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007581 return true;
7582}
7583
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007584static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007585 while (true) {
7586 e = e->IgnoreParens();
7587 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7588 switch (cast->getCastKind()) {
7589 case CK_BitCast:
7590 case CK_LValueBitCast:
7591 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007592 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007593 e = cast->getSubExpr();
7594 continue;
7595
John McCall31168b02011-06-15 23:02:42 +00007596 default:
7597 return false;
7598 }
7599 }
7600
7601 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7602 ObjCIvarDecl *ivar = ref->getDecl();
7603 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7604 return false;
7605
7606 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007607 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007608 return false;
7609
7610 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7611 owner.Indirect = true;
7612 return true;
7613 }
7614
7615 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7616 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7617 if (!var) return false;
7618 return considerVariable(var, ref, owner);
7619 }
7620
John McCall31168b02011-06-15 23:02:42 +00007621 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7622 if (member->isArrow()) return false;
7623
7624 // Don't count this as an indirect ownership.
7625 e = member->getBase();
7626 continue;
7627 }
7628
John McCallfe96e0b2011-11-06 09:01:30 +00007629 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7630 // Only pay attention to pseudo-objects on property references.
7631 ObjCPropertyRefExpr *pre
7632 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7633 ->IgnoreParens());
7634 if (!pre) return false;
7635 if (pre->isImplicitProperty()) return false;
7636 ObjCPropertyDecl *property = pre->getExplicitProperty();
7637 if (!property->isRetaining() &&
7638 !(property->getPropertyIvarDecl() &&
7639 property->getPropertyIvarDecl()->getType()
7640 .getObjCLifetime() == Qualifiers::OCL_Strong))
7641 return false;
7642
7643 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007644 if (pre->isSuperReceiver()) {
7645 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7646 if (!owner.Variable)
7647 return false;
7648 owner.Loc = pre->getLocation();
7649 owner.Range = pre->getSourceRange();
7650 return true;
7651 }
John McCallfe96e0b2011-11-06 09:01:30 +00007652 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7653 ->getSourceExpr());
7654 continue;
7655 }
7656
John McCall31168b02011-06-15 23:02:42 +00007657 // Array ivars?
7658
7659 return false;
7660 }
7661}
7662
7663namespace {
7664 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7665 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7666 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007667 Context(Context), Variable(variable), Capturer(nullptr),
7668 VarWillBeReased(false) {}
7669 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007670 VarDecl *Variable;
7671 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007672 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007673
7674 void VisitDeclRefExpr(DeclRefExpr *ref) {
7675 if (ref->getDecl() == Variable && !Capturer)
7676 Capturer = ref;
7677 }
7678
John McCall31168b02011-06-15 23:02:42 +00007679 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7680 if (Capturer) return;
7681 Visit(ref->getBase());
7682 if (Capturer && ref->isFreeIvar())
7683 Capturer = ref;
7684 }
7685
7686 void VisitBlockExpr(BlockExpr *block) {
7687 // Look inside nested blocks
7688 if (block->getBlockDecl()->capturesVariable(Variable))
7689 Visit(block->getBlockDecl()->getBody());
7690 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007691
7692 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7693 if (Capturer) return;
7694 if (OVE->getSourceExpr())
7695 Visit(OVE->getSourceExpr());
7696 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007697 void VisitBinaryOperator(BinaryOperator *BinOp) {
7698 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7699 return;
7700 Expr *LHS = BinOp->getLHS();
7701 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7702 if (DRE->getDecl() != Variable)
7703 return;
7704 if (Expr *RHS = BinOp->getRHS()) {
7705 RHS = RHS->IgnoreParenCasts();
7706 llvm::APSInt Value;
7707 VarWillBeReased =
7708 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7709 }
7710 }
7711 }
John McCall31168b02011-06-15 23:02:42 +00007712 };
7713}
7714
7715/// Check whether the given argument is a block which captures a
7716/// variable.
7717static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7718 assert(owner.Variable && owner.Loc.isValid());
7719
7720 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007721
7722 // Look through [^{...} copy] and Block_copy(^{...}).
7723 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7724 Selector Cmd = ME->getSelector();
7725 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7726 e = ME->getInstanceReceiver();
7727 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007728 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007729 e = e->IgnoreParenCasts();
7730 }
7731 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7732 if (CE->getNumArgs() == 1) {
7733 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007734 if (Fn) {
7735 const IdentifierInfo *FnI = Fn->getIdentifier();
7736 if (FnI && FnI->isStr("_Block_copy")) {
7737 e = CE->getArg(0)->IgnoreParenCasts();
7738 }
7739 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007740 }
7741 }
7742
John McCall31168b02011-06-15 23:02:42 +00007743 BlockExpr *block = dyn_cast<BlockExpr>(e);
7744 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007745 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007746
7747 FindCaptureVisitor visitor(S.Context, owner.Variable);
7748 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007749 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007750}
7751
7752static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7753 RetainCycleOwner &owner) {
7754 assert(capturer);
7755 assert(owner.Variable && owner.Loc.isValid());
7756
7757 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7758 << owner.Variable << capturer->getSourceRange();
7759 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7760 << owner.Indirect << owner.Range;
7761}
7762
7763/// Check for a keyword selector that starts with the word 'add' or
7764/// 'set'.
7765static bool isSetterLikeSelector(Selector sel) {
7766 if (sel.isUnarySelector()) return false;
7767
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007768 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007769 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007770 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007771 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007772 else if (str.startswith("add")) {
7773 // Specially whitelist 'addOperationWithBlock:'.
7774 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7775 return false;
7776 str = str.substr(3);
7777 }
John McCall31168b02011-06-15 23:02:42 +00007778 else
7779 return false;
7780
7781 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007782 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007783}
7784
7785/// Check a message send to see if it's likely to cause a retain cycle.
7786void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7787 // Only check instance methods whose selector looks like a setter.
7788 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7789 return;
7790
7791 // Try to find a variable that the receiver is strongly owned by.
7792 RetainCycleOwner owner;
7793 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007794 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007795 return;
7796 } else {
7797 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7798 owner.Variable = getCurMethodDecl()->getSelfDecl();
7799 owner.Loc = msg->getSuperLoc();
7800 owner.Range = msg->getSuperLoc();
7801 }
7802
7803 // Check whether the receiver is captured by any of the arguments.
7804 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7805 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7806 return diagnoseRetainCycle(*this, capturer, owner);
7807}
7808
7809/// Check a property assign to see if it's likely to cause a retain cycle.
7810void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7811 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007812 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007813 return;
7814
7815 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7816 diagnoseRetainCycle(*this, capturer, owner);
7817}
7818
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007819void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7820 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007821 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007822 return;
7823
7824 // Because we don't have an expression for the variable, we have to set the
7825 // location explicitly here.
7826 Owner.Loc = Var->getLocation();
7827 Owner.Range = Var->getSourceRange();
7828
7829 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7830 diagnoseRetainCycle(*this, Capturer, Owner);
7831}
7832
Ted Kremenek9304da92012-12-21 08:04:28 +00007833static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7834 Expr *RHS, bool isProperty) {
7835 // Check if RHS is an Objective-C object literal, which also can get
7836 // immediately zapped in a weak reference. Note that we explicitly
7837 // allow ObjCStringLiterals, since those are designed to never really die.
7838 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007839
Ted Kremenek64873352012-12-21 22:46:35 +00007840 // This enum needs to match with the 'select' in
7841 // warn_objc_arc_literal_assign (off-by-1).
7842 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7843 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7844 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007845
7846 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007847 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007848 << (isProperty ? 0 : 1)
7849 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007850
7851 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007852}
7853
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007854static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7855 Qualifiers::ObjCLifetime LT,
7856 Expr *RHS, bool isProperty) {
7857 // Strip off any implicit cast added to get to the one ARC-specific.
7858 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7859 if (cast->getCastKind() == CK_ARCConsumeObject) {
7860 S.Diag(Loc, diag::warn_arc_retained_assign)
7861 << (LT == Qualifiers::OCL_ExplicitNone)
7862 << (isProperty ? 0 : 1)
7863 << RHS->getSourceRange();
7864 return true;
7865 }
7866 RHS = cast->getSubExpr();
7867 }
7868
7869 if (LT == Qualifiers::OCL_Weak &&
7870 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7871 return true;
7872
7873 return false;
7874}
7875
Ted Kremenekb36234d2012-12-21 08:04:20 +00007876bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7877 QualType LHS, Expr *RHS) {
7878 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7879
7880 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7881 return false;
7882
7883 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7884 return true;
7885
7886 return false;
7887}
7888
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007889void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7890 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007891 QualType LHSType;
7892 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007893 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007894 ObjCPropertyRefExpr *PRE
7895 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7896 if (PRE && !PRE->isImplicitProperty()) {
7897 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7898 if (PD)
7899 LHSType = PD->getType();
7900 }
7901
7902 if (LHSType.isNull())
7903 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007904
7905 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7906
7907 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007908 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007909 getCurFunction()->markSafeWeakUse(LHS);
7910 }
7911
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007912 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7913 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007914
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007915 // FIXME. Check for other life times.
7916 if (LT != Qualifiers::OCL_None)
7917 return;
7918
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007919 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007920 if (PRE->isImplicitProperty())
7921 return;
7922 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7923 if (!PD)
7924 return;
7925
Bill Wendling44426052012-12-20 19:22:21 +00007926 unsigned Attributes = PD->getPropertyAttributes();
7927 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007928 // when 'assign' attribute was not explicitly specified
7929 // by user, ignore it and rely on property type itself
7930 // for lifetime info.
7931 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7932 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7933 LHSType->isObjCRetainableType())
7934 return;
7935
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007936 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007937 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007938 Diag(Loc, diag::warn_arc_retained_property_assign)
7939 << RHS->getSourceRange();
7940 return;
7941 }
7942 RHS = cast->getSubExpr();
7943 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007944 }
Bill Wendling44426052012-12-20 19:22:21 +00007945 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007946 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7947 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007948 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007949 }
7950}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007951
7952//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7953
7954namespace {
7955bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7956 SourceLocation StmtLoc,
7957 const NullStmt *Body) {
7958 // Do not warn if the body is a macro that expands to nothing, e.g:
7959 //
7960 // #define CALL(x)
7961 // if (condition)
7962 // CALL(0);
7963 //
7964 if (Body->hasLeadingEmptyMacro())
7965 return false;
7966
7967 // Get line numbers of statement and body.
7968 bool StmtLineInvalid;
7969 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7970 &StmtLineInvalid);
7971 if (StmtLineInvalid)
7972 return false;
7973
7974 bool BodyLineInvalid;
7975 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7976 &BodyLineInvalid);
7977 if (BodyLineInvalid)
7978 return false;
7979
7980 // Warn if null statement and body are on the same line.
7981 if (StmtLine != BodyLine)
7982 return false;
7983
7984 return true;
7985}
7986} // Unnamed namespace
7987
7988void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7989 const Stmt *Body,
7990 unsigned DiagID) {
7991 // Since this is a syntactic check, don't emit diagnostic for template
7992 // instantiations, this just adds noise.
7993 if (CurrentInstantiationScope)
7994 return;
7995
7996 // The body should be a null statement.
7997 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7998 if (!NBody)
7999 return;
8000
8001 // Do the usual checks.
8002 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8003 return;
8004
8005 Diag(NBody->getSemiLoc(), DiagID);
8006 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8007}
8008
8009void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8010 const Stmt *PossibleBody) {
8011 assert(!CurrentInstantiationScope); // Ensured by caller
8012
8013 SourceLocation StmtLoc;
8014 const Stmt *Body;
8015 unsigned DiagID;
8016 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8017 StmtLoc = FS->getRParenLoc();
8018 Body = FS->getBody();
8019 DiagID = diag::warn_empty_for_body;
8020 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8021 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8022 Body = WS->getBody();
8023 DiagID = diag::warn_empty_while_body;
8024 } else
8025 return; // Neither `for' nor `while'.
8026
8027 // The body should be a null statement.
8028 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8029 if (!NBody)
8030 return;
8031
8032 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008033 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008034 return;
8035
8036 // Do the usual checks.
8037 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8038 return;
8039
8040 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8041 // noise level low, emit diagnostics only if for/while is followed by a
8042 // CompoundStmt, e.g.:
8043 // for (int i = 0; i < n; i++);
8044 // {
8045 // a(i);
8046 // }
8047 // or if for/while is followed by a statement with more indentation
8048 // than for/while itself:
8049 // for (int i = 0; i < n; i++);
8050 // a(i);
8051 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8052 if (!ProbableTypo) {
8053 bool BodyColInvalid;
8054 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8055 PossibleBody->getLocStart(),
8056 &BodyColInvalid);
8057 if (BodyColInvalid)
8058 return;
8059
8060 bool StmtColInvalid;
8061 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8062 S->getLocStart(),
8063 &StmtColInvalid);
8064 if (StmtColInvalid)
8065 return;
8066
8067 if (BodyCol > StmtCol)
8068 ProbableTypo = true;
8069 }
8070
8071 if (ProbableTypo) {
8072 Diag(NBody->getSemiLoc(), DiagID);
8073 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8074 }
8075}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008076
8077//===--- Layout compatibility ----------------------------------------------//
8078
8079namespace {
8080
8081bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8082
8083/// \brief Check if two enumeration types are layout-compatible.
8084bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8085 // C++11 [dcl.enum] p8:
8086 // Two enumeration types are layout-compatible if they have the same
8087 // underlying type.
8088 return ED1->isComplete() && ED2->isComplete() &&
8089 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8090}
8091
8092/// \brief Check if two fields are layout-compatible.
8093bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8094 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8095 return false;
8096
8097 if (Field1->isBitField() != Field2->isBitField())
8098 return false;
8099
8100 if (Field1->isBitField()) {
8101 // Make sure that the bit-fields are the same length.
8102 unsigned Bits1 = Field1->getBitWidthValue(C);
8103 unsigned Bits2 = Field2->getBitWidthValue(C);
8104
8105 if (Bits1 != Bits2)
8106 return false;
8107 }
8108
8109 return true;
8110}
8111
8112/// \brief Check if two standard-layout structs are layout-compatible.
8113/// (C++11 [class.mem] p17)
8114bool isLayoutCompatibleStruct(ASTContext &C,
8115 RecordDecl *RD1,
8116 RecordDecl *RD2) {
8117 // If both records are C++ classes, check that base classes match.
8118 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8119 // If one of records is a CXXRecordDecl we are in C++ mode,
8120 // thus the other one is a CXXRecordDecl, too.
8121 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8122 // Check number of base classes.
8123 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8124 return false;
8125
8126 // Check the base classes.
8127 for (CXXRecordDecl::base_class_const_iterator
8128 Base1 = D1CXX->bases_begin(),
8129 BaseEnd1 = D1CXX->bases_end(),
8130 Base2 = D2CXX->bases_begin();
8131 Base1 != BaseEnd1;
8132 ++Base1, ++Base2) {
8133 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8134 return false;
8135 }
8136 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8137 // If only RD2 is a C++ class, it should have zero base classes.
8138 if (D2CXX->getNumBases() > 0)
8139 return false;
8140 }
8141
8142 // Check the fields.
8143 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8144 Field2End = RD2->field_end(),
8145 Field1 = RD1->field_begin(),
8146 Field1End = RD1->field_end();
8147 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8148 if (!isLayoutCompatible(C, *Field1, *Field2))
8149 return false;
8150 }
8151 if (Field1 != Field1End || Field2 != Field2End)
8152 return false;
8153
8154 return true;
8155}
8156
8157/// \brief Check if two standard-layout unions are layout-compatible.
8158/// (C++11 [class.mem] p18)
8159bool isLayoutCompatibleUnion(ASTContext &C,
8160 RecordDecl *RD1,
8161 RecordDecl *RD2) {
8162 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008163 for (auto *Field2 : RD2->fields())
8164 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008165
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008166 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008167 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8168 I = UnmatchedFields.begin(),
8169 E = UnmatchedFields.end();
8170
8171 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008172 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008173 bool Result = UnmatchedFields.erase(*I);
8174 (void) Result;
8175 assert(Result);
8176 break;
8177 }
8178 }
8179 if (I == E)
8180 return false;
8181 }
8182
8183 return UnmatchedFields.empty();
8184}
8185
8186bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8187 if (RD1->isUnion() != RD2->isUnion())
8188 return false;
8189
8190 if (RD1->isUnion())
8191 return isLayoutCompatibleUnion(C, RD1, RD2);
8192 else
8193 return isLayoutCompatibleStruct(C, RD1, RD2);
8194}
8195
8196/// \brief Check if two types are layout-compatible in C++11 sense.
8197bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8198 if (T1.isNull() || T2.isNull())
8199 return false;
8200
8201 // C++11 [basic.types] p11:
8202 // If two types T1 and T2 are the same type, then T1 and T2 are
8203 // layout-compatible types.
8204 if (C.hasSameType(T1, T2))
8205 return true;
8206
8207 T1 = T1.getCanonicalType().getUnqualifiedType();
8208 T2 = T2.getCanonicalType().getUnqualifiedType();
8209
8210 const Type::TypeClass TC1 = T1->getTypeClass();
8211 const Type::TypeClass TC2 = T2->getTypeClass();
8212
8213 if (TC1 != TC2)
8214 return false;
8215
8216 if (TC1 == Type::Enum) {
8217 return isLayoutCompatible(C,
8218 cast<EnumType>(T1)->getDecl(),
8219 cast<EnumType>(T2)->getDecl());
8220 } else if (TC1 == Type::Record) {
8221 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8222 return false;
8223
8224 return isLayoutCompatible(C,
8225 cast<RecordType>(T1)->getDecl(),
8226 cast<RecordType>(T2)->getDecl());
8227 }
8228
8229 return false;
8230}
8231}
8232
8233//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8234
8235namespace {
8236/// \brief Given a type tag expression find the type tag itself.
8237///
8238/// \param TypeExpr Type tag expression, as it appears in user's code.
8239///
8240/// \param VD Declaration of an identifier that appears in a type tag.
8241///
8242/// \param MagicValue Type tag magic value.
8243bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8244 const ValueDecl **VD, uint64_t *MagicValue) {
8245 while(true) {
8246 if (!TypeExpr)
8247 return false;
8248
8249 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8250
8251 switch (TypeExpr->getStmtClass()) {
8252 case Stmt::UnaryOperatorClass: {
8253 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8254 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8255 TypeExpr = UO->getSubExpr();
8256 continue;
8257 }
8258 return false;
8259 }
8260
8261 case Stmt::DeclRefExprClass: {
8262 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8263 *VD = DRE->getDecl();
8264 return true;
8265 }
8266
8267 case Stmt::IntegerLiteralClass: {
8268 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8269 llvm::APInt MagicValueAPInt = IL->getValue();
8270 if (MagicValueAPInt.getActiveBits() <= 64) {
8271 *MagicValue = MagicValueAPInt.getZExtValue();
8272 return true;
8273 } else
8274 return false;
8275 }
8276
8277 case Stmt::BinaryConditionalOperatorClass:
8278 case Stmt::ConditionalOperatorClass: {
8279 const AbstractConditionalOperator *ACO =
8280 cast<AbstractConditionalOperator>(TypeExpr);
8281 bool Result;
8282 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8283 if (Result)
8284 TypeExpr = ACO->getTrueExpr();
8285 else
8286 TypeExpr = ACO->getFalseExpr();
8287 continue;
8288 }
8289 return false;
8290 }
8291
8292 case Stmt::BinaryOperatorClass: {
8293 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8294 if (BO->getOpcode() == BO_Comma) {
8295 TypeExpr = BO->getRHS();
8296 continue;
8297 }
8298 return false;
8299 }
8300
8301 default:
8302 return false;
8303 }
8304 }
8305}
8306
8307/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8308///
8309/// \param TypeExpr Expression that specifies a type tag.
8310///
8311/// \param MagicValues Registered magic values.
8312///
8313/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8314/// kind.
8315///
8316/// \param TypeInfo Information about the corresponding C type.
8317///
8318/// \returns true if the corresponding C type was found.
8319bool GetMatchingCType(
8320 const IdentifierInfo *ArgumentKind,
8321 const Expr *TypeExpr, const ASTContext &Ctx,
8322 const llvm::DenseMap<Sema::TypeTagMagicValue,
8323 Sema::TypeTagData> *MagicValues,
8324 bool &FoundWrongKind,
8325 Sema::TypeTagData &TypeInfo) {
8326 FoundWrongKind = false;
8327
8328 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008329 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008330
8331 uint64_t MagicValue;
8332
8333 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8334 return false;
8335
8336 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008337 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008338 if (I->getArgumentKind() != ArgumentKind) {
8339 FoundWrongKind = true;
8340 return false;
8341 }
8342 TypeInfo.Type = I->getMatchingCType();
8343 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8344 TypeInfo.MustBeNull = I->getMustBeNull();
8345 return true;
8346 }
8347 return false;
8348 }
8349
8350 if (!MagicValues)
8351 return false;
8352
8353 llvm::DenseMap<Sema::TypeTagMagicValue,
8354 Sema::TypeTagData>::const_iterator I =
8355 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8356 if (I == MagicValues->end())
8357 return false;
8358
8359 TypeInfo = I->second;
8360 return true;
8361}
8362} // unnamed namespace
8363
8364void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8365 uint64_t MagicValue, QualType Type,
8366 bool LayoutCompatible,
8367 bool MustBeNull) {
8368 if (!TypeTagForDatatypeMagicValues)
8369 TypeTagForDatatypeMagicValues.reset(
8370 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8371
8372 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8373 (*TypeTagForDatatypeMagicValues)[Magic] =
8374 TypeTagData(Type, LayoutCompatible, MustBeNull);
8375}
8376
8377namespace {
8378bool IsSameCharType(QualType T1, QualType T2) {
8379 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8380 if (!BT1)
8381 return false;
8382
8383 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8384 if (!BT2)
8385 return false;
8386
8387 BuiltinType::Kind T1Kind = BT1->getKind();
8388 BuiltinType::Kind T2Kind = BT2->getKind();
8389
8390 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8391 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8392 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8393 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8394}
8395} // unnamed namespace
8396
8397void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8398 const Expr * const *ExprArgs) {
8399 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8400 bool IsPointerAttr = Attr->getIsPointer();
8401
8402 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8403 bool FoundWrongKind;
8404 TypeTagData TypeInfo;
8405 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8406 TypeTagForDatatypeMagicValues.get(),
8407 FoundWrongKind, TypeInfo)) {
8408 if (FoundWrongKind)
8409 Diag(TypeTagExpr->getExprLoc(),
8410 diag::warn_type_tag_for_datatype_wrong_kind)
8411 << TypeTagExpr->getSourceRange();
8412 return;
8413 }
8414
8415 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8416 if (IsPointerAttr) {
8417 // Skip implicit cast of pointer to `void *' (as a function argument).
8418 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008419 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008420 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008421 ArgumentExpr = ICE->getSubExpr();
8422 }
8423 QualType ArgumentType = ArgumentExpr->getType();
8424
8425 // Passing a `void*' pointer shouldn't trigger a warning.
8426 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8427 return;
8428
8429 if (TypeInfo.MustBeNull) {
8430 // Type tag with matching void type requires a null pointer.
8431 if (!ArgumentExpr->isNullPointerConstant(Context,
8432 Expr::NPC_ValueDependentIsNotNull)) {
8433 Diag(ArgumentExpr->getExprLoc(),
8434 diag::warn_type_safety_null_pointer_required)
8435 << ArgumentKind->getName()
8436 << ArgumentExpr->getSourceRange()
8437 << TypeTagExpr->getSourceRange();
8438 }
8439 return;
8440 }
8441
8442 QualType RequiredType = TypeInfo.Type;
8443 if (IsPointerAttr)
8444 RequiredType = Context.getPointerType(RequiredType);
8445
8446 bool mismatch = false;
8447 if (!TypeInfo.LayoutCompatible) {
8448 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8449
8450 // C++11 [basic.fundamental] p1:
8451 // Plain char, signed char, and unsigned char are three distinct types.
8452 //
8453 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8454 // char' depending on the current char signedness mode.
8455 if (mismatch)
8456 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8457 RequiredType->getPointeeType())) ||
8458 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8459 mismatch = false;
8460 } else
8461 if (IsPointerAttr)
8462 mismatch = !isLayoutCompatible(Context,
8463 ArgumentType->getPointeeType(),
8464 RequiredType->getPointeeType());
8465 else
8466 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8467
8468 if (mismatch)
8469 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008470 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008471 << TypeInfo.LayoutCompatible << RequiredType
8472 << ArgumentExpr->getSourceRange()
8473 << TypeTagExpr->getSourceRange();
8474}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008475