blob: c978a1e5b11705953b9e70b662ccab2ee6a36d57 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#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 {
Chris Lattnere925d612010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.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
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCalldadc5752010-08-24 06:29:42 +0000114ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000117
Chris Lattner3be167f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000142 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000147 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000154 if (SemaBuiltinUnorderedCompare(TheCall))
155 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000156 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
159 return ExprError();
160 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000166 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000167 return ExprError();
168 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000169 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000173 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000174 if (SemaBuiltinPrefetch(TheCall))
175 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000176 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000177 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000178 if (SemaBuiltinObjectSize(TheCall))
179 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000180 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
183 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000184 break;
John McCallbebede42011-02-26 05:39:39 +0000185
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
189 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000190 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000193 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000194 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000200 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000206 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000224 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000230 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000236 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000242 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000248 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000254 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000260 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000266 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000272 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000278 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000284 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000289#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000290 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000291 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000292 return ExprError();
293 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
296 return ExprError();
297 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000298 }
299
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000303 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307 return ExprError();
308 break;
Tim Northover2fe823a2013-08-01 09:23:19 +0000309 case llvm::Triple::aarch64:
Christian Pirker9b019ae2014-02-25 13:51:00 +0000310 case llvm::Triple::aarch64_be:
Tim Northover2fe823a2013-08-01 09:23:19 +0000311 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
312 return ExprError();
313 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000314 case llvm::Triple::mips:
315 case llvm::Triple::mipsel:
316 case llvm::Triple::mips64:
317 case llvm::Triple::mips64el:
318 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
319 return ExprError();
320 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000321 case llvm::Triple::x86:
322 case llvm::Triple::x86_64:
323 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
324 return ExprError();
325 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000326 default:
327 break;
328 }
329 }
330
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000331 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000332}
333
Nate Begeman91e1fea2010-06-14 05:21:25 +0000334// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000335static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000336 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000337 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000338 switch (Type.getEltType()) {
339 case NeonTypeFlags::Int8:
340 case NeonTypeFlags::Poly8:
341 return shift ? 7 : (8 << IsQuad) - 1;
342 case NeonTypeFlags::Int16:
343 case NeonTypeFlags::Poly16:
344 return shift ? 15 : (4 << IsQuad) - 1;
345 case NeonTypeFlags::Int32:
346 return shift ? 31 : (2 << IsQuad) - 1;
347 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000348 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000349 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000350 case NeonTypeFlags::Poly128:
351 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000352 case NeonTypeFlags::Float16:
353 assert(!shift && "cannot shift float types!");
354 return (4 << IsQuad) - 1;
355 case NeonTypeFlags::Float32:
356 assert(!shift && "cannot shift float types!");
357 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000358 case NeonTypeFlags::Float64:
359 assert(!shift && "cannot shift float types!");
360 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000361 }
David Blaikie8a40f702012-01-17 06:56:22 +0000362 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000363}
364
Bob Wilsone4d77232011-11-08 05:04:11 +0000365/// getNeonEltType - Return the QualType corresponding to the elements of
366/// the vector type specified by the NeonTypeFlags. This is used to check
367/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000368static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
369 bool IsAArch64) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000370 switch (Flags.getEltType()) {
371 case NeonTypeFlags::Int8:
372 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
373 case NeonTypeFlags::Int16:
374 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
375 case NeonTypeFlags::Int32:
376 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
377 case NeonTypeFlags::Int64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000378 if (IsAArch64)
379 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
380 else
381 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
382 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000383 case NeonTypeFlags::Poly8:
Kevin Qincaac85e2013-11-14 03:29:16 +0000384 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000385 case NeonTypeFlags::Poly16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000386 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
387 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000388 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000389 case NeonTypeFlags::Poly128:
390 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000391 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000392 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000393 case NeonTypeFlags::Float32:
394 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000395 case NeonTypeFlags::Float64:
396 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000397 }
David Blaikie8a40f702012-01-17 06:56:22 +0000398 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000399}
400
Tim Northover12670412014-02-19 10:37:05 +0000401bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000402 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000403 uint64_t mask = 0;
404 unsigned TV = 0;
405 int PtrArgNum = -1;
406 bool HasConstPtr = false;
407 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000408#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000409#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000410#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000411 }
412
413 // For NEON intrinsics which are overloaded on vector element type, validate
414 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000415 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000416 if (mask) {
417 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
418 return true;
419
420 TV = Result.getLimitedValue(64);
421 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
422 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000423 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000424 }
425
426 if (PtrArgNum >= 0) {
427 // Check that pointer arguments have the specified type.
428 Expr *Arg = TheCall->getArg(PtrArgNum);
429 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
430 Arg = ICE->getSubExpr();
431 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
432 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000433
434 bool IsAArch64 =
435 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::aarch64;
436 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, IsAArch64);
Tim Northover2fe823a2013-08-01 09:23:19 +0000437 if (HasConstPtr)
438 EltTy = EltTy.withConst();
439 QualType LHSTy = Context.getPointerType(EltTy);
440 AssignConvertType ConvTy;
441 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
442 if (RHS.isInvalid())
443 return true;
444 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
445 RHS.get(), AA_Assigning))
446 return true;
447 }
448
449 // For NEON intrinsics which take an immediate value as part of the
450 // instruction, range check them here.
451 unsigned i = 0, l = 0, u = 0;
452 switch (BuiltinID) {
453 default:
454 return false;
Tim Northover12670412014-02-19 10:37:05 +0000455#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000456#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000457#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000458 }
459 ;
460
461 // We can't check the value of a dependent argument.
462 if (TheCall->getArg(i)->isTypeDependent() ||
463 TheCall->getArg(i)->isValueDependent())
464 return false;
465
466 // Check that the immediate argument is actually a constant.
467 if (SemaBuiltinConstantArg(TheCall, i, Result))
468 return true;
469
470 // Range check against the upper/lower values for this isntruction.
471 unsigned Val = Result.getZExtValue();
472 if (Val < l || Val > (u + l))
473 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
474 << l << u + l << TheCall->getArg(i)->getSourceRange();
475
476 return false;
477}
478
Tim Northover12670412014-02-19 10:37:05 +0000479bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
480 CallExpr *TheCall) {
481 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
482 return true;
483
484 return false;
485}
486
Tim Northover6aacd492013-07-16 09:47:53 +0000487bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
488 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
489 BuiltinID == ARM::BI__builtin_arm_strex) &&
490 "unexpected ARM builtin");
491 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
492
493 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
494
495 // Ensure that we have the proper number of arguments.
496 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
497 return true;
498
499 // Inspect the pointer argument of the atomic builtin. This should always be
500 // a pointer type, whose element is an integral scalar or pointer type.
501 // Because it is a pointer type, we don't have to worry about any implicit
502 // casts here.
503 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
504 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
505 if (PointerArgRes.isInvalid())
506 return true;
507 PointerArg = PointerArgRes.take();
508
509 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
510 if (!pointerType) {
511 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
512 << PointerArg->getType() << PointerArg->getSourceRange();
513 return true;
514 }
515
516 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
517 // task is to insert the appropriate casts into the AST. First work out just
518 // what the appropriate type is.
519 QualType ValType = pointerType->getPointeeType();
520 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
521 if (IsLdrex)
522 AddrType.addConst();
523
524 // Issue a warning if the cast is dodgy.
525 CastKind CastNeeded = CK_NoOp;
526 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
527 CastNeeded = CK_BitCast;
528 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
529 << PointerArg->getType()
530 << Context.getPointerType(AddrType)
531 << AA_Passing << PointerArg->getSourceRange();
532 }
533
534 // Finally, do the cast and replace the argument with the corrected version.
535 AddrType = Context.getPointerType(AddrType);
536 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
537 if (PointerArgRes.isInvalid())
538 return true;
539 PointerArg = PointerArgRes.take();
540
541 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
542
543 // In general, we allow ints, floats and pointers to be loaded and stored.
544 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
545 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
546 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
547 << PointerArg->getType() << PointerArg->getSourceRange();
548 return true;
549 }
550
551 // But ARM doesn't have instructions to deal with 128-bit versions.
552 if (Context.getTypeSize(ValType) > 64) {
553 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
554 << PointerArg->getType() << PointerArg->getSourceRange();
555 return true;
556 }
557
558 switch (ValType.getObjCLifetime()) {
559 case Qualifiers::OCL_None:
560 case Qualifiers::OCL_ExplicitNone:
561 // okay
562 break;
563
564 case Qualifiers::OCL_Weak:
565 case Qualifiers::OCL_Strong:
566 case Qualifiers::OCL_Autoreleasing:
567 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
568 << ValType << PointerArg->getSourceRange();
569 return true;
570 }
571
572
573 if (IsLdrex) {
574 TheCall->setType(ValType);
575 return false;
576 }
577
578 // Initialize the argument to be stored.
579 ExprResult ValArg = TheCall->getArg(0);
580 InitializedEntity Entity = InitializedEntity::InitializeParameter(
581 Context, ValType, /*consume*/ false);
582 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
583 if (ValArg.isInvalid())
584 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000585 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000586
587 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
588 // but the custom checker bypasses all default analysis.
589 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000590 return false;
591}
592
Nate Begeman4904e322010-06-08 02:47:44 +0000593bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000594 llvm::APSInt Result;
595
Tim Northover6aacd492013-07-16 09:47:53 +0000596 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
597 BuiltinID == ARM::BI__builtin_arm_strex) {
598 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
599 }
600
Tim Northover12670412014-02-19 10:37:05 +0000601 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
602 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000603
Nate Begemand773fe62010-06-13 04:47:52 +0000604 // For NEON intrinsics which take an immediate value as part of the
605 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000606 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000607 switch (BuiltinID) {
608 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000609 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
610 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000611 case ARM::BI__builtin_arm_vcvtr_f:
612 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000613 case ARM::BI__builtin_arm_dmb:
614 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begemand773fe62010-06-13 04:47:52 +0000615 };
616
Douglas Gregor98c3cfc2012-06-29 01:05:22 +0000617 // We can't check the value of a dependent argument.
618 if (TheCall->getArg(i)->isTypeDependent() ||
619 TheCall->getArg(i)->isValueDependent())
620 return false;
621
Nate Begeman91e1fea2010-06-14 05:21:25 +0000622 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000623 if (SemaBuiltinConstantArg(TheCall, i, Result))
624 return true;
625
Nate Begeman91e1fea2010-06-14 05:21:25 +0000626 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000627 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000628 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000629 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000630 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000631
Nate Begemanf568b072010-08-03 21:32:34 +0000632 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000633 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000634}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000635
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000636bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
637 unsigned i = 0, l = 0, u = 0;
638 switch (BuiltinID) {
639 default: return false;
640 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
641 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000642 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
643 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
644 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
645 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
646 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000647 };
648
649 // We can't check the value of a dependent argument.
650 if (TheCall->getArg(i)->isTypeDependent() ||
651 TheCall->getArg(i)->isValueDependent())
652 return false;
653
654 // Check that the immediate argument is actually a constant.
655 llvm::APSInt Result;
656 if (SemaBuiltinConstantArg(TheCall, i, Result))
657 return true;
658
659 // Range check against the upper/lower values for this instruction.
660 unsigned Val = Result.getZExtValue();
661 if (Val < l || Val > u)
662 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
663 << l << u << TheCall->getArg(i)->getSourceRange();
664
665 return false;
666}
667
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000668bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
669 switch (BuiltinID) {
670 case X86::BI_mm_prefetch:
671 return SemaBuiltinMMPrefetch(TheCall);
672 break;
673 }
674 return false;
675}
676
Richard Smith55ce3522012-06-25 20:30:08 +0000677/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
678/// parameter with the FormatAttr's correct format_idx and firstDataArg.
679/// Returns true when the format fits the function and the FormatStringInfo has
680/// been populated.
681bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
682 FormatStringInfo *FSI) {
683 FSI->HasVAListArg = Format->getFirstArg() == 0;
684 FSI->FormatIdx = Format->getFormatIdx() - 1;
685 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000686
Richard Smith55ce3522012-06-25 20:30:08 +0000687 // The way the format attribute works in GCC, the implicit this argument
688 // of member functions is counted. However, it doesn't appear in our own
689 // lists, so decrement format_idx in that case.
690 if (IsCXXMember) {
691 if(FSI->FormatIdx == 0)
692 return false;
693 --FSI->FormatIdx;
694 if (FSI->FirstDataArg != 0)
695 --FSI->FirstDataArg;
696 }
697 return true;
698}
Mike Stump11289f42009-09-09 15:08:12 +0000699
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000700/// Checks if a the given expression evaluates to null.
701///
702/// \brief Returns true if the value evaluates to null.
703static bool CheckNonNullExpr(Sema &S,
704 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000705 // As a special case, transparent unions initialized with zero are
706 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000707 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000708 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
709 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000710 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000711 if (const InitListExpr *ILE =
712 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000713 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000714 }
715
716 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000717 return (!Expr->isValueDependent() &&
718 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
719 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000720}
721
722static void CheckNonNullArgument(Sema &S,
723 const Expr *ArgExpr,
724 SourceLocation CallSiteLoc) {
725 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000726 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
727}
728
Ted Kremenek2bc73332014-01-17 06:24:43 +0000729static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000730 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000731 const Expr * const *ExprArgs,
732 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000733 // Check the attributes attached to the method/function itself.
Ted Kremeneka146db32014-01-17 06:24:47 +0000734 for (specific_attr_iterator<NonNullAttr>
735 I = FDecl->specific_attr_begin<NonNullAttr>(),
736 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {
Ted Kremenek2bc73332014-01-17 06:24:43 +0000737
Ted Kremeneka146db32014-01-17 06:24:47 +0000738 const NonNullAttr *NonNull = *I;
739 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
740 e = NonNull->args_end();
741 i != e; ++i) {
742 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000743 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000744 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000745
746 // Check the attributes on the parameters.
747 ArrayRef<ParmVarDecl*> parms;
748 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
749 parms = FD->parameters();
750 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
751 parms = MD->parameters();
752
753 unsigned argIndex = 0;
754 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
755 I != E; ++I, ++argIndex) {
756 const ParmVarDecl *PVD = *I;
757 if (PVD->hasAttr<NonNullAttr>())
758 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
759 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000760}
761
Richard Smith55ce3522012-06-25 20:30:08 +0000762/// Handles the checks for format strings, non-POD arguments to vararg
763/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000764void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
765 unsigned NumParams, bool IsMemberFunction,
766 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000767 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000768 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000769 if (CurContext->isDependentContext())
770 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000771
Ted Kremenekb8176da2010-09-09 04:33:05 +0000772 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000773 llvm::SmallBitVector CheckedVarArgs;
774 if (FDecl) {
Richard Trieu41bc0992013-06-22 00:20:41 +0000775 for (specific_attr_iterator<FormatAttr>
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000776 I = FDecl->specific_attr_begin<FormatAttr>(),
777 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000778 I != E; ++I) {
779 // Only create vector if there are format attributes.
780 CheckedVarArgs.resize(Args.size());
781
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000782 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
783 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000784 }
Richard Smithd7293d72013-08-05 18:49:43 +0000785 }
Richard Smith55ce3522012-06-25 20:30:08 +0000786
787 // Refuse POD arguments that weren't caught by the format string
788 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000789 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000790 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000791 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000792 if (const Expr *Arg = Args[ArgIdx]) {
793 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
794 checkVariadicArgument(Arg, CallType);
795 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000796 }
Richard Smithd7293d72013-08-05 18:49:43 +0000797 }
Mike Stump11289f42009-09-09 15:08:12 +0000798
Richard Trieu41bc0992013-06-22 00:20:41 +0000799 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000800 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000801
Richard Trieu41bc0992013-06-22 00:20:41 +0000802 // Type safety checking.
803 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
804 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
805 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
806 i != e; ++i) {
807 CheckArgumentWithTypeTag(*i, Args.data());
808 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000809 }
Richard Smith55ce3522012-06-25 20:30:08 +0000810}
811
812/// CheckConstructorCall - Check a constructor call for correctness and safety
813/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000814void Sema::CheckConstructorCall(FunctionDecl *FDecl,
815 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000816 const FunctionProtoType *Proto,
817 SourceLocation Loc) {
818 VariadicCallType CallType =
819 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000820 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000821 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
822}
823
824/// CheckFunctionCall - Check a direct function call for various correctness
825/// and safety properties not strictly enforced by the C type system.
826bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
827 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000828 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
829 isa<CXXMethodDecl>(FDecl);
830 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
831 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000832 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
833 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000834 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000835 Expr** Args = TheCall->getArgs();
836 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000837 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000838 // If this is a call to a member operator, hide the first argument
839 // from checkCall.
840 // FIXME: Our choice of AST representation here is less than ideal.
841 ++Args;
842 --NumArgs;
843 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000844 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000845 IsMemberFunction, TheCall->getRParenLoc(),
846 TheCall->getCallee()->getSourceRange(), CallType);
847
848 IdentifierInfo *FnInfo = FDecl->getIdentifier();
849 // None of the checks below are needed for functions that don't have
850 // simple names (e.g., C++ conversion functions).
851 if (!FnInfo)
852 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000853
Anna Zaks22122702012-01-17 00:37:07 +0000854 unsigned CMId = FDecl->getMemoryFunctionKind();
855 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000856 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000857
Anna Zaks201d4892012-01-13 21:52:01 +0000858 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000859 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000860 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000861 else if (CMId == Builtin::BIstrncat)
862 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000863 else
Anna Zaks22122702012-01-17 00:37:07 +0000864 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000865
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000866 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000867}
868
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000869bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000870 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000871 VariadicCallType CallType =
872 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000873
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000874 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000875 /*IsMemberFunction=*/false,
876 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000877
878 return false;
879}
880
Richard Trieu664c4c62013-06-20 21:03:13 +0000881bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
882 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000883 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
884 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000885 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000886
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000887 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000888 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000889 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000890
Richard Trieu664c4c62013-06-20 21:03:13 +0000891 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000892 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000893 CallType = VariadicDoesNotApply;
894 } else if (Ty->isBlockPointerType()) {
895 CallType = VariadicBlock;
896 } else { // Ty->isFunctionPointerType()
897 CallType = VariadicFunction;
898 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000899 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000900
Alp Toker9cacbab2014-01-20 20:26:09 +0000901 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
902 TheCall->getNumArgs()),
903 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000904 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000905
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000906 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000907}
908
Richard Trieu41bc0992013-06-22 00:20:41 +0000909/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
910/// such as function pointers returned from functions.
911bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
912 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
913 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000914 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000915
Alp Toker9cacbab2014-01-20 20:26:09 +0000916 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
917 TheCall->getArgs(), TheCall->getNumArgs()),
918 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000919 TheCall->getCallee()->getSourceRange(), CallType);
920
921 return false;
922}
923
Richard Smithfeea8832012-04-12 05:08:17 +0000924ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
925 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000926 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
927 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000928
Richard Smithfeea8832012-04-12 05:08:17 +0000929 // All these operations take one of the following forms:
930 enum {
931 // C __c11_atomic_init(A *, C)
932 Init,
933 // C __c11_atomic_load(A *, int)
934 Load,
935 // void __atomic_load(A *, CP, int)
936 Copy,
937 // C __c11_atomic_add(A *, M, int)
938 Arithmetic,
939 // C __atomic_exchange_n(A *, CP, int)
940 Xchg,
941 // void __atomic_exchange(A *, C *, CP, int)
942 GNUXchg,
943 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
944 C11CmpXchg,
945 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
946 GNUCmpXchg
947 } Form = Init;
948 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
949 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
950 // where:
951 // C is an appropriate type,
952 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
953 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
954 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
955 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000956
Richard Smithfeea8832012-04-12 05:08:17 +0000957 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
958 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
959 && "need to update code for modified C11 atomics");
960 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
961 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
962 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
963 Op == AtomicExpr::AO__atomic_store_n ||
964 Op == AtomicExpr::AO__atomic_exchange_n ||
965 Op == AtomicExpr::AO__atomic_compare_exchange_n;
966 bool IsAddSub = false;
967
968 switch (Op) {
969 case AtomicExpr::AO__c11_atomic_init:
970 Form = Init;
971 break;
972
973 case AtomicExpr::AO__c11_atomic_load:
974 case AtomicExpr::AO__atomic_load_n:
975 Form = Load;
976 break;
977
978 case AtomicExpr::AO__c11_atomic_store:
979 case AtomicExpr::AO__atomic_load:
980 case AtomicExpr::AO__atomic_store:
981 case AtomicExpr::AO__atomic_store_n:
982 Form = Copy;
983 break;
984
985 case AtomicExpr::AO__c11_atomic_fetch_add:
986 case AtomicExpr::AO__c11_atomic_fetch_sub:
987 case AtomicExpr::AO__atomic_fetch_add:
988 case AtomicExpr::AO__atomic_fetch_sub:
989 case AtomicExpr::AO__atomic_add_fetch:
990 case AtomicExpr::AO__atomic_sub_fetch:
991 IsAddSub = true;
992 // Fall through.
993 case AtomicExpr::AO__c11_atomic_fetch_and:
994 case AtomicExpr::AO__c11_atomic_fetch_or:
995 case AtomicExpr::AO__c11_atomic_fetch_xor:
996 case AtomicExpr::AO__atomic_fetch_and:
997 case AtomicExpr::AO__atomic_fetch_or:
998 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +0000999 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001000 case AtomicExpr::AO__atomic_and_fetch:
1001 case AtomicExpr::AO__atomic_or_fetch:
1002 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001003 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001004 Form = Arithmetic;
1005 break;
1006
1007 case AtomicExpr::AO__c11_atomic_exchange:
1008 case AtomicExpr::AO__atomic_exchange_n:
1009 Form = Xchg;
1010 break;
1011
1012 case AtomicExpr::AO__atomic_exchange:
1013 Form = GNUXchg;
1014 break;
1015
1016 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1017 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1018 Form = C11CmpXchg;
1019 break;
1020
1021 case AtomicExpr::AO__atomic_compare_exchange:
1022 case AtomicExpr::AO__atomic_compare_exchange_n:
1023 Form = GNUCmpXchg;
1024 break;
1025 }
1026
1027 // Check we have the right number of arguments.
1028 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001029 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001030 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001031 << TheCall->getCallee()->getSourceRange();
1032 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001033 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1034 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001035 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001036 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001037 << TheCall->getCallee()->getSourceRange();
1038 return ExprError();
1039 }
1040
Richard Smithfeea8832012-04-12 05:08:17 +00001041 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001042 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001043 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1044 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1045 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001046 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001047 << Ptr->getType() << Ptr->getSourceRange();
1048 return ExprError();
1049 }
1050
Richard Smithfeea8832012-04-12 05:08:17 +00001051 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1052 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1053 QualType ValType = AtomTy; // 'C'
1054 if (IsC11) {
1055 if (!AtomTy->isAtomicType()) {
1056 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1057 << Ptr->getType() << Ptr->getSourceRange();
1058 return ExprError();
1059 }
Richard Smithe00921a2012-09-15 06:09:58 +00001060 if (AtomTy.isConstQualified()) {
1061 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1062 << Ptr->getType() << Ptr->getSourceRange();
1063 return ExprError();
1064 }
Richard Smithfeea8832012-04-12 05:08:17 +00001065 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001066 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001067
Richard Smithfeea8832012-04-12 05:08:17 +00001068 // For an arithmetic operation, the implied arithmetic must be well-formed.
1069 if (Form == Arithmetic) {
1070 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1071 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1072 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1073 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1074 return ExprError();
1075 }
1076 if (!IsAddSub && !ValType->isIntegerType()) {
1077 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1078 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1079 return ExprError();
1080 }
1081 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1082 // For __atomic_*_n operations, the value type must be a scalar integral or
1083 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001084 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001085 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1086 return ExprError();
1087 }
1088
Eli Friedmanaa769812013-09-11 03:49:34 +00001089 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1090 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001091 // For GNU atomics, require a trivially-copyable type. This is not part of
1092 // the GNU atomics specification, but we enforce it for sanity.
1093 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001094 << Ptr->getType() << Ptr->getSourceRange();
1095 return ExprError();
1096 }
1097
Richard Smithfeea8832012-04-12 05:08:17 +00001098 // FIXME: For any builtin other than a load, the ValType must not be
1099 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001100
1101 switch (ValType.getObjCLifetime()) {
1102 case Qualifiers::OCL_None:
1103 case Qualifiers::OCL_ExplicitNone:
1104 // okay
1105 break;
1106
1107 case Qualifiers::OCL_Weak:
1108 case Qualifiers::OCL_Strong:
1109 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001110 // FIXME: Can this happen? By this point, ValType should be known
1111 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001112 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1113 << ValType << Ptr->getSourceRange();
1114 return ExprError();
1115 }
1116
1117 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001118 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001119 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001120 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001121 ResultType = Context.BoolTy;
1122
Richard Smithfeea8832012-04-12 05:08:17 +00001123 // The type of a parameter passed 'by value'. In the GNU atomics, such
1124 // arguments are actually passed as pointers.
1125 QualType ByValType = ValType; // 'CP'
1126 if (!IsC11 && !IsN)
1127 ByValType = Ptr->getType();
1128
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001129 // The first argument --- the pointer --- has a fixed type; we
1130 // deduce the types of the rest of the arguments accordingly. Walk
1131 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001132 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001133 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001134 if (i < NumVals[Form] + 1) {
1135 switch (i) {
1136 case 1:
1137 // The second argument is the non-atomic operand. For arithmetic, this
1138 // is always passed by value, and for a compare_exchange it is always
1139 // passed by address. For the rest, GNU uses by-address and C11 uses
1140 // by-value.
1141 assert(Form != Load);
1142 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1143 Ty = ValType;
1144 else if (Form == Copy || Form == Xchg)
1145 Ty = ByValType;
1146 else if (Form == Arithmetic)
1147 Ty = Context.getPointerDiffType();
1148 else
1149 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1150 break;
1151 case 2:
1152 // The third argument to compare_exchange / GNU exchange is a
1153 // (pointer to a) desired value.
1154 Ty = ByValType;
1155 break;
1156 case 3:
1157 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1158 Ty = Context.BoolTy;
1159 break;
1160 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001161 } else {
1162 // The order(s) are always converted to int.
1163 Ty = Context.IntTy;
1164 }
Richard Smithfeea8832012-04-12 05:08:17 +00001165
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001166 InitializedEntity Entity =
1167 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001168 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001169 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1170 if (Arg.isInvalid())
1171 return true;
1172 TheCall->setArg(i, Arg.get());
1173 }
1174
Richard Smithfeea8832012-04-12 05:08:17 +00001175 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001176 SmallVector<Expr*, 5> SubExprs;
1177 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001178 switch (Form) {
1179 case Init:
1180 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001181 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001182 break;
1183 case Load:
1184 SubExprs.push_back(TheCall->getArg(1)); // Order
1185 break;
1186 case Copy:
1187 case Arithmetic:
1188 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001189 SubExprs.push_back(TheCall->getArg(2)); // Order
1190 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001191 break;
1192 case GNUXchg:
1193 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1194 SubExprs.push_back(TheCall->getArg(3)); // Order
1195 SubExprs.push_back(TheCall->getArg(1)); // Val1
1196 SubExprs.push_back(TheCall->getArg(2)); // Val2
1197 break;
1198 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001199 SubExprs.push_back(TheCall->getArg(3)); // Order
1200 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001201 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001202 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001203 break;
1204 case GNUCmpXchg:
1205 SubExprs.push_back(TheCall->getArg(4)); // Order
1206 SubExprs.push_back(TheCall->getArg(1)); // Val1
1207 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1208 SubExprs.push_back(TheCall->getArg(2)); // Val2
1209 SubExprs.push_back(TheCall->getArg(3)); // Weak
1210 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001211 }
Fariborz Jahanian615de762013-05-28 17:37:39 +00001212
1213 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1214 SubExprs, ResultType, Op,
1215 TheCall->getRParenLoc());
1216
1217 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1218 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1219 Context.AtomicUsesUnsupportedLibcall(AE))
1220 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1221 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001222
Fariborz Jahanian615de762013-05-28 17:37:39 +00001223 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001224}
1225
1226
John McCall29ad95b2011-08-27 01:09:30 +00001227/// checkBuiltinArgument - Given a call to a builtin function, perform
1228/// normal type-checking on the given argument, updating the call in
1229/// place. This is useful when a builtin function requires custom
1230/// type-checking for some of its arguments but not necessarily all of
1231/// them.
1232///
1233/// Returns true on error.
1234static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1235 FunctionDecl *Fn = E->getDirectCallee();
1236 assert(Fn && "builtin call without direct callee!");
1237
1238 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1239 InitializedEntity Entity =
1240 InitializedEntity::InitializeParameter(S.Context, Param);
1241
1242 ExprResult Arg = E->getArg(0);
1243 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1244 if (Arg.isInvalid())
1245 return true;
1246
1247 E->setArg(ArgIndex, Arg.take());
1248 return false;
1249}
1250
Chris Lattnerdc046542009-05-08 06:58:22 +00001251/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1252/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1253/// type of its first argument. The main ActOnCallExpr routines have already
1254/// promoted the types of arguments because all of these calls are prototyped as
1255/// void(...).
1256///
1257/// This function goes through and does final semantic checking for these
1258/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001259ExprResult
1260Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001261 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001262 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1263 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1264
1265 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001266 if (TheCall->getNumArgs() < 1) {
1267 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1268 << 0 << 1 << TheCall->getNumArgs()
1269 << TheCall->getCallee()->getSourceRange();
1270 return ExprError();
1271 }
Mike Stump11289f42009-09-09 15:08:12 +00001272
Chris Lattnerdc046542009-05-08 06:58:22 +00001273 // Inspect the first argument of the atomic builtin. This should always be
1274 // a pointer type, whose element is an integral scalar or pointer type.
1275 // Because it is a pointer type, we don't have to worry about any implicit
1276 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001277 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001278 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001279 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1280 if (FirstArgResult.isInvalid())
1281 return ExprError();
1282 FirstArg = FirstArgResult.take();
1283 TheCall->setArg(0, FirstArg);
1284
John McCall31168b02011-06-15 23:02:42 +00001285 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1286 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001287 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1288 << FirstArg->getType() << FirstArg->getSourceRange();
1289 return ExprError();
1290 }
Mike Stump11289f42009-09-09 15:08:12 +00001291
John McCall31168b02011-06-15 23:02:42 +00001292 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001293 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001294 !ValType->isBlockPointerType()) {
1295 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1296 << FirstArg->getType() << FirstArg->getSourceRange();
1297 return ExprError();
1298 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001299
John McCall31168b02011-06-15 23:02:42 +00001300 switch (ValType.getObjCLifetime()) {
1301 case Qualifiers::OCL_None:
1302 case Qualifiers::OCL_ExplicitNone:
1303 // okay
1304 break;
1305
1306 case Qualifiers::OCL_Weak:
1307 case Qualifiers::OCL_Strong:
1308 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001309 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001310 << ValType << FirstArg->getSourceRange();
1311 return ExprError();
1312 }
1313
John McCallb50451a2011-10-05 07:41:44 +00001314 // Strip any qualifiers off ValType.
1315 ValType = ValType.getUnqualifiedType();
1316
Chandler Carruth3973af72010-07-18 20:54:12 +00001317 // The majority of builtins return a value, but a few have special return
1318 // types, so allow them to override appropriately below.
1319 QualType ResultType = ValType;
1320
Chris Lattnerdc046542009-05-08 06:58:22 +00001321 // We need to figure out which concrete builtin this maps onto. For example,
1322 // __sync_fetch_and_add with a 2 byte object turns into
1323 // __sync_fetch_and_add_2.
1324#define BUILTIN_ROW(x) \
1325 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1326 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001327
Chris Lattnerdc046542009-05-08 06:58:22 +00001328 static const unsigned BuiltinIndices[][5] = {
1329 BUILTIN_ROW(__sync_fetch_and_add),
1330 BUILTIN_ROW(__sync_fetch_and_sub),
1331 BUILTIN_ROW(__sync_fetch_and_or),
1332 BUILTIN_ROW(__sync_fetch_and_and),
1333 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001334
Chris Lattnerdc046542009-05-08 06:58:22 +00001335 BUILTIN_ROW(__sync_add_and_fetch),
1336 BUILTIN_ROW(__sync_sub_and_fetch),
1337 BUILTIN_ROW(__sync_and_and_fetch),
1338 BUILTIN_ROW(__sync_or_and_fetch),
1339 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattnerdc046542009-05-08 06:58:22 +00001341 BUILTIN_ROW(__sync_val_compare_and_swap),
1342 BUILTIN_ROW(__sync_bool_compare_and_swap),
1343 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001344 BUILTIN_ROW(__sync_lock_release),
1345 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001346 };
Mike Stump11289f42009-09-09 15:08:12 +00001347#undef BUILTIN_ROW
1348
Chris Lattnerdc046542009-05-08 06:58:22 +00001349 // Determine the index of the size.
1350 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001351 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001352 case 1: SizeIndex = 0; break;
1353 case 2: SizeIndex = 1; break;
1354 case 4: SizeIndex = 2; break;
1355 case 8: SizeIndex = 3; break;
1356 case 16: SizeIndex = 4; break;
1357 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001358 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1359 << FirstArg->getType() << FirstArg->getSourceRange();
1360 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Chris Lattnerdc046542009-05-08 06:58:22 +00001363 // Each of these builtins has one pointer argument, followed by some number of
1364 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1365 // that we ignore. Find out which row of BuiltinIndices to read from as well
1366 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001367 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001368 unsigned BuiltinIndex, NumFixed = 1;
1369 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001370 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001371 case Builtin::BI__sync_fetch_and_add:
1372 case Builtin::BI__sync_fetch_and_add_1:
1373 case Builtin::BI__sync_fetch_and_add_2:
1374 case Builtin::BI__sync_fetch_and_add_4:
1375 case Builtin::BI__sync_fetch_and_add_8:
1376 case Builtin::BI__sync_fetch_and_add_16:
1377 BuiltinIndex = 0;
1378 break;
1379
1380 case Builtin::BI__sync_fetch_and_sub:
1381 case Builtin::BI__sync_fetch_and_sub_1:
1382 case Builtin::BI__sync_fetch_and_sub_2:
1383 case Builtin::BI__sync_fetch_and_sub_4:
1384 case Builtin::BI__sync_fetch_and_sub_8:
1385 case Builtin::BI__sync_fetch_and_sub_16:
1386 BuiltinIndex = 1;
1387 break;
1388
1389 case Builtin::BI__sync_fetch_and_or:
1390 case Builtin::BI__sync_fetch_and_or_1:
1391 case Builtin::BI__sync_fetch_and_or_2:
1392 case Builtin::BI__sync_fetch_and_or_4:
1393 case Builtin::BI__sync_fetch_and_or_8:
1394 case Builtin::BI__sync_fetch_and_or_16:
1395 BuiltinIndex = 2;
1396 break;
1397
1398 case Builtin::BI__sync_fetch_and_and:
1399 case Builtin::BI__sync_fetch_and_and_1:
1400 case Builtin::BI__sync_fetch_and_and_2:
1401 case Builtin::BI__sync_fetch_and_and_4:
1402 case Builtin::BI__sync_fetch_and_and_8:
1403 case Builtin::BI__sync_fetch_and_and_16:
1404 BuiltinIndex = 3;
1405 break;
Mike Stump11289f42009-09-09 15:08:12 +00001406
Douglas Gregor73722482011-11-28 16:30:08 +00001407 case Builtin::BI__sync_fetch_and_xor:
1408 case Builtin::BI__sync_fetch_and_xor_1:
1409 case Builtin::BI__sync_fetch_and_xor_2:
1410 case Builtin::BI__sync_fetch_and_xor_4:
1411 case Builtin::BI__sync_fetch_and_xor_8:
1412 case Builtin::BI__sync_fetch_and_xor_16:
1413 BuiltinIndex = 4;
1414 break;
1415
1416 case Builtin::BI__sync_add_and_fetch:
1417 case Builtin::BI__sync_add_and_fetch_1:
1418 case Builtin::BI__sync_add_and_fetch_2:
1419 case Builtin::BI__sync_add_and_fetch_4:
1420 case Builtin::BI__sync_add_and_fetch_8:
1421 case Builtin::BI__sync_add_and_fetch_16:
1422 BuiltinIndex = 5;
1423 break;
1424
1425 case Builtin::BI__sync_sub_and_fetch:
1426 case Builtin::BI__sync_sub_and_fetch_1:
1427 case Builtin::BI__sync_sub_and_fetch_2:
1428 case Builtin::BI__sync_sub_and_fetch_4:
1429 case Builtin::BI__sync_sub_and_fetch_8:
1430 case Builtin::BI__sync_sub_and_fetch_16:
1431 BuiltinIndex = 6;
1432 break;
1433
1434 case Builtin::BI__sync_and_and_fetch:
1435 case Builtin::BI__sync_and_and_fetch_1:
1436 case Builtin::BI__sync_and_and_fetch_2:
1437 case Builtin::BI__sync_and_and_fetch_4:
1438 case Builtin::BI__sync_and_and_fetch_8:
1439 case Builtin::BI__sync_and_and_fetch_16:
1440 BuiltinIndex = 7;
1441 break;
1442
1443 case Builtin::BI__sync_or_and_fetch:
1444 case Builtin::BI__sync_or_and_fetch_1:
1445 case Builtin::BI__sync_or_and_fetch_2:
1446 case Builtin::BI__sync_or_and_fetch_4:
1447 case Builtin::BI__sync_or_and_fetch_8:
1448 case Builtin::BI__sync_or_and_fetch_16:
1449 BuiltinIndex = 8;
1450 break;
1451
1452 case Builtin::BI__sync_xor_and_fetch:
1453 case Builtin::BI__sync_xor_and_fetch_1:
1454 case Builtin::BI__sync_xor_and_fetch_2:
1455 case Builtin::BI__sync_xor_and_fetch_4:
1456 case Builtin::BI__sync_xor_and_fetch_8:
1457 case Builtin::BI__sync_xor_and_fetch_16:
1458 BuiltinIndex = 9;
1459 break;
Mike Stump11289f42009-09-09 15:08:12 +00001460
Chris Lattnerdc046542009-05-08 06:58:22 +00001461 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001462 case Builtin::BI__sync_val_compare_and_swap_1:
1463 case Builtin::BI__sync_val_compare_and_swap_2:
1464 case Builtin::BI__sync_val_compare_and_swap_4:
1465 case Builtin::BI__sync_val_compare_and_swap_8:
1466 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001467 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001468 NumFixed = 2;
1469 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001470
Chris Lattnerdc046542009-05-08 06:58:22 +00001471 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001472 case Builtin::BI__sync_bool_compare_and_swap_1:
1473 case Builtin::BI__sync_bool_compare_and_swap_2:
1474 case Builtin::BI__sync_bool_compare_and_swap_4:
1475 case Builtin::BI__sync_bool_compare_and_swap_8:
1476 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001477 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001478 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001479 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001480 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001481
1482 case Builtin::BI__sync_lock_test_and_set:
1483 case Builtin::BI__sync_lock_test_and_set_1:
1484 case Builtin::BI__sync_lock_test_and_set_2:
1485 case Builtin::BI__sync_lock_test_and_set_4:
1486 case Builtin::BI__sync_lock_test_and_set_8:
1487 case Builtin::BI__sync_lock_test_and_set_16:
1488 BuiltinIndex = 12;
1489 break;
1490
Chris Lattnerdc046542009-05-08 06:58:22 +00001491 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001492 case Builtin::BI__sync_lock_release_1:
1493 case Builtin::BI__sync_lock_release_2:
1494 case Builtin::BI__sync_lock_release_4:
1495 case Builtin::BI__sync_lock_release_8:
1496 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001497 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001498 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001499 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001500 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001501
1502 case Builtin::BI__sync_swap:
1503 case Builtin::BI__sync_swap_1:
1504 case Builtin::BI__sync_swap_2:
1505 case Builtin::BI__sync_swap_4:
1506 case Builtin::BI__sync_swap_8:
1507 case Builtin::BI__sync_swap_16:
1508 BuiltinIndex = 14;
1509 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Chris Lattnerdc046542009-05-08 06:58:22 +00001512 // Now that we know how many fixed arguments we expect, first check that we
1513 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001514 if (TheCall->getNumArgs() < 1+NumFixed) {
1515 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1516 << 0 << 1+NumFixed << TheCall->getNumArgs()
1517 << TheCall->getCallee()->getSourceRange();
1518 return ExprError();
1519 }
Mike Stump11289f42009-09-09 15:08:12 +00001520
Chris Lattner5b9241b2009-05-08 15:36:58 +00001521 // Get the decl for the concrete builtin from this, we can tell what the
1522 // concrete integer type we should convert to is.
1523 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1524 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001525 FunctionDecl *NewBuiltinDecl;
1526 if (NewBuiltinID == BuiltinID)
1527 NewBuiltinDecl = FDecl;
1528 else {
1529 // Perform builtin lookup to avoid redeclaring it.
1530 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1531 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1532 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1533 assert(Res.getFoundDecl());
1534 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1535 if (NewBuiltinDecl == 0)
1536 return ExprError();
1537 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001538
John McCallcf142162010-08-07 06:22:56 +00001539 // The first argument --- the pointer --- has a fixed type; we
1540 // deduce the types of the rest of the arguments accordingly. Walk
1541 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001542 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001543 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001544
Chris Lattnerdc046542009-05-08 06:58:22 +00001545 // GCC does an implicit conversion to the pointer or integer ValType. This
1546 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001547 // Initialize the argument.
1548 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1549 ValType, /*consume*/ false);
1550 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001551 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001552 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001553
Chris Lattnerdc046542009-05-08 06:58:22 +00001554 // Okay, we have something that *can* be converted to the right type. Check
1555 // to see if there is a potentially weird extension going on here. This can
1556 // happen when you do an atomic operation on something like an char* and
1557 // pass in 42. The 42 gets converted to char. This is even more strange
1558 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001559 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001560 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001561 }
Mike Stump11289f42009-09-09 15:08:12 +00001562
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001563 ASTContext& Context = this->getASTContext();
1564
1565 // Create a new DeclRefExpr to refer to the new decl.
1566 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1567 Context,
1568 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001569 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001570 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001571 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001572 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001573 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001574 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001575
Chris Lattnerdc046542009-05-08 06:58:22 +00001576 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001577 // FIXME: This loses syntactic information.
1578 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1579 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1580 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001581 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001582
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001583 // Change the result type of the call to match the original value type. This
1584 // is arbitrary, but the codegen for these builtins ins design to handle it
1585 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001586 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001587
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001588 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001589}
1590
Chris Lattner6436fb62009-02-18 06:01:06 +00001591/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001592/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001593/// Note: It might also make sense to do the UTF-16 conversion here (would
1594/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001595bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001596 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001597 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1598
Douglas Gregorfb65e592011-07-27 05:40:30 +00001599 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001600 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1601 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001602 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001603 }
Mike Stump11289f42009-09-09 15:08:12 +00001604
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001605 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001606 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001607 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001608 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001609 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001610 UTF16 *ToPtr = &ToBuf[0];
1611
1612 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1613 &ToPtr, ToPtr + NumBytes,
1614 strictConversion);
1615 // Check for conversion failure.
1616 if (Result != conversionOK)
1617 Diag(Arg->getLocStart(),
1618 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1619 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001620 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001621}
1622
Chris Lattnere202e6a2007-12-20 00:05:45 +00001623/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1624/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001625bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1626 Expr *Fn = TheCall->getCallee();
1627 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001628 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001629 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001630 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1631 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001632 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001633 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001634 return true;
1635 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001636
1637 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001638 return Diag(TheCall->getLocEnd(),
1639 diag::err_typecheck_call_too_few_args_at_least)
1640 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001641 }
1642
John McCall29ad95b2011-08-27 01:09:30 +00001643 // Type-check the first argument normally.
1644 if (checkBuiltinArgument(*this, TheCall, 0))
1645 return true;
1646
Chris Lattnere202e6a2007-12-20 00:05:45 +00001647 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001648 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001649 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001650 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001651 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001652 else if (FunctionDecl *FD = getCurFunctionDecl())
1653 isVariadic = FD->isVariadic();
1654 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001655 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattnere202e6a2007-12-20 00:05:45 +00001657 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001658 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1659 return true;
1660 }
Mike Stump11289f42009-09-09 15:08:12 +00001661
Chris Lattner43be2e62007-12-19 23:59:04 +00001662 // Verify that the second argument to the builtin is the last argument of the
1663 // current function or method.
1664 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001665 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001666
Nico Weber9eea7642013-05-24 23:31:57 +00001667 // These are valid if SecondArgIsLastNamedArgument is false after the next
1668 // block.
1669 QualType Type;
1670 SourceLocation ParamLoc;
1671
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001672 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1673 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001674 // FIXME: This isn't correct for methods (results in bogus warning).
1675 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001676 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001677 if (CurBlock)
1678 LastArg = *(CurBlock->TheDecl->param_end()-1);
1679 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001680 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001681 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001682 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001683 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001684
1685 Type = PV->getType();
1686 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001687 }
1688 }
Mike Stump11289f42009-09-09 15:08:12 +00001689
Chris Lattner43be2e62007-12-19 23:59:04 +00001690 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001691 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001692 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001693 else if (Type->isReferenceType()) {
1694 Diag(Arg->getLocStart(),
1695 diag::warn_va_start_of_reference_type_is_undefined);
1696 Diag(ParamLoc, diag::note_parameter_type) << Type;
1697 }
1698
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001699 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001700 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001701}
Chris Lattner43be2e62007-12-19 23:59:04 +00001702
Chris Lattner2da14fb2007-12-20 00:26:33 +00001703/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1704/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001705bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1706 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001707 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001708 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001709 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001710 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001711 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001712 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001713 << SourceRange(TheCall->getArg(2)->getLocStart(),
1714 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001715
John Wiegley01296292011-04-08 18:41:53 +00001716 ExprResult OrigArg0 = TheCall->getArg(0);
1717 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001718
Chris Lattner2da14fb2007-12-20 00:26:33 +00001719 // Do standard promotions between the two arguments, returning their common
1720 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001721 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001722 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1723 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001724
1725 // Make sure any conversions are pushed back into the call; this is
1726 // type safe since unordered compare builtins are declared as "_Bool
1727 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001728 TheCall->setArg(0, OrigArg0.get());
1729 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001730
John Wiegley01296292011-04-08 18:41:53 +00001731 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001732 return false;
1733
Chris Lattner2da14fb2007-12-20 00:26:33 +00001734 // If the common type isn't a real floating type, then the arguments were
1735 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001736 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001737 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001738 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001739 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1740 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001741
Chris Lattner2da14fb2007-12-20 00:26:33 +00001742 return false;
1743}
1744
Benjamin Kramer634fc102010-02-15 22:42:31 +00001745/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1746/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001747/// to check everything. We expect the last argument to be a floating point
1748/// value.
1749bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1750 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001751 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001752 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001753 if (TheCall->getNumArgs() > NumArgs)
1754 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001755 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001756 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001757 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001758 (*(TheCall->arg_end()-1))->getLocEnd());
1759
Benjamin Kramer64aae502010-02-16 10:07:31 +00001760 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001761
Eli Friedman7e4faac2009-08-31 20:06:00 +00001762 if (OrigArg->isTypeDependent())
1763 return false;
1764
Chris Lattner68784ef2010-05-06 05:50:07 +00001765 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001766 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001767 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001768 diag::err_typecheck_call_invalid_unary_fp)
1769 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001770
Chris Lattner68784ef2010-05-06 05:50:07 +00001771 // If this is an implicit conversion from float -> double, remove it.
1772 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1773 Expr *CastArg = Cast->getSubExpr();
1774 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1775 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1776 "promotion from float to double is the only expected cast here");
1777 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001778 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001779 }
1780 }
1781
Eli Friedman7e4faac2009-08-31 20:06:00 +00001782 return false;
1783}
1784
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001785/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1786// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001787ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001788 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001789 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001790 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001791 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1792 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001793
Nate Begemana0110022010-06-08 00:16:34 +00001794 // Determine which of the following types of shufflevector we're checking:
1795 // 1) unary, vector mask: (lhs, mask)
1796 // 2) binary, vector mask: (lhs, rhs, mask)
1797 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1798 QualType resType = TheCall->getArg(0)->getType();
1799 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001800
Douglas Gregorc25f7662009-05-19 22:10:17 +00001801 if (!TheCall->getArg(0)->isTypeDependent() &&
1802 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001803 QualType LHSType = TheCall->getArg(0)->getType();
1804 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001805
Craig Topperbaca3892013-07-29 06:47:04 +00001806 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1807 return ExprError(Diag(TheCall->getLocStart(),
1808 diag::err_shufflevector_non_vector)
1809 << SourceRange(TheCall->getArg(0)->getLocStart(),
1810 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001811
Nate Begemana0110022010-06-08 00:16:34 +00001812 numElements = LHSType->getAs<VectorType>()->getNumElements();
1813 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001814
Nate Begemana0110022010-06-08 00:16:34 +00001815 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1816 // with mask. If so, verify that RHS is an integer vector type with the
1817 // same number of elts as lhs.
1818 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001819 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001820 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001821 return ExprError(Diag(TheCall->getLocStart(),
1822 diag::err_shufflevector_incompatible_vector)
1823 << SourceRange(TheCall->getArg(1)->getLocStart(),
1824 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001825 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001826 return ExprError(Diag(TheCall->getLocStart(),
1827 diag::err_shufflevector_incompatible_vector)
1828 << SourceRange(TheCall->getArg(0)->getLocStart(),
1829 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001830 } else if (numElements != numResElements) {
1831 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001832 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001833 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001834 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001835 }
1836
1837 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001838 if (TheCall->getArg(i)->isTypeDependent() ||
1839 TheCall->getArg(i)->isValueDependent())
1840 continue;
1841
Nate Begemana0110022010-06-08 00:16:34 +00001842 llvm::APSInt Result(32);
1843 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1844 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001845 diag::err_shufflevector_nonconstant_argument)
1846 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001847
Craig Topper50ad5b72013-08-03 17:40:38 +00001848 // Allow -1 which will be translated to undef in the IR.
1849 if (Result.isSigned() && Result.isAllOnesValue())
1850 continue;
1851
Chris Lattner7ab824e2008-08-10 02:05:13 +00001852 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001853 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001854 diag::err_shufflevector_argument_too_large)
1855 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001856 }
1857
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001858 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001859
Chris Lattner7ab824e2008-08-10 02:05:13 +00001860 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001861 exprs.push_back(TheCall->getArg(i));
1862 TheCall->setArg(i, 0);
1863 }
1864
Benjamin Kramerc215e762012-08-24 11:54:20 +00001865 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001866 TheCall->getCallee()->getLocStart(),
1867 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001868}
Chris Lattner43be2e62007-12-19 23:59:04 +00001869
Hal Finkelc4d7c822013-09-18 03:29:45 +00001870/// SemaConvertVectorExpr - Handle __builtin_convertvector
1871ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1872 SourceLocation BuiltinLoc,
1873 SourceLocation RParenLoc) {
1874 ExprValueKind VK = VK_RValue;
1875 ExprObjectKind OK = OK_Ordinary;
1876 QualType DstTy = TInfo->getType();
1877 QualType SrcTy = E->getType();
1878
1879 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1880 return ExprError(Diag(BuiltinLoc,
1881 diag::err_convertvector_non_vector)
1882 << E->getSourceRange());
1883 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1884 return ExprError(Diag(BuiltinLoc,
1885 diag::err_convertvector_non_vector_type));
1886
1887 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1888 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1889 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1890 if (SrcElts != DstElts)
1891 return ExprError(Diag(BuiltinLoc,
1892 diag::err_convertvector_incompatible_vector)
1893 << E->getSourceRange());
1894 }
1895
1896 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1897 BuiltinLoc, RParenLoc));
1898
1899}
1900
Daniel Dunbarb7257262008-07-21 22:59:13 +00001901/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1902// This is declared to take (const void*, ...) and can take two
1903// optional constant int args.
1904bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001905 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001906
Chris Lattner3b054132008-11-19 05:08:23 +00001907 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001908 return Diag(TheCall->getLocEnd(),
1909 diag::err_typecheck_call_too_many_args_at_most)
1910 << 0 /*function call*/ << 3 << NumArgs
1911 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001912
1913 // Argument 0 is checked for us and the remaining arguments must be
1914 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001915 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001916 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001917
1918 // We can't check the value of a dependent argument.
1919 if (Arg->isTypeDependent() || Arg->isValueDependent())
1920 continue;
1921
Eli Friedman5efba262009-12-04 00:30:06 +00001922 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001923 if (SemaBuiltinConstantArg(TheCall, i, Result))
1924 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001925
Daniel Dunbarb7257262008-07-21 22:59:13 +00001926 // FIXME: gcc issues a warning and rewrites these to 0. These
1927 // seems especially odd for the third argument since the default
1928 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001929 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001930 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001931 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001932 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001933 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001934 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001935 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001936 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001937 }
1938 }
1939
Chris Lattner3b054132008-11-19 05:08:23 +00001940 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001941}
1942
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001943/// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
1944// This is declared to take (const char*, int)
1945bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
1946 Expr *Arg = TheCall->getArg(1);
1947
1948 // We can't check the value of a dependent argument.
1949 if (Arg->isTypeDependent() || Arg->isValueDependent())
1950 return false;
1951
1952 llvm::APSInt Result;
1953 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1954 return true;
1955
1956 if (Result.getLimitedValue() > 3)
1957 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1958 << "0" << "3" << Arg->getSourceRange();
1959
1960 return false;
1961}
1962
Eric Christopher8d0c6212010-04-17 02:26:23 +00001963/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1964/// TheCall is a constant expression.
1965bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1966 llvm::APSInt &Result) {
1967 Expr *Arg = TheCall->getArg(ArgNum);
1968 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1969 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1970
1971 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1972
1973 if (!Arg->isIntegerConstantExpr(Result, Context))
1974 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001975 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001976
Chris Lattnerd545ad12009-09-23 06:06:36 +00001977 return false;
1978}
1979
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001980/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1981/// int type). This simply type checks that type is one of the defined
1982/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001983// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001984bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001985 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001986
1987 // We can't check the value of a dependent argument.
1988 if (TheCall->getArg(1)->isTypeDependent() ||
1989 TheCall->getArg(1)->isValueDependent())
1990 return false;
1991
Eric Christopher8d0c6212010-04-17 02:26:23 +00001992 // Check constant-ness first.
1993 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1994 return true;
1995
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001996 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001997 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001998 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1999 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002000 }
2001
2002 return false;
2003}
2004
Eli Friedmanc97d0142009-05-03 06:04:26 +00002005/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002006/// This checks that val is a constant 1.
2007bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2008 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002009 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002010
Eric Christopher8d0c6212010-04-17 02:26:23 +00002011 // TODO: This is less than ideal. Overload this to take a value.
2012 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2013 return true;
2014
2015 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002016 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2017 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2018
2019 return false;
2020}
2021
Richard Smithd7293d72013-08-05 18:49:43 +00002022namespace {
2023enum StringLiteralCheckType {
2024 SLCT_NotALiteral,
2025 SLCT_UncheckedLiteral,
2026 SLCT_CheckedLiteral
2027};
2028}
2029
Richard Smith55ce3522012-06-25 20:30:08 +00002030// Determine if an expression is a string literal or constant string.
2031// If this function returns false on the arguments to a function expecting a
2032// format string, we will usually need to emit a warning.
2033// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002034static StringLiteralCheckType
2035checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2036 bool HasVAListArg, unsigned format_idx,
2037 unsigned firstDataArg, Sema::FormatStringType Type,
2038 Sema::VariadicCallType CallType, bool InFunctionCall,
2039 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002040 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002041 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002042 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002043
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002044 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002045
Richard Smithd7293d72013-08-05 18:49:43 +00002046 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002047 // Technically -Wformat-nonliteral does not warn about this case.
2048 // The behavior of printf and friends in this case is implementation
2049 // dependent. Ideally if the format string cannot be null then
2050 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002051 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002052
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002053 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002054 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002055 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002056 // The expression is a literal if both sub-expressions were, and it was
2057 // completely checked only if both sub-expressions were checked.
2058 const AbstractConditionalOperator *C =
2059 cast<AbstractConditionalOperator>(E);
2060 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002061 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002062 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002063 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002064 if (Left == SLCT_NotALiteral)
2065 return SLCT_NotALiteral;
2066 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002067 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002068 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002069 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002070 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002071 }
2072
2073 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002074 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2075 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002076 }
2077
John McCallc07a0c72011-02-17 10:25:35 +00002078 case Stmt::OpaqueValueExprClass:
2079 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2080 E = src;
2081 goto tryAgain;
2082 }
Richard Smith55ce3522012-06-25 20:30:08 +00002083 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002084
Ted Kremeneka8890832011-02-24 23:03:04 +00002085 case Stmt::PredefinedExprClass:
2086 // While __func__, etc., are technically not string literals, they
2087 // cannot contain format specifiers and thus are not a security
2088 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002089 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002090
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002091 case Stmt::DeclRefExprClass: {
2092 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002093
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002094 // As an exception, do not flag errors for variables binding to
2095 // const string literals.
2096 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2097 bool isConstant = false;
2098 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002099
Richard Smithd7293d72013-08-05 18:49:43 +00002100 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2101 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002102 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002103 isConstant = T.isConstant(S.Context) &&
2104 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002105 } else if (T->isObjCObjectPointerType()) {
2106 // In ObjC, there is usually no "const ObjectPointer" type,
2107 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002108 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002109 }
Mike Stump11289f42009-09-09 15:08:12 +00002110
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002111 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002112 if (const Expr *Init = VD->getAnyInitializer()) {
2113 // Look through initializers like const char c[] = { "foo" }
2114 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2115 if (InitList->isStringLiteralInit())
2116 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2117 }
Richard Smithd7293d72013-08-05 18:49:43 +00002118 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002119 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002120 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002121 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002122 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002123 }
Mike Stump11289f42009-09-09 15:08:12 +00002124
Anders Carlssonb012ca92009-06-28 19:55:58 +00002125 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2126 // special check to see if the format string is a function parameter
2127 // of the function calling the printf function. If the function
2128 // has an attribute indicating it is a printf-like function, then we
2129 // should suppress warnings concerning non-literals being used in a call
2130 // to a vprintf function. For example:
2131 //
2132 // void
2133 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2134 // va_list ap;
2135 // va_start(ap, fmt);
2136 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2137 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002138 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002139 if (HasVAListArg) {
2140 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2141 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2142 int PVIndex = PV->getFunctionScopeIndex() + 1;
2143 for (specific_attr_iterator<FormatAttr>
2144 i = ND->specific_attr_begin<FormatAttr>(),
2145 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2146 FormatAttr *PVFormat = *i;
2147 // adjust for implicit parameter
2148 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2149 if (MD->isInstance())
2150 ++PVIndex;
2151 // We also check if the formats are compatible.
2152 // We can't pass a 'scanf' string to a 'printf' function.
2153 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002154 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002155 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002156 }
2157 }
2158 }
2159 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002160 }
Mike Stump11289f42009-09-09 15:08:12 +00002161
Richard Smith55ce3522012-06-25 20:30:08 +00002162 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002163 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002164
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002165 case Stmt::CallExprClass:
2166 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002167 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002168 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2169 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2170 unsigned ArgIndex = FA->getFormatIdx();
2171 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2172 if (MD->isInstance())
2173 --ArgIndex;
2174 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002175
Richard Smithd7293d72013-08-05 18:49:43 +00002176 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002177 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002178 Type, CallType, InFunctionCall,
2179 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002180 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2181 unsigned BuiltinID = FD->getBuiltinID();
2182 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2183 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2184 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002185 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002186 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002187 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002188 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002189 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002190 }
2191 }
Mike Stump11289f42009-09-09 15:08:12 +00002192
Richard Smith55ce3522012-06-25 20:30:08 +00002193 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002194 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002195 case Stmt::ObjCStringLiteralClass:
2196 case Stmt::StringLiteralClass: {
2197 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002198
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002199 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002200 StrE = ObjCFExpr->getString();
2201 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002202 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002203
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002204 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002205 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2206 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002207 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002208 }
Mike Stump11289f42009-09-09 15:08:12 +00002209
Richard Smith55ce3522012-06-25 20:30:08 +00002210 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002211 }
Mike Stump11289f42009-09-09 15:08:12 +00002212
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002213 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002214 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002215 }
2216}
2217
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002218Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002219 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002220 .Case("scanf", FST_Scanf)
2221 .Cases("printf", "printf0", FST_Printf)
2222 .Cases("NSString", "CFString", FST_NSString)
2223 .Case("strftime", FST_Strftime)
2224 .Case("strfmon", FST_Strfmon)
2225 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2226 .Default(FST_Unknown);
2227}
2228
Jordan Rose3e0ec582012-07-19 18:10:23 +00002229/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002230/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002231/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002232bool Sema::CheckFormatArguments(const FormatAttr *Format,
2233 ArrayRef<const Expr *> Args,
2234 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002235 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002236 SourceLocation Loc, SourceRange Range,
2237 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002238 FormatStringInfo FSI;
2239 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002240 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002241 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002242 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002243 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002244}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002245
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002246bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002247 bool HasVAListArg, unsigned format_idx,
2248 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002249 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002250 SourceLocation Loc, SourceRange Range,
2251 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002252 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002253 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002254 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002255 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002256 }
Mike Stump11289f42009-09-09 15:08:12 +00002257
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002258 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002259
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002260 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002261 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002262 // Dynamically generated format strings are difficult to
2263 // automatically vet at compile time. Requiring that format strings
2264 // are string literals: (1) permits the checking of format strings by
2265 // the compiler and thereby (2) can practically remove the source of
2266 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002267
Mike Stump11289f42009-09-09 15:08:12 +00002268 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002269 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002270 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002271 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002272 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002273 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2274 format_idx, firstDataArg, Type, CallType,
2275 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002276 if (CT != SLCT_NotALiteral)
2277 // Literal format string found, check done!
2278 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002279
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002280 // Strftime is particular as it always uses a single 'time' argument,
2281 // so it is safe to pass a non-literal string.
2282 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002283 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002284
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002285 // Do not emit diag when the string param is a macro expansion and the
2286 // format is either NSString or CFString. This is a hack to prevent
2287 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2288 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002289 if (Type == FST_NSString &&
2290 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002291 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002292
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002293 // If there are no arguments specified, warn with -Wformat-security, otherwise
2294 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002295 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002296 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002297 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002298 << OrigFormatExpr->getSourceRange();
2299 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002300 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002301 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002302 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002303 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002304}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002305
Ted Kremenekab278de2010-01-28 23:39:18 +00002306namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002307class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2308protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002309 Sema &S;
2310 const StringLiteral *FExpr;
2311 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002312 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002313 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002314 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002315 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002316 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002317 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002318 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002319 bool usesPositionalArgs;
2320 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002321 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002322 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002323 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002324public:
Ted Kremenek02087932010-07-16 02:11:22 +00002325 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002326 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002327 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002328 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002329 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002330 Sema::VariadicCallType callType,
2331 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002332 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002333 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2334 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002335 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002336 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002337 inFunctionCall(inFunctionCall), CallType(callType),
2338 CheckedVarArgs(CheckedVarArgs) {
2339 CoveredArgs.resize(numDataArgs);
2340 CoveredArgs.reset();
2341 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002342
Ted Kremenek019d2242010-01-29 01:50:07 +00002343 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002344
Ted Kremenek02087932010-07-16 02:11:22 +00002345 void HandleIncompleteSpecifier(const char *startSpecifier,
2346 unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002347
Jordan Rose92303592012-09-08 04:00:03 +00002348 void HandleInvalidLengthModifier(
2349 const analyze_format_string::FormatSpecifier &FS,
2350 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002351 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002352
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002353 void HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002354 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002355 const char *startSpecifier, unsigned specifierLen);
2356
2357 void HandleNonStandardConversionSpecifier(
2358 const analyze_format_string::ConversionSpecifier &CS,
2359 const char *startSpecifier, unsigned specifierLen);
2360
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002361 virtual void HandlePosition(const char *startPos, unsigned posLen);
2362
Ted Kremenekd1668192010-02-27 01:41:03 +00002363 virtual void HandleInvalidPosition(const char *startSpecifier,
2364 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00002365 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00002366
2367 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2368
Ted Kremenekab278de2010-01-28 23:39:18 +00002369 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002370
Richard Trieu03cf7b72011-10-28 00:41:25 +00002371 template <typename Range>
2372 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2373 const Expr *ArgumentExpr,
2374 PartialDiagnostic PDiag,
2375 SourceLocation StringLoc,
2376 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002377 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002378
Ted Kremenek02087932010-07-16 02:11:22 +00002379protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002380 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2381 const char *startSpec,
2382 unsigned specifierLen,
2383 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002384
2385 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2386 const char *startSpec,
2387 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002388
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002389 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002390 CharSourceRange getSpecifierRange(const char *startSpecifier,
2391 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002392 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002393
Ted Kremenek5739de72010-01-29 01:06:55 +00002394 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002395
2396 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2397 const analyze_format_string::ConversionSpecifier &CS,
2398 const char *startSpecifier, unsigned specifierLen,
2399 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002400
2401 template <typename Range>
2402 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2403 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002404 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002405
2406 void CheckPositionalAndNonpositionalArgs(
2407 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00002408};
2409}
2410
Ted Kremenek02087932010-07-16 02:11:22 +00002411SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002412 return OrigFormatExpr->getSourceRange();
2413}
2414
Ted Kremenek02087932010-07-16 02:11:22 +00002415CharSourceRange CheckFormatHandler::
2416getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002417 SourceLocation Start = getLocationOfByte(startSpecifier);
2418 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2419
2420 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002421 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002422
2423 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002424}
2425
Ted Kremenek02087932010-07-16 02:11:22 +00002426SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002427 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002428}
2429
Ted Kremenek02087932010-07-16 02:11:22 +00002430void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2431 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002432 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2433 getLocationOfByte(startSpecifier),
2434 /*IsStringLocation*/true,
2435 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002436}
2437
Jordan Rose92303592012-09-08 04:00:03 +00002438void CheckFormatHandler::HandleInvalidLengthModifier(
2439 const analyze_format_string::FormatSpecifier &FS,
2440 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002441 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002442 using namespace analyze_format_string;
2443
2444 const LengthModifier &LM = FS.getLengthModifier();
2445 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2446
2447 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002448 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002449 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002450 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002451 getLocationOfByte(LM.getStart()),
2452 /*IsStringLocation*/true,
2453 getSpecifierRange(startSpecifier, specifierLen));
2454
2455 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2456 << FixedLM->toString()
2457 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2458
2459 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002460 FixItHint Hint;
2461 if (DiagID == diag::warn_format_nonsensical_length)
2462 Hint = FixItHint::CreateRemoval(LMRange);
2463
2464 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002465 getLocationOfByte(LM.getStart()),
2466 /*IsStringLocation*/true,
2467 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002468 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002469 }
2470}
2471
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002472void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002473 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002474 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002475 using namespace analyze_format_string;
2476
2477 const LengthModifier &LM = FS.getLengthModifier();
2478 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2479
2480 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002481 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002482 if (FixedLM) {
2483 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2484 << LM.toString() << 0,
2485 getLocationOfByte(LM.getStart()),
2486 /*IsStringLocation*/true,
2487 getSpecifierRange(startSpecifier, specifierLen));
2488
2489 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2490 << FixedLM->toString()
2491 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2492
2493 } else {
2494 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2495 << LM.toString() << 0,
2496 getLocationOfByte(LM.getStart()),
2497 /*IsStringLocation*/true,
2498 getSpecifierRange(startSpecifier, specifierLen));
2499 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002500}
2501
2502void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2503 const analyze_format_string::ConversionSpecifier &CS,
2504 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002505 using namespace analyze_format_string;
2506
2507 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002508 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002509 if (FixedCS) {
2510 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2511 << CS.toString() << /*conversion specifier*/1,
2512 getLocationOfByte(CS.getStart()),
2513 /*IsStringLocation*/true,
2514 getSpecifierRange(startSpecifier, specifierLen));
2515
2516 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2517 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2518 << FixedCS->toString()
2519 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2520 } else {
2521 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2522 << CS.toString() << /*conversion specifier*/1,
2523 getLocationOfByte(CS.getStart()),
2524 /*IsStringLocation*/true,
2525 getSpecifierRange(startSpecifier, specifierLen));
2526 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002527}
2528
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002529void CheckFormatHandler::HandlePosition(const char *startPos,
2530 unsigned posLen) {
2531 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2532 getLocationOfByte(startPos),
2533 /*IsStringLocation*/true,
2534 getSpecifierRange(startPos, posLen));
2535}
2536
Ted Kremenekd1668192010-02-27 01:41:03 +00002537void
Ted Kremenek02087932010-07-16 02:11:22 +00002538CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2539 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002540 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2541 << (unsigned) p,
2542 getLocationOfByte(startPos), /*IsStringLocation*/true,
2543 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002544}
2545
Ted Kremenek02087932010-07-16 02:11:22 +00002546void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002547 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002548 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2549 getLocationOfByte(startPos),
2550 /*IsStringLocation*/true,
2551 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002552}
2553
Ted Kremenek02087932010-07-16 02:11:22 +00002554void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002555 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002556 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002557 EmitFormatDiagnostic(
2558 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2559 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2560 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002561 }
Ted Kremenek02087932010-07-16 02:11:22 +00002562}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002563
Jordan Rose58bbe422012-07-19 18:10:08 +00002564// Note that this may return NULL if there was an error parsing or building
2565// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002566const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002567 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002568}
2569
2570void CheckFormatHandler::DoneProcessing() {
2571 // Does the number of data arguments exceed the number of
2572 // format conversions in the format string?
2573 if (!HasVAListArg) {
2574 // Find any arguments that weren't covered.
2575 CoveredArgs.flip();
2576 signed notCoveredArg = CoveredArgs.find_first();
2577 if (notCoveredArg >= 0) {
2578 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002579 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2580 SourceLocation Loc = E->getLocStart();
2581 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2582 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2583 Loc, /*IsStringLocation*/false,
2584 getFormatStringRange());
2585 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002586 }
Ted Kremenek02087932010-07-16 02:11:22 +00002587 }
2588 }
2589}
2590
Ted Kremenekce815422010-07-19 21:25:57 +00002591bool
2592CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2593 SourceLocation Loc,
2594 const char *startSpec,
2595 unsigned specifierLen,
2596 const char *csStart,
2597 unsigned csLen) {
2598
2599 bool keepGoing = true;
2600 if (argIndex < NumDataArgs) {
2601 // Consider the argument coverered, even though the specifier doesn't
2602 // make sense.
2603 CoveredArgs.set(argIndex);
2604 }
2605 else {
2606 // If argIndex exceeds the number of data arguments we
2607 // don't issue a warning because that is just a cascade of warnings (and
2608 // they may have intended '%%' anyway). We don't want to continue processing
2609 // the format string after this point, however, as we will like just get
2610 // gibberish when trying to match arguments.
2611 keepGoing = false;
2612 }
2613
Richard Trieu03cf7b72011-10-28 00:41:25 +00002614 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2615 << StringRef(csStart, csLen),
2616 Loc, /*IsStringLocation*/true,
2617 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002618
2619 return keepGoing;
2620}
2621
Richard Trieu03cf7b72011-10-28 00:41:25 +00002622void
2623CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2624 const char *startSpec,
2625 unsigned specifierLen) {
2626 EmitFormatDiagnostic(
2627 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2628 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2629}
2630
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002631bool
2632CheckFormatHandler::CheckNumArgs(
2633 const analyze_format_string::FormatSpecifier &FS,
2634 const analyze_format_string::ConversionSpecifier &CS,
2635 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2636
2637 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002638 PartialDiagnostic PDiag = FS.usesPositionalArg()
2639 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2640 << (argIndex+1) << NumDataArgs)
2641 : S.PDiag(diag::warn_printf_insufficient_data_args);
2642 EmitFormatDiagnostic(
2643 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2644 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002645 return false;
2646 }
2647 return true;
2648}
2649
Richard Trieu03cf7b72011-10-28 00:41:25 +00002650template<typename Range>
2651void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2652 SourceLocation Loc,
2653 bool IsStringLocation,
2654 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002655 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002656 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002657 Loc, IsStringLocation, StringRange, FixIt);
2658}
2659
2660/// \brief If the format string is not within the funcion call, emit a note
2661/// so that the function call and string are in diagnostic messages.
2662///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002663/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002664/// call and only one diagnostic message will be produced. Otherwise, an
2665/// extra note will be emitted pointing to location of the format string.
2666///
2667/// \param ArgumentExpr the expression that is passed as the format string
2668/// argument in the function call. Used for getting locations when two
2669/// diagnostics are emitted.
2670///
2671/// \param PDiag the callee should already have provided any strings for the
2672/// diagnostic message. This function only adds locations and fixits
2673/// to diagnostics.
2674///
2675/// \param Loc primary location for diagnostic. If two diagnostics are
2676/// required, one will be at Loc and a new SourceLocation will be created for
2677/// the other one.
2678///
2679/// \param IsStringLocation if true, Loc points to the format string should be
2680/// used for the note. Otherwise, Loc points to the argument list and will
2681/// be used with PDiag.
2682///
2683/// \param StringRange some or all of the string to highlight. This is
2684/// templated so it can accept either a CharSourceRange or a SourceRange.
2685///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002686/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002687template<typename Range>
2688void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2689 const Expr *ArgumentExpr,
2690 PartialDiagnostic PDiag,
2691 SourceLocation Loc,
2692 bool IsStringLocation,
2693 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002694 ArrayRef<FixItHint> FixIt) {
2695 if (InFunctionCall) {
2696 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2697 D << StringRange;
2698 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2699 I != E; ++I) {
2700 D << *I;
2701 }
2702 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002703 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2704 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002705
2706 const Sema::SemaDiagnosticBuilder &Note =
2707 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2708 diag::note_format_string_defined);
2709
2710 Note << StringRange;
2711 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2712 I != E; ++I) {
2713 Note << *I;
2714 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002715 }
2716}
2717
Ted Kremenek02087932010-07-16 02:11:22 +00002718//===--- CHECK: Printf format string checking ------------------------------===//
2719
2720namespace {
2721class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002722 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002723public:
2724 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2725 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002726 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002727 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002728 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002729 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002730 Sema::VariadicCallType CallType,
2731 llvm::SmallBitVector &CheckedVarArgs)
2732 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2733 numDataArgs, beg, hasVAListArg, Args,
2734 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2735 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002736 {}
2737
Ted Kremenek02087932010-07-16 02:11:22 +00002738
2739 bool HandleInvalidPrintfConversionSpecifier(
2740 const analyze_printf::PrintfSpecifier &FS,
2741 const char *startSpecifier,
2742 unsigned specifierLen);
2743
2744 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2745 const char *startSpecifier,
2746 unsigned specifierLen);
Richard Smith55ce3522012-06-25 20:30:08 +00002747 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2748 const char *StartSpecifier,
2749 unsigned SpecifierLen,
2750 const Expr *E);
2751
Ted Kremenek02087932010-07-16 02:11:22 +00002752 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2753 const char *startSpecifier, unsigned specifierLen);
2754 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2755 const analyze_printf::OptionalAmount &Amt,
2756 unsigned type,
2757 const char *startSpecifier, unsigned specifierLen);
2758 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2759 const analyze_printf::OptionalFlag &flag,
2760 const char *startSpecifier, unsigned specifierLen);
2761 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2762 const analyze_printf::OptionalFlag &ignoredFlag,
2763 const analyze_printf::OptionalFlag &flag,
2764 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002765 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith55ce3522012-06-25 20:30:08 +00002766 const Expr *E, const CharSourceRange &CSR);
2767
Ted Kremenek02087932010-07-16 02:11:22 +00002768};
2769}
2770
2771bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2772 const analyze_printf::PrintfSpecifier &FS,
2773 const char *startSpecifier,
2774 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002775 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002776 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002777
Ted Kremenekce815422010-07-19 21:25:57 +00002778 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2779 getLocationOfByte(CS.getStart()),
2780 startSpecifier, specifierLen,
2781 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002782}
2783
Ted Kremenek02087932010-07-16 02:11:22 +00002784bool CheckPrintfHandler::HandleAmount(
2785 const analyze_format_string::OptionalAmount &Amt,
2786 unsigned k, const char *startSpecifier,
2787 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002788
2789 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002790 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002791 unsigned argIndex = Amt.getArgIndex();
2792 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002793 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2794 << k,
2795 getLocationOfByte(Amt.getStart()),
2796 /*IsStringLocation*/true,
2797 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002798 // Don't do any more checking. We will just emit
2799 // spurious errors.
2800 return false;
2801 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002802
Ted Kremenek5739de72010-01-29 01:06:55 +00002803 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002804 // Although not in conformance with C99, we also allow the argument to be
2805 // an 'unsigned int' as that is a reasonably safe case. GCC also
2806 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002807 CoveredArgs.set(argIndex);
2808 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002809 if (!Arg)
2810 return false;
2811
Ted Kremenek5739de72010-01-29 01:06:55 +00002812 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002813
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002814 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2815 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002816
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002817 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002818 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002819 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002820 << T << Arg->getSourceRange(),
2821 getLocationOfByte(Amt.getStart()),
2822 /*IsStringLocation*/true,
2823 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002824 // Don't do any more checking. We will just emit
2825 // spurious errors.
2826 return false;
2827 }
2828 }
2829 }
2830 return true;
2831}
Ted Kremenek5739de72010-01-29 01:06:55 +00002832
Tom Careb49ec692010-06-17 19:00:27 +00002833void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002834 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002835 const analyze_printf::OptionalAmount &Amt,
2836 unsigned type,
2837 const char *startSpecifier,
2838 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002839 const analyze_printf::PrintfConversionSpecifier &CS =
2840 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002841
Richard Trieu03cf7b72011-10-28 00:41:25 +00002842 FixItHint fixit =
2843 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2844 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2845 Amt.getConstantLength()))
2846 : FixItHint();
2847
2848 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2849 << type << CS.toString(),
2850 getLocationOfByte(Amt.getStart()),
2851 /*IsStringLocation*/true,
2852 getSpecifierRange(startSpecifier, specifierLen),
2853 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002854}
2855
Ted Kremenek02087932010-07-16 02:11:22 +00002856void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002857 const analyze_printf::OptionalFlag &flag,
2858 const char *startSpecifier,
2859 unsigned specifierLen) {
2860 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002861 const analyze_printf::PrintfConversionSpecifier &CS =
2862 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002863 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2864 << flag.toString() << CS.toString(),
2865 getLocationOfByte(flag.getPosition()),
2866 /*IsStringLocation*/true,
2867 getSpecifierRange(startSpecifier, specifierLen),
2868 FixItHint::CreateRemoval(
2869 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002870}
2871
2872void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002873 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002874 const analyze_printf::OptionalFlag &ignoredFlag,
2875 const analyze_printf::OptionalFlag &flag,
2876 const char *startSpecifier,
2877 unsigned specifierLen) {
2878 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002879 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2880 << ignoredFlag.toString() << flag.toString(),
2881 getLocationOfByte(ignoredFlag.getPosition()),
2882 /*IsStringLocation*/true,
2883 getSpecifierRange(startSpecifier, specifierLen),
2884 FixItHint::CreateRemoval(
2885 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002886}
2887
Richard Smith55ce3522012-06-25 20:30:08 +00002888// Determines if the specified is a C++ class or struct containing
2889// a member with the specified name and kind (e.g. a CXXMethodDecl named
2890// "c_str()").
2891template<typename MemberKind>
2892static llvm::SmallPtrSet<MemberKind*, 1>
2893CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2894 const RecordType *RT = Ty->getAs<RecordType>();
2895 llvm::SmallPtrSet<MemberKind*, 1> Results;
2896
2897 if (!RT)
2898 return Results;
2899 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2900 if (!RD)
2901 return Results;
2902
2903 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2904 Sema::LookupMemberName);
2905
2906 // We just need to include all members of the right kind turned up by the
2907 // filter, at this point.
2908 if (S.LookupQualifiedName(R, RT->getDecl()))
2909 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2910 NamedDecl *decl = (*I)->getUnderlyingDecl();
2911 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2912 Results.insert(FK);
2913 }
2914 return Results;
2915}
2916
2917// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002918// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002919// Returns true when a c_str() conversion method is found.
2920bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002921 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith55ce3522012-06-25 20:30:08 +00002922 const CharSourceRange &CSR) {
2923 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2924
2925 MethodSet Results =
2926 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2927
2928 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2929 MI != ME; ++MI) {
2930 const CXXMethodDecl *Method = *MI;
2931 if (Method->getNumParams() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002932 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002933 // FIXME: Suggest parens if the expression needs them.
2934 SourceLocation EndLoc =
2935 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2936 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2937 << "c_str()"
2938 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2939 return true;
2940 }
2941 }
2942
2943 return false;
2944}
2945
Ted Kremenekab278de2010-01-28 23:39:18 +00002946bool
Ted Kremenek02087932010-07-16 02:11:22 +00002947CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002948 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002949 const char *startSpecifier,
2950 unsigned specifierLen) {
2951
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002952 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002953 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002954 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002955
Ted Kremenek6cd69422010-07-19 22:01:06 +00002956 if (FS.consumesDataArgument()) {
2957 if (atFirstArg) {
2958 atFirstArg = false;
2959 usesPositionalArgs = FS.usesPositionalArg();
2960 }
2961 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002962 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2963 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002964 return false;
2965 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002966 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002967
Ted Kremenekd1668192010-02-27 01:41:03 +00002968 // First check if the field width, precision, and conversion specifier
2969 // have matching data arguments.
2970 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2971 startSpecifier, specifierLen)) {
2972 return false;
2973 }
2974
2975 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2976 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002977 return false;
2978 }
2979
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002980 if (!CS.consumesDataArgument()) {
2981 // FIXME: Technically specifying a precision or field width here
2982 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002983 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002984 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002985
Ted Kremenek4a49d982010-02-26 19:18:41 +00002986 // Consume the argument.
2987 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002988 if (argIndex < NumDataArgs) {
2989 // The check to see if the argIndex is valid will come later.
2990 // We set the bit here because we may exit early from this
2991 // function if we encounter some other error.
2992 CoveredArgs.set(argIndex);
2993 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002994
2995 // Check for using an Objective-C specific conversion specifier
2996 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002997 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002998 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2999 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003000 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003001
Tom Careb49ec692010-06-17 19:00:27 +00003002 // Check for invalid use of field width
3003 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003004 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003005 startSpecifier, specifierLen);
3006 }
3007
3008 // Check for invalid use of precision
3009 if (!FS.hasValidPrecision()) {
3010 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3011 startSpecifier, specifierLen);
3012 }
3013
3014 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003015 if (!FS.hasValidThousandsGroupingPrefix())
3016 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003017 if (!FS.hasValidLeadingZeros())
3018 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3019 if (!FS.hasValidPlusPrefix())
3020 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003021 if (!FS.hasValidSpacePrefix())
3022 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003023 if (!FS.hasValidAlternativeForm())
3024 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3025 if (!FS.hasValidLeftJustified())
3026 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3027
3028 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003029 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3030 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3031 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003032 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3033 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3034 startSpecifier, specifierLen);
3035
3036 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003037 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003038 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3039 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003040 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003041 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003042 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003043 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3044 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003045
Jordan Rose92303592012-09-08 04:00:03 +00003046 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3047 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3048
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003049 // The remaining checks depend on the data arguments.
3050 if (HasVAListArg)
3051 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003052
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003053 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003054 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003055
Jordan Rose58bbe422012-07-19 18:10:08 +00003056 const Expr *Arg = getDataArg(argIndex);
3057 if (!Arg)
3058 return true;
3059
3060 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003061}
3062
Jordan Roseaee34382012-09-05 22:56:26 +00003063static bool requiresParensToAddCast(const Expr *E) {
3064 // FIXME: We should have a general way to reason about operator
3065 // precedence and whether parens are actually needed here.
3066 // Take care of a few common cases where they aren't.
3067 const Expr *Inside = E->IgnoreImpCasts();
3068 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3069 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3070
3071 switch (Inside->getStmtClass()) {
3072 case Stmt::ArraySubscriptExprClass:
3073 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003074 case Stmt::CharacterLiteralClass:
3075 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003076 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003077 case Stmt::FloatingLiteralClass:
3078 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003079 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003080 case Stmt::ObjCArrayLiteralClass:
3081 case Stmt::ObjCBoolLiteralExprClass:
3082 case Stmt::ObjCBoxedExprClass:
3083 case Stmt::ObjCDictionaryLiteralClass:
3084 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003085 case Stmt::ObjCIvarRefExprClass:
3086 case Stmt::ObjCMessageExprClass:
3087 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003088 case Stmt::ObjCStringLiteralClass:
3089 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003090 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003091 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003092 case Stmt::UnaryOperatorClass:
3093 return false;
3094 default:
3095 return true;
3096 }
3097}
3098
Richard Smith55ce3522012-06-25 20:30:08 +00003099bool
3100CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3101 const char *StartSpecifier,
3102 unsigned SpecifierLen,
3103 const Expr *E) {
3104 using namespace analyze_format_string;
3105 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003106 // Now type check the data expression that matches the
3107 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003108 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3109 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003110 if (!AT.isValid())
3111 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003112
Jordan Rose598ec092012-12-05 18:44:40 +00003113 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003114 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3115 ExprTy = TET->getUnderlyingExpr()->getType();
3116 }
3117
Jordan Rose598ec092012-12-05 18:44:40 +00003118 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003119 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003120
Jordan Rose22b74712012-09-05 22:56:19 +00003121 // Look through argument promotions for our error message's reported type.
3122 // This includes the integral and floating promotions, but excludes array
3123 // and function pointer decay; seeing that an argument intended to be a
3124 // string has type 'char [6]' is probably more confusing than 'char *'.
3125 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3126 if (ICE->getCastKind() == CK_IntegralCast ||
3127 ICE->getCastKind() == CK_FloatingCast) {
3128 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003129 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003130
3131 // Check if we didn't match because of an implicit cast from a 'char'
3132 // or 'short' to an 'int'. This is done because printf is a varargs
3133 // function.
3134 if (ICE->getType() == S.Context.IntTy ||
3135 ICE->getType() == S.Context.UnsignedIntTy) {
3136 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003137 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003138 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003139 }
Jordan Rose98709982012-06-04 22:48:57 +00003140 }
Jordan Rose598ec092012-12-05 18:44:40 +00003141 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3142 // Special case for 'a', which has type 'int' in C.
3143 // Note, however, that we do /not/ want to treat multibyte constants like
3144 // 'MooV' as characters! This form is deprecated but still exists.
3145 if (ExprTy == S.Context.IntTy)
3146 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3147 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003148 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003149
Jordan Rose0e5badd2012-12-05 18:44:49 +00003150 // %C in an Objective-C context prints a unichar, not a wchar_t.
3151 // If the argument is an integer of some kind, believe the %C and suggest
3152 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003153 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003154 if (ObjCContext &&
3155 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3156 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3157 !ExprTy->isCharType()) {
3158 // 'unichar' is defined as a typedef of unsigned short, but we should
3159 // prefer using the typedef if it is visible.
3160 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003161
3162 // While we are here, check if the value is an IntegerLiteral that happens
3163 // to be within the valid range.
3164 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3165 const llvm::APInt &V = IL->getValue();
3166 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3167 return true;
3168 }
3169
Jordan Rose0e5badd2012-12-05 18:44:49 +00003170 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3171 Sema::LookupOrdinaryName);
3172 if (S.LookupName(Result, S.getCurScope())) {
3173 NamedDecl *ND = Result.getFoundDecl();
3174 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3175 if (TD->getUnderlyingType() == IntendedTy)
3176 IntendedTy = S.Context.getTypedefType(TD);
3177 }
3178 }
3179 }
3180
3181 // Special-case some of Darwin's platform-independence types by suggesting
3182 // casts to primitive types that are known to be large enough.
3183 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003184 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003185 // Use a 'while' to peel off layers of typedefs.
3186 QualType TyTy = IntendedTy;
3187 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003188 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003189 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003190 .Case("NSInteger", S.Context.LongTy)
3191 .Case("NSUInteger", S.Context.UnsignedLongTy)
3192 .Case("SInt32", S.Context.IntTy)
3193 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003194 .Default(QualType());
3195
3196 if (!CastTy.isNull()) {
3197 ShouldNotPrintDirectly = true;
3198 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003199 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003200 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003201 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003202 }
3203 }
3204
Jordan Rose22b74712012-09-05 22:56:19 +00003205 // We may be able to offer a FixItHint if it is a supported type.
3206 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003207 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003208 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003209
Jordan Rose22b74712012-09-05 22:56:19 +00003210 if (success) {
3211 // Get the fix string from the fixed format specifier
3212 SmallString<16> buf;
3213 llvm::raw_svector_ostream os(buf);
3214 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003215
Jordan Roseaee34382012-09-05 22:56:26 +00003216 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3217
Jordan Rose0e5badd2012-12-05 18:44:49 +00003218 if (IntendedTy == ExprTy) {
3219 // In this case, the specifier is wrong and should be changed to match
3220 // the argument.
3221 EmitFormatDiagnostic(
3222 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3223 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3224 << E->getSourceRange(),
3225 E->getLocStart(),
3226 /*IsStringLocation*/false,
3227 SpecRange,
3228 FixItHint::CreateReplacement(SpecRange, os.str()));
3229
3230 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003231 // The canonical type for formatting this value is different from the
3232 // actual type of the expression. (This occurs, for example, with Darwin's
3233 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3234 // should be printed as 'long' for 64-bit compatibility.)
3235 // Rather than emitting a normal format/argument mismatch, we want to
3236 // add a cast to the recommended type (and correct the format string
3237 // if necessary).
3238 SmallString<16> CastBuf;
3239 llvm::raw_svector_ostream CastFix(CastBuf);
3240 CastFix << "(";
3241 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3242 CastFix << ")";
3243
3244 SmallVector<FixItHint,4> Hints;
3245 if (!AT.matchesType(S.Context, IntendedTy))
3246 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3247
3248 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3249 // If there's already a cast present, just replace it.
3250 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3251 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3252
3253 } else if (!requiresParensToAddCast(E)) {
3254 // If the expression has high enough precedence,
3255 // just write the C-style cast.
3256 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3257 CastFix.str()));
3258 } else {
3259 // Otherwise, add parens around the expression as well as the cast.
3260 CastFix << "(";
3261 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3262 CastFix.str()));
3263
3264 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3265 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3266 }
3267
Jordan Rose0e5badd2012-12-05 18:44:49 +00003268 if (ShouldNotPrintDirectly) {
3269 // The expression has a type that should not be printed directly.
3270 // We extract the name from the typedef because we don't want to show
3271 // the underlying type in the diagnostic.
3272 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003273
Jordan Rose0e5badd2012-12-05 18:44:49 +00003274 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3275 << Name << IntendedTy
3276 << E->getSourceRange(),
3277 E->getLocStart(), /*IsStringLocation=*/false,
3278 SpecRange, Hints);
3279 } else {
3280 // In this case, the expression could be printed using a different
3281 // specifier, but we've decided that the specifier is probably correct
3282 // and we should cast instead. Just use the normal warning message.
3283 EmitFormatDiagnostic(
3284 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3285 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3286 << E->getSourceRange(),
3287 E->getLocStart(), /*IsStringLocation*/false,
3288 SpecRange, Hints);
3289 }
Jordan Roseaee34382012-09-05 22:56:26 +00003290 }
Jordan Rose22b74712012-09-05 22:56:19 +00003291 } else {
3292 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3293 SpecifierLen);
3294 // Since the warning for passing non-POD types to variadic functions
3295 // was deferred until now, we emit a warning for non-POD
3296 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003297 switch (S.isValidVarArgType(ExprTy)) {
3298 case Sema::VAK_Valid:
3299 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003300 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003301 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3302 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3303 << CSR
3304 << E->getSourceRange(),
3305 E->getLocStart(), /*IsStringLocation*/false, CSR);
3306 break;
3307
3308 case Sema::VAK_Undefined:
3309 EmitFormatDiagnostic(
3310 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003311 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003312 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003313 << CallType
3314 << AT.getRepresentativeTypeName(S.Context)
3315 << CSR
3316 << E->getSourceRange(),
3317 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose22b74712012-09-05 22:56:19 +00003318 checkForCStrMembers(AT, E, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00003319 break;
3320
3321 case Sema::VAK_Invalid:
3322 if (ExprTy->isObjCObjectType())
3323 EmitFormatDiagnostic(
3324 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3325 << S.getLangOpts().CPlusPlus11
3326 << ExprTy
3327 << CallType
3328 << AT.getRepresentativeTypeName(S.Context)
3329 << CSR
3330 << E->getSourceRange(),
3331 E->getLocStart(), /*IsStringLocation*/false, CSR);
3332 else
3333 // FIXME: If this is an initializer list, suggest removing the braces
3334 // or inserting a cast to the target type.
3335 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3336 << isa<InitListExpr>(E) << ExprTy << CallType
3337 << AT.getRepresentativeTypeName(S.Context)
3338 << E->getSourceRange();
3339 break;
3340 }
3341
3342 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3343 "format string specifier index out of range");
3344 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003345 }
3346
Ted Kremenekab278de2010-01-28 23:39:18 +00003347 return true;
3348}
3349
Ted Kremenek02087932010-07-16 02:11:22 +00003350//===--- CHECK: Scanf format string checking ------------------------------===//
3351
3352namespace {
3353class CheckScanfHandler : public CheckFormatHandler {
3354public:
3355 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3356 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003357 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003358 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003359 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003360 Sema::VariadicCallType CallType,
3361 llvm::SmallBitVector &CheckedVarArgs)
3362 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3363 numDataArgs, beg, hasVAListArg,
3364 Args, formatIdx, inFunctionCall, CallType,
3365 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003366 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003367
3368 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3369 const char *startSpecifier,
3370 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003371
3372 bool HandleInvalidScanfConversionSpecifier(
3373 const analyze_scanf::ScanfSpecifier &FS,
3374 const char *startSpecifier,
3375 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003376
3377 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00003378};
Ted Kremenek019d2242010-01-29 01:50:07 +00003379}
Ted Kremenekab278de2010-01-28 23:39:18 +00003380
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003381void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3382 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003383 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3384 getLocationOfByte(end), /*IsStringLocation*/true,
3385 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003386}
3387
Ted Kremenekce815422010-07-19 21:25:57 +00003388bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3389 const analyze_scanf::ScanfSpecifier &FS,
3390 const char *startSpecifier,
3391 unsigned specifierLen) {
3392
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003393 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003394 FS.getConversionSpecifier();
3395
3396 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3397 getLocationOfByte(CS.getStart()),
3398 startSpecifier, specifierLen,
3399 CS.getStart(), CS.getLength());
3400}
3401
Ted Kremenek02087932010-07-16 02:11:22 +00003402bool CheckScanfHandler::HandleScanfSpecifier(
3403 const analyze_scanf::ScanfSpecifier &FS,
3404 const char *startSpecifier,
3405 unsigned specifierLen) {
3406
3407 using namespace analyze_scanf;
3408 using namespace analyze_format_string;
3409
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003410 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003411
Ted Kremenek6cd69422010-07-19 22:01:06 +00003412 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3413 // be used to decide if we are using positional arguments consistently.
3414 if (FS.consumesDataArgument()) {
3415 if (atFirstArg) {
3416 atFirstArg = false;
3417 usesPositionalArgs = FS.usesPositionalArg();
3418 }
3419 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003420 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3421 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003422 return false;
3423 }
Ted Kremenek02087932010-07-16 02:11:22 +00003424 }
3425
3426 // Check if the field with is non-zero.
3427 const OptionalAmount &Amt = FS.getFieldWidth();
3428 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3429 if (Amt.getConstantAmount() == 0) {
3430 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3431 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003432 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3433 getLocationOfByte(Amt.getStart()),
3434 /*IsStringLocation*/true, R,
3435 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003436 }
3437 }
3438
3439 if (!FS.consumesDataArgument()) {
3440 // FIXME: Technically specifying a precision or field width here
3441 // makes no sense. Worth issuing a warning at some point.
3442 return true;
3443 }
3444
3445 // Consume the argument.
3446 unsigned argIndex = FS.getArgIndex();
3447 if (argIndex < NumDataArgs) {
3448 // The check to see if the argIndex is valid will come later.
3449 // We set the bit here because we may exit early from this
3450 // function if we encounter some other error.
3451 CoveredArgs.set(argIndex);
3452 }
3453
Ted Kremenek4407ea42010-07-20 20:04:47 +00003454 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003455 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003456 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3457 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003458 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003459 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003460 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003461 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3462 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003463
Jordan Rose92303592012-09-08 04:00:03 +00003464 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3465 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3466
Ted Kremenek02087932010-07-16 02:11:22 +00003467 // The remaining checks depend on the data arguments.
3468 if (HasVAListArg)
3469 return true;
3470
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003471 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003472 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003473
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003474 // Check that the argument type matches the format specifier.
3475 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003476 if (!Ex)
3477 return true;
3478
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003479 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3480 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003481 ScanfSpecifier fixedFS = FS;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003482 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgd99d6882012-02-15 09:59:46 +00003483 S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003484
3485 if (success) {
3486 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003487 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003488 llvm::raw_svector_ostream os(buf);
3489 fixedFS.toString(os);
3490
3491 EmitFormatDiagnostic(
3492 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003493 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003494 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003495 Ex->getLocStart(),
3496 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003497 getSpecifierRange(startSpecifier, specifierLen),
3498 FixItHint::CreateReplacement(
3499 getSpecifierRange(startSpecifier, specifierLen),
3500 os.str()));
3501 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003502 EmitFormatDiagnostic(
3503 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003504 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003505 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003506 Ex->getLocStart(),
3507 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003508 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003509 }
3510 }
3511
Ted Kremenek02087932010-07-16 02:11:22 +00003512 return true;
3513}
3514
3515void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003516 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003517 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003518 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003519 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003520 bool inFunctionCall, VariadicCallType CallType,
3521 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003522
Ted Kremenekab278de2010-01-28 23:39:18 +00003523 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003524 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003525 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003526 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003527 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3528 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003529 return;
3530 }
Ted Kremenek02087932010-07-16 02:11:22 +00003531
Ted Kremenekab278de2010-01-28 23:39:18 +00003532 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003533 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003534 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003535 // Account for cases where the string literal is truncated in a declaration.
3536 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3537 assert(T && "String literal not of constant array type!");
3538 size_t TypeSize = T->getSize().getZExtValue();
3539 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003540 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003541
3542 // Emit a warning if the string literal is truncated and does not contain an
3543 // embedded null character.
3544 if (TypeSize <= StrRef.size() &&
3545 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3546 CheckFormatHandler::EmitFormatDiagnostic(
3547 *this, inFunctionCall, Args[format_idx],
3548 PDiag(diag::warn_printf_format_string_not_null_terminated),
3549 FExpr->getLocStart(),
3550 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3551 return;
3552 }
3553
Ted Kremenekab278de2010-01-28 23:39:18 +00003554 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003555 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003556 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003557 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003558 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3559 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003560 return;
3561 }
Ted Kremenek02087932010-07-16 02:11:22 +00003562
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003563 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003564 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003565 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003566 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003567 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003568
Hans Wennborg23926bd2011-12-15 10:25:47 +00003569 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003570 getLangOpts(),
3571 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003572 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003573 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003574 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003575 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003576 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003577
Hans Wennborg23926bd2011-12-15 10:25:47 +00003578 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003579 getLangOpts(),
3580 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003581 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003582 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003583}
3584
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003585//===--- CHECK: Standard memory functions ---------------------------------===//
3586
Nico Weber0e6daef2013-12-26 23:38:39 +00003587/// \brief Takes the expression passed to the size_t parameter of functions
3588/// such as memcmp, strncat, etc and warns if it's a comparison.
3589///
3590/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3591static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3592 IdentifierInfo *FnName,
3593 SourceLocation FnLoc,
3594 SourceLocation RParenLoc) {
3595 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3596 if (!Size)
3597 return false;
3598
3599 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3600 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3601 return false;
3602
3603 Preprocessor &PP = S.getPreprocessor();
3604 SourceRange SizeRange = Size->getSourceRange();
3605 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3606 << SizeRange << FnName;
3607 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3608 << FnName
3609 << FixItHint::CreateInsertion(
3610 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3611 ")")
3612 << FixItHint::CreateRemoval(RParenLoc);
3613 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3614 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3615 << FixItHint::CreateInsertion(
3616 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3617
3618 return true;
3619}
3620
Douglas Gregora74926b2011-05-03 20:05:22 +00003621/// \brief Determine whether the given type is a dynamic class type (e.g.,
3622/// whether it has a vtable).
3623static bool isDynamicClassType(QualType T) {
3624 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3625 if (CXXRecordDecl *Definition = Record->getDefinition())
3626 if (Definition->isDynamicClass())
3627 return true;
3628
3629 return false;
3630}
3631
Chandler Carruth889ed862011-06-21 23:04:20 +00003632/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003633/// otherwise returns NULL.
3634static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003635 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003636 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3637 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3638 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003639
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003640 return 0;
3641}
3642
Chandler Carruth889ed862011-06-21 23:04:20 +00003643/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003644static QualType getSizeOfArgType(const Expr* E) {
3645 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3646 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3647 if (SizeOf->getKind() == clang::UETT_SizeOf)
3648 return SizeOf->getTypeOfArgument();
3649
3650 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00003651}
3652
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003653/// \brief Check for dangerous or invalid arguments to memset().
3654///
Chandler Carruthac687262011-06-03 06:23:57 +00003655/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003656/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3657/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003658///
3659/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003660void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00003661 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003662 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00003663 assert(BId != 0);
3664
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003665 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00003666 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00003667 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00003668 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003669 return;
3670
Anna Zaks22122702012-01-17 00:37:07 +00003671 unsigned LastArg = (BId == Builtin::BImemset ||
3672 BId == Builtin::BIstrndup ? 1 : 2);
3673 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00003674 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003675
Nico Weber0e6daef2013-12-26 23:38:39 +00003676 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
3677 Call->getLocStart(), Call->getRParenLoc()))
3678 return;
3679
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003680 // We have special checking when the length is a sizeof expression.
3681 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3682 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3683 llvm::FoldingSetNodeID SizeOfArgID;
3684
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003685 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3686 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003687 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003688
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003689 QualType DestTy = Dest->getType();
3690 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3691 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00003692
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003693 // Never warn about void type pointers. This can be used to suppress
3694 // false positives.
3695 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003696 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003697
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003698 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3699 // actually comparing the expressions for equality. Because computing the
3700 // expression IDs can be expensive, we only do this if the diagnostic is
3701 // enabled.
3702 if (SizeOfArg &&
3703 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3704 SizeOfArg->getExprLoc())) {
3705 // We only compute IDs for expressions if the warning is enabled, and
3706 // cache the sizeof arg's ID.
3707 if (SizeOfArgID == llvm::FoldingSetNodeID())
3708 SizeOfArg->Profile(SizeOfArgID, Context, true);
3709 llvm::FoldingSetNodeID DestID;
3710 Dest->Profile(DestID, Context, true);
3711 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00003712 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3713 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003714 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00003715 StringRef ReadableName = FnName->getName();
3716
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003717 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00003718 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003719 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00003720 if (!PointeeTy->isIncompleteType() &&
3721 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003722 ActionIdx = 2; // If the pointee's size is sizeof(char),
3723 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00003724
3725 // If the function is defined as a builtin macro, do not show macro
3726 // expansion.
3727 SourceLocation SL = SizeOfArg->getExprLoc();
3728 SourceRange DSR = Dest->getSourceRange();
3729 SourceRange SSR = SizeOfArg->getSourceRange();
3730 SourceManager &SM = PP.getSourceManager();
3731
3732 if (SM.isMacroArgExpansion(SL)) {
3733 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3734 SL = SM.getSpellingLoc(SL);
3735 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3736 SM.getSpellingLoc(DSR.getEnd()));
3737 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3738 SM.getSpellingLoc(SSR.getEnd()));
3739 }
3740
Anna Zaksd08d9152012-05-30 23:14:52 +00003741 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003742 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00003743 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00003744 << PointeeTy
3745 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00003746 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00003747 << SSR);
3748 DiagRuntimeBehavior(SL, SizeOfArg,
3749 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3750 << ActionIdx
3751 << SSR);
3752
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003753 break;
3754 }
3755 }
3756
3757 // Also check for cases where the sizeof argument is the exact same
3758 // type as the memory argument, and where it points to a user-defined
3759 // record type.
3760 if (SizeOfArgTy != QualType()) {
3761 if (PointeeTy->isRecordType() &&
3762 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3763 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3764 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3765 << FnName << SizeOfArgTy << ArgIdx
3766 << PointeeTy << Dest->getSourceRange()
3767 << LenExpr->getSourceRange());
3768 break;
3769 }
Nico Weberc5e73862011-06-14 16:14:58 +00003770 }
3771
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003772 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00003773 if (isDynamicClassType(PointeeTy)) {
3774
3775 unsigned OperationType = 0;
3776 // "overwritten" if we're warning about the destination for any call
3777 // but memcmp; otherwise a verb appropriate to the call.
3778 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3779 if (BId == Builtin::BImemcpy)
3780 OperationType = 1;
3781 else if(BId == Builtin::BImemmove)
3782 OperationType = 2;
3783 else if (BId == Builtin::BImemcmp)
3784 OperationType = 3;
3785 }
3786
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003787 DiagRuntimeBehavior(
3788 Dest->getExprLoc(), Dest,
3789 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00003790 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00003791 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00003792 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003793 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00003794 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3795 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003796 DiagRuntimeBehavior(
3797 Dest->getExprLoc(), Dest,
3798 PDiag(diag::warn_arc_object_memaccess)
3799 << ArgIdx << FnName << PointeeTy
3800 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00003801 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003802 continue;
John McCall31168b02011-06-15 23:02:42 +00003803
3804 DiagRuntimeBehavior(
3805 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00003806 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003807 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3808 break;
3809 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003810 }
3811}
3812
Ted Kremenek6865f772011-08-18 20:55:45 +00003813// A little helper routine: ignore addition and subtraction of integer literals.
3814// This intentionally does not ignore all integer constant expressions because
3815// we don't want to remove sizeof().
3816static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3817 Ex = Ex->IgnoreParenCasts();
3818
3819 for (;;) {
3820 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3821 if (!BO || !BO->isAdditiveOp())
3822 break;
3823
3824 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3825 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3826
3827 if (isa<IntegerLiteral>(RHS))
3828 Ex = LHS;
3829 else if (isa<IntegerLiteral>(LHS))
3830 Ex = RHS;
3831 else
3832 break;
3833 }
3834
3835 return Ex;
3836}
3837
Anna Zaks13b08572012-08-08 21:42:23 +00003838static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3839 ASTContext &Context) {
3840 // Only handle constant-sized or VLAs, but not flexible members.
3841 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3842 // Only issue the FIXIT for arrays of size > 1.
3843 if (CAT->getSize().getSExtValue() <= 1)
3844 return false;
3845 } else if (!Ty->isVariableArrayType()) {
3846 return false;
3847 }
3848 return true;
3849}
3850
Ted Kremenek6865f772011-08-18 20:55:45 +00003851// Warn if the user has made the 'size' argument to strlcpy or strlcat
3852// be the size of the source, instead of the destination.
3853void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3854 IdentifierInfo *FnName) {
3855
3856 // Don't crash if the user has the wrong number of arguments
3857 if (Call->getNumArgs() != 3)
3858 return;
3859
3860 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3861 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3862 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00003863
3864 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
3865 Call->getLocStart(), Call->getRParenLoc()))
3866 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00003867
3868 // Look for 'strlcpy(dst, x, sizeof(x))'
3869 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3870 CompareWithSrc = Ex;
3871 else {
3872 // Look for 'strlcpy(dst, x, strlen(x))'
3873 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00003874 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
3875 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00003876 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3877 }
3878 }
3879
3880 if (!CompareWithSrc)
3881 return;
3882
3883 // Determine if the argument to sizeof/strlen is equal to the source
3884 // argument. In principle there's all kinds of things you could do
3885 // here, for instance creating an == expression and evaluating it with
3886 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3887 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3888 if (!SrcArgDRE)
3889 return;
3890
3891 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3892 if (!CompareWithSrcDRE ||
3893 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3894 return;
3895
3896 const Expr *OriginalSizeArg = Call->getArg(2);
3897 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3898 << OriginalSizeArg->getSourceRange() << FnName;
3899
3900 // Output a FIXIT hint if the destination is an array (rather than a
3901 // pointer to an array). This could be enhanced to handle some
3902 // pointers if we know the actual size, like if DstArg is 'array+2'
3903 // we could say 'sizeof(array)-2'.
3904 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00003905 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00003906 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003907
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003908 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003909 llvm::raw_svector_ostream OS(sizeString);
3910 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00003911 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00003912 OS << ")";
3913
3914 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3915 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3916 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00003917}
3918
Anna Zaks314cd092012-02-01 19:08:57 +00003919/// Check if two expressions refer to the same declaration.
3920static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3921 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3922 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3923 return D1->getDecl() == D2->getDecl();
3924 return false;
3925}
3926
3927static const Expr *getStrlenExprArg(const Expr *E) {
3928 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3929 const FunctionDecl *FD = CE->getDirectCallee();
3930 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3931 return 0;
3932 return CE->getArg(0)->IgnoreParenCasts();
3933 }
3934 return 0;
3935}
3936
3937// Warn on anti-patterns as the 'size' argument to strncat.
3938// The correct size argument should look like following:
3939// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3940void Sema::CheckStrncatArguments(const CallExpr *CE,
3941 IdentifierInfo *FnName) {
3942 // Don't crash if the user has the wrong number of arguments.
3943 if (CE->getNumArgs() < 3)
3944 return;
3945 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3946 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3947 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3948
Nico Weber0e6daef2013-12-26 23:38:39 +00003949 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
3950 CE->getRParenLoc()))
3951 return;
3952
Anna Zaks314cd092012-02-01 19:08:57 +00003953 // Identify common expressions, which are wrongly used as the size argument
3954 // to strncat and may lead to buffer overflows.
3955 unsigned PatternType = 0;
3956 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3957 // - sizeof(dst)
3958 if (referToTheSameDecl(SizeOfArg, DstArg))
3959 PatternType = 1;
3960 // - sizeof(src)
3961 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3962 PatternType = 2;
3963 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3964 if (BE->getOpcode() == BO_Sub) {
3965 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3966 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3967 // - sizeof(dst) - strlen(dst)
3968 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3969 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3970 PatternType = 1;
3971 // - sizeof(src) - (anything)
3972 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3973 PatternType = 2;
3974 }
3975 }
3976
3977 if (PatternType == 0)
3978 return;
3979
Anna Zaks5069aa32012-02-03 01:27:37 +00003980 // Generate the diagnostic.
3981 SourceLocation SL = LenArg->getLocStart();
3982 SourceRange SR = LenArg->getSourceRange();
3983 SourceManager &SM = PP.getSourceManager();
3984
3985 // If the function is defined as a builtin macro, do not show macro expansion.
3986 if (SM.isMacroArgExpansion(SL)) {
3987 SL = SM.getSpellingLoc(SL);
3988 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3989 SM.getSpellingLoc(SR.getEnd()));
3990 }
3991
Anna Zaks13b08572012-08-08 21:42:23 +00003992 // Check if the destination is an array (rather than a pointer to an array).
3993 QualType DstTy = DstArg->getType();
3994 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3995 Context);
3996 if (!isKnownSizeArray) {
3997 if (PatternType == 1)
3998 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3999 else
4000 Diag(SL, diag::warn_strncat_src_size) << SR;
4001 return;
4002 }
4003
Anna Zaks314cd092012-02-01 19:08:57 +00004004 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004005 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004006 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004007 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004008
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004009 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004010 llvm::raw_svector_ostream OS(sizeString);
4011 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004012 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004013 OS << ") - ";
4014 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00004015 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004016 OS << ") - 1";
4017
Anna Zaks5069aa32012-02-03 01:27:37 +00004018 Diag(SL, diag::note_strncat_wrong_size)
4019 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004020}
4021
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004022//===--- CHECK: Return Address of Stack Variable --------------------------===//
4023
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004024static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4025 Decl *ParentDecl);
4026static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4027 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004028
4029/// CheckReturnStackAddr - Check if a return statement returns the address
4030/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004031static void
4032CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4033 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004034
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004035 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004036 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004037
4038 // Perform checking for returned stack addresses, local blocks,
4039 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004040 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004041 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004042 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004043 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004044 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004045 }
4046
4047 if (stackE == 0)
4048 return; // Nothing suspicious was found.
4049
4050 SourceLocation diagLoc;
4051 SourceRange diagRange;
4052 if (refVars.empty()) {
4053 diagLoc = stackE->getLocStart();
4054 diagRange = stackE->getSourceRange();
4055 } else {
4056 // We followed through a reference variable. 'stackE' contains the
4057 // problematic expression but we will warn at the return statement pointing
4058 // at the reference variable. We will later display the "trail" of
4059 // reference variables using notes.
4060 diagLoc = refVars[0]->getLocStart();
4061 diagRange = refVars[0]->getSourceRange();
4062 }
4063
4064 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004065 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004066 : diag::warn_ret_stack_addr)
4067 << DR->getDecl()->getDeclName() << diagRange;
4068 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004069 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004070 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004071 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004072 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004073 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4074 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004075 << diagRange;
4076 }
4077
4078 // Display the "trail" of reference variables that we followed until we
4079 // found the problematic expression using notes.
4080 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4081 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4082 // If this var binds to another reference var, show the range of the next
4083 // var, otherwise the var binds to the problematic expression, in which case
4084 // show the range of the expression.
4085 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4086 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004087 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4088 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004089 }
4090}
4091
4092/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4093/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004094/// to a location on the stack, a local block, an address of a label, or a
4095/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004096/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004097/// encounter a subexpression that (1) clearly does not lead to one of the
4098/// above problematic expressions (2) is something we cannot determine leads to
4099/// a problematic expression based on such local checking.
4100///
4101/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4102/// the expression that they point to. Such variables are added to the
4103/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004104///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004105/// EvalAddr processes expressions that are pointers that are used as
4106/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004107/// At the base case of the recursion is a check for the above problematic
4108/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004109///
4110/// This implementation handles:
4111///
4112/// * pointer-to-pointer casts
4113/// * implicit conversions from array references to pointers
4114/// * taking the address of fields
4115/// * arbitrary interplay between "&" and "*" operators
4116/// * pointer arithmetic from an address of a stack variable
4117/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004118static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4119 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004120 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004121 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004122
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004123 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004124 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004125 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004126 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004127 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004128
Peter Collingbourne91147592011-04-15 00:35:48 +00004129 E = E->IgnoreParens();
4130
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004131 // Our "symbolic interpreter" is just a dispatch off the currently
4132 // viewed AST node. We then recursively traverse the AST by calling
4133 // EvalAddr and EvalVal appropriately.
4134 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004135 case Stmt::DeclRefExprClass: {
4136 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4137
Richard Smith40f08eb2014-01-30 22:05:38 +00004138 // If we leave the immediate function, the lifetime isn't about to end.
4139 if (DR->refersToEnclosingLocal())
4140 return 0;
4141
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004142 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4143 // If this is a reference variable, follow through to the expression that
4144 // it points to.
4145 if (V->hasLocalStorage() &&
4146 V->getType()->isReferenceType() && V->hasInit()) {
4147 // Add the reference variable to the "trail".
4148 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004149 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004150 }
4151
4152 return NULL;
4153 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004154
Chris Lattner934edb22007-12-28 05:31:15 +00004155 case Stmt::UnaryOperatorClass: {
4156 // The only unary operator that make sense to handle here
4157 // is AddrOf. All others don't make sense as pointers.
4158 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004159
John McCalle3027922010-08-25 11:45:40 +00004160 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004161 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004162 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004163 return NULL;
4164 }
Mike Stump11289f42009-09-09 15:08:12 +00004165
Chris Lattner934edb22007-12-28 05:31:15 +00004166 case Stmt::BinaryOperatorClass: {
4167 // Handle pointer arithmetic. All other binary operators are not valid
4168 // in this context.
4169 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004170 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004171
John McCalle3027922010-08-25 11:45:40 +00004172 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004173 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004174
Chris Lattner934edb22007-12-28 05:31:15 +00004175 Expr *Base = B->getLHS();
4176
4177 // Determine which argument is the real pointer base. It could be
4178 // the RHS argument instead of the LHS.
4179 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004180
Chris Lattner934edb22007-12-28 05:31:15 +00004181 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004182 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004183 }
Steve Naroff2752a172008-09-10 19:17:48 +00004184
Chris Lattner934edb22007-12-28 05:31:15 +00004185 // For conditional operators we need to see if either the LHS or RHS are
4186 // valid DeclRefExpr*s. If one of them is valid, we return it.
4187 case Stmt::ConditionalOperatorClass: {
4188 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004189
Chris Lattner934edb22007-12-28 05:31:15 +00004190 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004191 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4192 if (Expr *LHSExpr = C->getLHS()) {
4193 // In C++, we can have a throw-expression, which has 'void' type.
4194 if (!LHSExpr->getType()->isVoidType())
4195 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004196 return LHS;
4197 }
Chris Lattner934edb22007-12-28 05:31:15 +00004198
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004199 // In C++, we can have a throw-expression, which has 'void' type.
4200 if (C->getRHS()->getType()->isVoidType())
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004201 return 0;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004202
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004203 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004204 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004205
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004206 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004207 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004208 return E; // local block.
4209 return NULL;
4210
4211 case Stmt::AddrLabelExprClass:
4212 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004213
John McCall28fc7092011-11-10 05:35:25 +00004214 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004215 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4216 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004217
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004218 // For casts, we need to handle conversions from arrays to
4219 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004220 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004221 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004222 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004223 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004224 case Stmt::CXXStaticCastExprClass:
4225 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004226 case Stmt::CXXConstCastExprClass:
4227 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004228 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4229 switch (cast<CastExpr>(E)->getCastKind()) {
4230 case CK_BitCast:
4231 case CK_LValueToRValue:
4232 case CK_NoOp:
4233 case CK_BaseToDerived:
4234 case CK_DerivedToBase:
4235 case CK_UncheckedDerivedToBase:
4236 case CK_Dynamic:
4237 case CK_CPointerToObjCPointerCast:
4238 case CK_BlockPointerToObjCPointerCast:
4239 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004240 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004241
4242 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004243 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004244
4245 default:
4246 return 0;
4247 }
Chris Lattner934edb22007-12-28 05:31:15 +00004248 }
Mike Stump11289f42009-09-09 15:08:12 +00004249
Douglas Gregorfe314812011-06-21 17:03:29 +00004250 case Stmt::MaterializeTemporaryExprClass:
4251 if (Expr *Result = EvalAddr(
4252 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004253 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004254 return Result;
4255
4256 return E;
4257
Chris Lattner934edb22007-12-28 05:31:15 +00004258 // Everything else: we simply don't reason about them.
4259 default:
4260 return NULL;
4261 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004262}
Mike Stump11289f42009-09-09 15:08:12 +00004263
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004264
4265/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4266/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004267static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4268 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004269do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004270 // We should only be called for evaluating non-pointer expressions, or
4271 // expressions with a pointer type that are not used as references but instead
4272 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004273
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004274 // Our "symbolic interpreter" is just a dispatch off the currently
4275 // viewed AST node. We then recursively traverse the AST by calling
4276 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004277
4278 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004279 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004280 case Stmt::ImplicitCastExprClass: {
4281 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004282 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004283 E = IE->getSubExpr();
4284 continue;
4285 }
4286 return NULL;
4287 }
4288
John McCall28fc7092011-11-10 05:35:25 +00004289 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004290 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004291
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004292 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004293 // When we hit a DeclRefExpr we are looking at code that refers to a
4294 // variable's name. If it's not a reference variable we check if it has
4295 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004296 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004297
Richard Smith40f08eb2014-01-30 22:05:38 +00004298 // If we leave the immediate function, the lifetime isn't about to end.
4299 if (DR->refersToEnclosingLocal())
4300 return 0;
4301
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004302 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4303 // Check if it refers to itself, e.g. "int& i = i;".
4304 if (V == ParentDecl)
4305 return DR;
4306
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004307 if (V->hasLocalStorage()) {
4308 if (!V->getType()->isReferenceType())
4309 return DR;
4310
4311 // Reference variable, follow through to the expression that
4312 // it points to.
4313 if (V->hasInit()) {
4314 // Add the reference variable to the "trail".
4315 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004316 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004317 }
4318 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004319 }
Mike Stump11289f42009-09-09 15:08:12 +00004320
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004321 return NULL;
4322 }
Mike Stump11289f42009-09-09 15:08:12 +00004323
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004324 case Stmt::UnaryOperatorClass: {
4325 // The only unary operator that make sense to handle here
4326 // is Deref. All others don't resolve to a "name." This includes
4327 // handling all sorts of rvalues passed to a unary operator.
4328 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004329
John McCalle3027922010-08-25 11:45:40 +00004330 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004331 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004332
4333 return NULL;
4334 }
Mike Stump11289f42009-09-09 15:08:12 +00004335
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004336 case Stmt::ArraySubscriptExprClass: {
4337 // Array subscripts are potential references to data on the stack. We
4338 // retrieve the DeclRefExpr* for the array variable if it indeed
4339 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004340 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004341 }
Mike Stump11289f42009-09-09 15:08:12 +00004342
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004343 case Stmt::ConditionalOperatorClass: {
4344 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004345 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004346 ConditionalOperator *C = cast<ConditionalOperator>(E);
4347
Anders Carlsson801c5c72007-11-30 19:04:31 +00004348 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004349 if (Expr *LHSExpr = C->getLHS()) {
4350 // In C++, we can have a throw-expression, which has 'void' type.
4351 if (!LHSExpr->getType()->isVoidType())
4352 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4353 return LHS;
4354 }
4355
4356 // In C++, we can have a throw-expression, which has 'void' type.
4357 if (C->getRHS()->getType()->isVoidType())
4358 return 0;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004359
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004360 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004361 }
Mike Stump11289f42009-09-09 15:08:12 +00004362
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004363 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004364 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004365 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004366
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004367 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004368 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004369 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004370
4371 // Check whether the member type is itself a reference, in which case
4372 // we're not going to refer to the member, but to what the member refers to.
4373 if (M->getMemberDecl()->getType()->isReferenceType())
4374 return NULL;
4375
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004376 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004377 }
Mike Stump11289f42009-09-09 15:08:12 +00004378
Douglas Gregorfe314812011-06-21 17:03:29 +00004379 case Stmt::MaterializeTemporaryExprClass:
4380 if (Expr *Result = EvalVal(
4381 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004382 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004383 return Result;
4384
4385 return E;
4386
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004387 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004388 // Check that we don't return or take the address of a reference to a
4389 // temporary. This is only useful in C++.
4390 if (!E->isTypeDependent() && E->isRValue())
4391 return E;
4392
4393 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004394 return NULL;
4395 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004396} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004397}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004398
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004399void
4400Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4401 SourceLocation ReturnLoc,
4402 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004403 const AttrVec *Attrs,
4404 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004405 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4406
4407 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004408 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4409 CheckNonNullExpr(*this, RetValExp))
4410 Diag(ReturnLoc, diag::warn_null_ret)
4411 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004412
4413 // C++11 [basic.stc.dynamic.allocation]p4:
4414 // If an allocation function declared with a non-throwing
4415 // exception-specification fails to allocate storage, it shall return
4416 // a null pointer. Any other allocation function that fails to allocate
4417 // storage shall indicate failure only by throwing an exception [...]
4418 if (FD) {
4419 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4420 if (Op == OO_New || Op == OO_Array_New) {
4421 const FunctionProtoType *Proto
4422 = FD->getType()->castAs<FunctionProtoType>();
4423 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4424 CheckNonNullExpr(*this, RetValExp))
4425 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4426 << FD << getLangOpts().CPlusPlus11;
4427 }
4428 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004429}
4430
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004431//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4432
4433/// Check for comparisons of floating point operands using != and ==.
4434/// Issue a warning if these are no self-comparisons, as they are not likely
4435/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004436void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004437 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4438 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004439
4440 // Special case: check for x == x (which is OK).
4441 // Do not emit warnings for such cases.
4442 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4443 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4444 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004445 return;
Mike Stump11289f42009-09-09 15:08:12 +00004446
4447
Ted Kremenekeda40e22007-11-29 00:59:04 +00004448 // Special case: check for comparisons against literals that can be exactly
4449 // represented by APFloat. In such cases, do not emit a warning. This
4450 // is a heuristic: often comparison against such literals are used to
4451 // detect if a value in a variable has not changed. This clearly can
4452 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004453 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4454 if (FLL->isExact())
4455 return;
4456 } else
4457 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4458 if (FLR->isExact())
4459 return;
Mike Stump11289f42009-09-09 15:08:12 +00004460
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004461 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004462 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004463 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004464 return;
Mike Stump11289f42009-09-09 15:08:12 +00004465
David Blaikie1f4ff152012-07-16 20:47:22 +00004466 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004467 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004468 return;
Mike Stump11289f42009-09-09 15:08:12 +00004469
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004470 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004471 Diag(Loc, diag::warn_floatingpoint_eq)
4472 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004473}
John McCallca01b222010-01-04 23:21:16 +00004474
John McCall70aa5392010-01-06 05:24:50 +00004475//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4476//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004477
John McCall70aa5392010-01-06 05:24:50 +00004478namespace {
John McCallca01b222010-01-04 23:21:16 +00004479
John McCall70aa5392010-01-06 05:24:50 +00004480/// Structure recording the 'active' range of an integer-valued
4481/// expression.
4482struct IntRange {
4483 /// The number of bits active in the int.
4484 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004485
John McCall70aa5392010-01-06 05:24:50 +00004486 /// True if the int is known not to have negative values.
4487 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004488
John McCall70aa5392010-01-06 05:24:50 +00004489 IntRange(unsigned Width, bool NonNegative)
4490 : Width(Width), NonNegative(NonNegative)
4491 {}
John McCallca01b222010-01-04 23:21:16 +00004492
John McCall817d4af2010-11-10 23:38:19 +00004493 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004494 static IntRange forBoolType() {
4495 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004496 }
4497
John McCall817d4af2010-11-10 23:38:19 +00004498 /// Returns the range of an opaque value of the given integral type.
4499 static IntRange forValueOfType(ASTContext &C, QualType T) {
4500 return forValueOfCanonicalType(C,
4501 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004502 }
4503
John McCall817d4af2010-11-10 23:38:19 +00004504 /// Returns the range of an opaque value of a canonical integral type.
4505 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004506 assert(T->isCanonicalUnqualified());
4507
4508 if (const VectorType *VT = dyn_cast<VectorType>(T))
4509 T = VT->getElementType().getTypePtr();
4510 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4511 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004512
David Majnemer6a426652013-06-07 22:07:20 +00004513 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004514 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004515 EnumDecl *Enum = ET->getDecl();
4516 if (!Enum->isCompleteDefinition())
4517 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004518
David Majnemer6a426652013-06-07 22:07:20 +00004519 unsigned NumPositive = Enum->getNumPositiveBits();
4520 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004521
David Majnemer6a426652013-06-07 22:07:20 +00004522 if (NumNegative == 0)
4523 return IntRange(NumPositive, true/*NonNegative*/);
4524 else
4525 return IntRange(std::max(NumPositive + 1, NumNegative),
4526 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004527 }
John McCall70aa5392010-01-06 05:24:50 +00004528
4529 const BuiltinType *BT = cast<BuiltinType>(T);
4530 assert(BT->isInteger());
4531
4532 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4533 }
4534
John McCall817d4af2010-11-10 23:38:19 +00004535 /// Returns the "target" range of a canonical integral type, i.e.
4536 /// the range of values expressible in the type.
4537 ///
4538 /// This matches forValueOfCanonicalType except that enums have the
4539 /// full range of their type, not the range of their enumerators.
4540 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4541 assert(T->isCanonicalUnqualified());
4542
4543 if (const VectorType *VT = dyn_cast<VectorType>(T))
4544 T = VT->getElementType().getTypePtr();
4545 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4546 T = CT->getElementType().getTypePtr();
4547 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004548 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004549
4550 const BuiltinType *BT = cast<BuiltinType>(T);
4551 assert(BT->isInteger());
4552
4553 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4554 }
4555
4556 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004557 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004558 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004559 L.NonNegative && R.NonNegative);
4560 }
4561
John McCall817d4af2010-11-10 23:38:19 +00004562 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004563 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004564 return IntRange(std::min(L.Width, R.Width),
4565 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004566 }
4567};
4568
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004569static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4570 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004571 if (value.isSigned() && value.isNegative())
4572 return IntRange(value.getMinSignedBits(), false);
4573
4574 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004575 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004576
4577 // isNonNegative() just checks the sign bit without considering
4578 // signedness.
4579 return IntRange(value.getActiveBits(), true);
4580}
4581
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004582static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4583 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004584 if (result.isInt())
4585 return GetValueRange(C, result.getInt(), MaxWidth);
4586
4587 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004588 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4589 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4590 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4591 R = IntRange::join(R, El);
4592 }
John McCall70aa5392010-01-06 05:24:50 +00004593 return R;
4594 }
4595
4596 if (result.isComplexInt()) {
4597 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4598 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4599 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004600 }
4601
4602 // This can happen with lossless casts to intptr_t of "based" lvalues.
4603 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004604 // FIXME: The only reason we need to pass the type in here is to get
4605 // the sign right on this one case. It would be nice if APValue
4606 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004607 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004608 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004609}
John McCall70aa5392010-01-06 05:24:50 +00004610
Eli Friedmane6d33952013-07-08 20:20:06 +00004611static QualType GetExprType(Expr *E) {
4612 QualType Ty = E->getType();
4613 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4614 Ty = AtomicRHS->getValueType();
4615 return Ty;
4616}
4617
John McCall70aa5392010-01-06 05:24:50 +00004618/// Pseudo-evaluate the given integer expression, estimating the
4619/// range of values it might take.
4620///
4621/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004622static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004623 E = E->IgnoreParens();
4624
4625 // Try a full evaluation first.
4626 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004627 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004628 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004629
4630 // I think we only want to look through implicit casts here; if the
4631 // user has an explicit widening cast, we should treat the value as
4632 // being of the new, wider type.
4633 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004634 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004635 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4636
Eli Friedmane6d33952013-07-08 20:20:06 +00004637 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00004638
John McCalle3027922010-08-25 11:45:40 +00004639 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00004640
John McCall70aa5392010-01-06 05:24:50 +00004641 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00004642 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00004643 return OutputTypeRange;
4644
4645 IntRange SubRange
4646 = GetExprRange(C, CE->getSubExpr(),
4647 std::min(MaxWidth, OutputTypeRange.Width));
4648
4649 // Bail out if the subexpr's range is as wide as the cast type.
4650 if (SubRange.Width >= OutputTypeRange.Width)
4651 return OutputTypeRange;
4652
4653 // Otherwise, we take the smaller width, and we're non-negative if
4654 // either the output type or the subexpr is.
4655 return IntRange(SubRange.Width,
4656 SubRange.NonNegative || OutputTypeRange.NonNegative);
4657 }
4658
4659 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4660 // If we can fold the condition, just take that operand.
4661 bool CondResult;
4662 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4663 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4664 : CO->getFalseExpr(),
4665 MaxWidth);
4666
4667 // Otherwise, conservatively merge.
4668 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4669 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4670 return IntRange::join(L, R);
4671 }
4672
4673 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4674 switch (BO->getOpcode()) {
4675
4676 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00004677 case BO_LAnd:
4678 case BO_LOr:
4679 case BO_LT:
4680 case BO_GT:
4681 case BO_LE:
4682 case BO_GE:
4683 case BO_EQ:
4684 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00004685 return IntRange::forBoolType();
4686
John McCallc3688382011-07-13 06:35:24 +00004687 // The type of the assignments is the type of the LHS, so the RHS
4688 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00004689 case BO_MulAssign:
4690 case BO_DivAssign:
4691 case BO_RemAssign:
4692 case BO_AddAssign:
4693 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00004694 case BO_XorAssign:
4695 case BO_OrAssign:
4696 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00004697 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00004698
John McCallc3688382011-07-13 06:35:24 +00004699 // Simple assignments just pass through the RHS, which will have
4700 // been coerced to the LHS type.
4701 case BO_Assign:
4702 // TODO: bitfields?
4703 return GetExprRange(C, BO->getRHS(), MaxWidth);
4704
John McCall70aa5392010-01-06 05:24:50 +00004705 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004706 case BO_PtrMemD:
4707 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00004708 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004709
John McCall2ce81ad2010-01-06 22:07:33 +00004710 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00004711 case BO_And:
4712 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00004713 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4714 GetExprRange(C, BO->getRHS(), MaxWidth));
4715
John McCall70aa5392010-01-06 05:24:50 +00004716 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00004717 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00004718 // ...except that we want to treat '1 << (blah)' as logically
4719 // positive. It's an important idiom.
4720 if (IntegerLiteral *I
4721 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4722 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004723 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00004724 return IntRange(R.Width, /*NonNegative*/ true);
4725 }
4726 }
4727 // fallthrough
4728
John McCalle3027922010-08-25 11:45:40 +00004729 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00004730 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004731
John McCall2ce81ad2010-01-06 22:07:33 +00004732 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00004733 case BO_Shr:
4734 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00004735 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4736
4737 // If the shift amount is a positive constant, drop the width by
4738 // that much.
4739 llvm::APSInt shift;
4740 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4741 shift.isNonNegative()) {
4742 unsigned zext = shift.getZExtValue();
4743 if (zext >= L.Width)
4744 L.Width = (L.NonNegative ? 0 : 1);
4745 else
4746 L.Width -= zext;
4747 }
4748
4749 return L;
4750 }
4751
4752 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00004753 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00004754 return GetExprRange(C, BO->getRHS(), MaxWidth);
4755
John McCall2ce81ad2010-01-06 22:07:33 +00004756 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00004757 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00004758 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00004759 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004760 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004761
John McCall51431812011-07-14 22:39:48 +00004762 // The width of a division result is mostly determined by the size
4763 // of the LHS.
4764 case BO_Div: {
4765 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004766 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004767 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4768
4769 // If the divisor is constant, use that.
4770 llvm::APSInt divisor;
4771 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4772 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4773 if (log2 >= L.Width)
4774 L.Width = (L.NonNegative ? 0 : 1);
4775 else
4776 L.Width = std::min(L.Width - log2, MaxWidth);
4777 return L;
4778 }
4779
4780 // Otherwise, just use the LHS's width.
4781 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4782 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4783 }
4784
4785 // The result of a remainder can't be larger than the result of
4786 // either side.
4787 case BO_Rem: {
4788 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004789 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004790 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4791 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4792
4793 IntRange meet = IntRange::meet(L, R);
4794 meet.Width = std::min(meet.Width, MaxWidth);
4795 return meet;
4796 }
4797
4798 // The default behavior is okay for these.
4799 case BO_Mul:
4800 case BO_Add:
4801 case BO_Xor:
4802 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00004803 break;
4804 }
4805
John McCall51431812011-07-14 22:39:48 +00004806 // The default case is to treat the operation as if it were closed
4807 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00004808 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4809 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4810 return IntRange::join(L, R);
4811 }
4812
4813 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4814 switch (UO->getOpcode()) {
4815 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00004816 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00004817 return IntRange::forBoolType();
4818
4819 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004820 case UO_Deref:
4821 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00004822 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004823
4824 default:
4825 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4826 }
4827 }
4828
Ted Kremeneka553fbf2013-10-14 18:55:27 +00004829 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4830 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4831
John McCalld25db7e2013-05-06 21:39:12 +00004832 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00004833 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00004834 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00004835
Eli Friedmane6d33952013-07-08 20:20:06 +00004836 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004837}
John McCall263a48b2010-01-04 23:31:57 +00004838
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004839static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004840 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00004841}
4842
John McCall263a48b2010-01-04 23:31:57 +00004843/// Checks whether the given value, which currently has the given
4844/// source semantics, has the same value when coerced through the
4845/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004846static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4847 const llvm::fltSemantics &Src,
4848 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004849 llvm::APFloat truncated = value;
4850
4851 bool ignored;
4852 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4853 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4854
4855 return truncated.bitwiseIsEqual(value);
4856}
4857
4858/// Checks whether the given value, which currently has the given
4859/// source semantics, has the same value when coerced through the
4860/// target semantics.
4861///
4862/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004863static bool IsSameFloatAfterCast(const APValue &value,
4864 const llvm::fltSemantics &Src,
4865 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004866 if (value.isFloat())
4867 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4868
4869 if (value.isVector()) {
4870 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4871 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4872 return false;
4873 return true;
4874 }
4875
4876 assert(value.isComplexFloat());
4877 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4878 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4879}
4880
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004881static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004882
Ted Kremenek6274be42010-09-23 21:43:44 +00004883static bool IsZero(Sema &S, Expr *E) {
4884 // Suppress cases where we are comparing against an enum constant.
4885 if (const DeclRefExpr *DR =
4886 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4887 if (isa<EnumConstantDecl>(DR->getDecl()))
4888 return false;
4889
4890 // Suppress cases where the '0' value is expanded from a macro.
4891 if (E->getLocStart().isMacroID())
4892 return false;
4893
John McCallcc7e5bf2010-05-06 08:58:33 +00004894 llvm::APSInt Value;
4895 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4896}
4897
John McCall2551c1b2010-10-06 00:25:24 +00004898static bool HasEnumType(Expr *E) {
4899 // Strip off implicit integral promotions.
4900 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004901 if (ICE->getCastKind() != CK_IntegralCast &&
4902 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00004903 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004904 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00004905 }
4906
4907 return E->getType()->isEnumeralType();
4908}
4909
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004910static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00004911 // Disable warning in template instantiations.
4912 if (!S.ActiveTemplateInstantiations.empty())
4913 return;
4914
John McCalle3027922010-08-25 11:45:40 +00004915 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00004916 if (E->isValueDependent())
4917 return;
4918
John McCalle3027922010-08-25 11:45:40 +00004919 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004920 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004921 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004922 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004923 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004924 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004925 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004926 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004927 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004928 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004929 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004930 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004931 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004932 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004933 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004934 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4935 }
4936}
4937
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004938static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004939 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004940 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004941 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00004942 // Disable warning in template instantiations.
4943 if (!S.ActiveTemplateInstantiations.empty())
4944 return;
4945
Richard Trieu560910c2012-11-14 22:50:24 +00004946 // 0 values are handled later by CheckTrivialUnsignedComparison().
4947 if (Value == 0)
4948 return;
4949
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004950 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004951 QualType OtherT = Other->getType();
4952 QualType ConstantT = Constant->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00004953 QualType CommonT = E->getLHS()->getType();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004954 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004955 return;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004956 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004957 && "comparison with non-integer type");
Richard Trieu560910c2012-11-14 22:50:24 +00004958
4959 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu560910c2012-11-14 22:50:24 +00004960 bool CommonSigned = CommonT->isSignedIntegerType();
4961
4962 bool EqualityOnly = false;
4963
4964 // TODO: Investigate using GetExprRange() to get tighter bounds on
4965 // on the bit ranges.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004966 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu560910c2012-11-14 22:50:24 +00004967 unsigned OtherWidth = OtherRange.Width;
4968
4969 if (CommonSigned) {
4970 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedman5ac98752012-11-30 23:09:29 +00004971 if (!OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004972 // Check that the constant is representable in type OtherT.
4973 if (ConstantSigned) {
4974 if (OtherWidth >= Value.getMinSignedBits())
4975 return;
4976 } else { // !ConstantSigned
4977 if (OtherWidth >= Value.getActiveBits() + 1)
4978 return;
4979 }
4980 } else { // !OtherSigned
4981 // Check that the constant is representable in type OtherT.
4982 // Negative values are out of range.
4983 if (ConstantSigned) {
4984 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4985 return;
4986 } else { // !ConstantSigned
4987 if (OtherWidth >= Value.getActiveBits())
4988 return;
4989 }
4990 }
4991 } else { // !CommonSigned
Eli Friedman5ac98752012-11-30 23:09:29 +00004992 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004993 if (OtherWidth >= Value.getActiveBits())
4994 return;
Eli Friedman5ac98752012-11-30 23:09:29 +00004995 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu560910c2012-11-14 22:50:24 +00004996 // Check to see if the constant is representable in OtherT.
4997 if (OtherWidth > Value.getActiveBits())
4998 return;
4999 // Check to see if the constant is equivalent to a negative value
5000 // cast to CommonT.
5001 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu03c3a2f2012-11-15 03:43:50 +00005002 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu560910c2012-11-14 22:50:24 +00005003 return;
5004 // The constant value rests between values that OtherT can represent after
5005 // conversion. Relational comparison still works, but equality
5006 // comparisons will be tautological.
5007 EqualityOnly = true;
5008 } else { // OtherSigned && ConstantSigned
5009 assert(0 && "Two signed types converted to unsigned types.");
5010 }
5011 }
5012
5013 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5014
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005015 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005016 if (op == BO_EQ || op == BO_NE) {
5017 IsTrue = op == BO_NE;
5018 } else if (EqualityOnly) {
5019 return;
5020 } else if (RhsConstant) {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005021 if (op == BO_GT || op == BO_GE)
Richard Trieu560910c2012-11-14 22:50:24 +00005022 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005023 else // op == BO_LT || op == BO_LE
Richard Trieu560910c2012-11-14 22:50:24 +00005024 IsTrue = PositiveConstant;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005025 } else {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005026 if (op == BO_LT || op == BO_LE)
Richard Trieu560910c2012-11-14 22:50:24 +00005027 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005028 else // op == BO_GT || op == BO_GE
Richard Trieu560910c2012-11-14 22:50:24 +00005029 IsTrue = PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005030 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005031
5032 // If this is a comparison to an enum constant, include that
5033 // constant in the diagnostic.
5034 const EnumConstantDecl *ED = 0;
5035 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5036 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5037
5038 SmallString<64> PrettySourceValue;
5039 llvm::raw_svector_ostream OS(PrettySourceValue);
5040 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005041 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005042 else
5043 OS << Value;
5044
Richard Trieuc38786b2014-01-10 04:38:09 +00005045 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5046 S.PDiag(diag::warn_out_of_range_compare)
5047 << OS.str() << OtherT << IsTrue
5048 << E->getLHS()->getSourceRange()
5049 << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005050}
5051
John McCallcc7e5bf2010-05-06 08:58:33 +00005052/// Analyze the operands of the given comparison. Implements the
5053/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005054static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005055 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5056 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005057}
John McCall263a48b2010-01-04 23:31:57 +00005058
John McCallca01b222010-01-04 23:21:16 +00005059/// \brief Implements -Wsign-compare.
5060///
Richard Trieu82402a02011-09-15 21:56:47 +00005061/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005062static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005063 // The type the comparison is being performed in.
5064 QualType T = E->getLHS()->getType();
5065 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5066 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005067 if (E->isValueDependent())
5068 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005069
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005070 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5071 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005072
5073 bool IsComparisonConstant = false;
5074
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005075 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005076 // of 'true' or 'false'.
5077 if (T->isIntegralType(S.Context)) {
5078 llvm::APSInt RHSValue;
5079 bool IsRHSIntegralLiteral =
5080 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5081 llvm::APSInt LHSValue;
5082 bool IsLHSIntegralLiteral =
5083 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5084 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5085 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5086 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5087 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5088 else
5089 IsComparisonConstant =
5090 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005091 } else if (!T->hasUnsignedIntegerRepresentation())
5092 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005093
John McCallcc7e5bf2010-05-06 08:58:33 +00005094 // We don't do anything special if this isn't an unsigned integral
5095 // comparison: we're only interested in integral comparisons, and
5096 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005097 //
5098 // We also don't care about value-dependent expressions or expressions
5099 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005100 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005101 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005102
John McCallcc7e5bf2010-05-06 08:58:33 +00005103 // Check to see if one of the (unmodified) operands is of different
5104 // signedness.
5105 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005106 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5107 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005108 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005109 signedOperand = LHS;
5110 unsignedOperand = RHS;
5111 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5112 signedOperand = RHS;
5113 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005114 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005115 CheckTrivialUnsignedComparison(S, E);
5116 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005117 }
5118
John McCallcc7e5bf2010-05-06 08:58:33 +00005119 // Otherwise, calculate the effective range of the signed operand.
5120 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005121
John McCallcc7e5bf2010-05-06 08:58:33 +00005122 // Go ahead and analyze implicit conversions in the operands. Note
5123 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005124 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5125 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005126
John McCallcc7e5bf2010-05-06 08:58:33 +00005127 // If the signed range is non-negative, -Wsign-compare won't fire,
5128 // but we should still check for comparisons which are always true
5129 // or false.
5130 if (signedRange.NonNegative)
5131 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005132
5133 // For (in)equality comparisons, if the unsigned operand is a
5134 // constant which cannot collide with a overflowed signed operand,
5135 // then reinterpreting the signed operand as unsigned will not
5136 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005137 if (E->isEqualityOp()) {
5138 unsigned comparisonWidth = S.Context.getIntWidth(T);
5139 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005140
John McCallcc7e5bf2010-05-06 08:58:33 +00005141 // We should never be unable to prove that the unsigned operand is
5142 // non-negative.
5143 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5144
5145 if (unsignedRange.Width < comparisonWidth)
5146 return;
5147 }
5148
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005149 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5150 S.PDiag(diag::warn_mixed_sign_comparison)
5151 << LHS->getType() << RHS->getType()
5152 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005153}
5154
John McCall1f425642010-11-11 03:21:53 +00005155/// Analyzes an attempt to assign the given value to a bitfield.
5156///
5157/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005158static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5159 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005160 assert(Bitfield->isBitField());
5161 if (Bitfield->isInvalidDecl())
5162 return false;
5163
John McCalldeebbcf2010-11-11 05:33:51 +00005164 // White-list bool bitfields.
5165 if (Bitfield->getType()->isBooleanType())
5166 return false;
5167
Douglas Gregor789adec2011-02-04 13:09:01 +00005168 // Ignore value- or type-dependent expressions.
5169 if (Bitfield->getBitWidth()->isValueDependent() ||
5170 Bitfield->getBitWidth()->isTypeDependent() ||
5171 Init->isValueDependent() ||
5172 Init->isTypeDependent())
5173 return false;
5174
John McCall1f425642010-11-11 03:21:53 +00005175 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5176
Richard Smith5fab0c92011-12-28 19:48:30 +00005177 llvm::APSInt Value;
5178 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005179 return false;
5180
John McCall1f425642010-11-11 03:21:53 +00005181 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005182 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005183
5184 if (OriginalWidth <= FieldWidth)
5185 return false;
5186
Eli Friedmanc267a322012-01-26 23:11:39 +00005187 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005188 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005189 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005190
Eli Friedmanc267a322012-01-26 23:11:39 +00005191 // Check whether the stored value is equal to the original value.
5192 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005193 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005194 return false;
5195
Eli Friedmanc267a322012-01-26 23:11:39 +00005196 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005197 // therefore don't strictly fit into a signed bitfield of width 1.
5198 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005199 return false;
5200
John McCall1f425642010-11-11 03:21:53 +00005201 std::string PrettyValue = Value.toString(10);
5202 std::string PrettyTrunc = TruncatedValue.toString(10);
5203
5204 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5205 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5206 << Init->getSourceRange();
5207
5208 return true;
5209}
5210
John McCalld2a53122010-11-09 23:24:47 +00005211/// Analyze the given simple or compound assignment for warning-worthy
5212/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005213static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005214 // Just recurse on the LHS.
5215 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5216
5217 // We want to recurse on the RHS as normal unless we're assigning to
5218 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005219 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005220 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005221 E->getOperatorLoc())) {
5222 // Recurse, ignoring any implicit conversions on the RHS.
5223 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5224 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005225 }
5226 }
5227
5228 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5229}
5230
John McCall263a48b2010-01-04 23:31:57 +00005231/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005232static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005233 SourceLocation CContext, unsigned diag,
5234 bool pruneControlFlow = false) {
5235 if (pruneControlFlow) {
5236 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5237 S.PDiag(diag)
5238 << SourceType << T << E->getSourceRange()
5239 << SourceRange(CContext));
5240 return;
5241 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005242 S.Diag(E->getExprLoc(), diag)
5243 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5244}
5245
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005246/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005247static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005248 SourceLocation CContext, unsigned diag,
5249 bool pruneControlFlow = false) {
5250 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005251}
5252
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005253/// Diagnose an implicit cast from a literal expression. Does not warn when the
5254/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005255void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5256 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005257 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005258 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005259 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005260 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5261 T->hasUnsignedIntegerRepresentation());
5262 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005263 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005264 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005265 return;
5266
Eli Friedman07185912013-08-29 23:44:43 +00005267 // FIXME: Force the precision of the source value down so we don't print
5268 // digits which are usually useless (we don't really care here if we
5269 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5270 // would automatically print the shortest representation, but it's a bit
5271 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005272 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005273 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5274 precision = (precision * 59 + 195) / 196;
5275 Value.toString(PrettySourceValue, precision);
5276
David Blaikie9b88cc02012-05-15 17:18:27 +00005277 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005278 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5279 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5280 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005281 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005282
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005283 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005284 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5285 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005286}
5287
John McCall18a2c2c2010-11-09 22:22:12 +00005288std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5289 if (!Range.Width) return "0";
5290
5291 llvm::APSInt ValueInRange = Value;
5292 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005293 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005294 return ValueInRange.toString(10);
5295}
5296
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005297static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5298 if (!isa<ImplicitCastExpr>(Ex))
5299 return false;
5300
5301 Expr *InnerE = Ex->IgnoreParenImpCasts();
5302 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5303 const Type *Source =
5304 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5305 if (Target->isDependentType())
5306 return false;
5307
5308 const BuiltinType *FloatCandidateBT =
5309 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5310 const Type *BoolCandidateType = ToBool ? Target : Source;
5311
5312 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5313 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5314}
5315
5316void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5317 SourceLocation CC) {
5318 unsigned NumArgs = TheCall->getNumArgs();
5319 for (unsigned i = 0; i < NumArgs; ++i) {
5320 Expr *CurrA = TheCall->getArg(i);
5321 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5322 continue;
5323
5324 bool IsSwapped = ((i > 0) &&
5325 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5326 IsSwapped |= ((i < (NumArgs - 1)) &&
5327 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5328 if (IsSwapped) {
5329 // Warn on this floating-point to bool conversion.
5330 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5331 CurrA->getType(), CC,
5332 diag::warn_impcast_floating_point_to_bool);
5333 }
5334 }
5335}
5336
John McCallcc7e5bf2010-05-06 08:58:33 +00005337void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005338 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005339 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005340
John McCallcc7e5bf2010-05-06 08:58:33 +00005341 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5342 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5343 if (Source == Target) return;
5344 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005345
Chandler Carruthc22845a2011-07-26 05:40:03 +00005346 // If the conversion context location is invalid don't complain. We also
5347 // don't want to emit a warning if the issue occurs from the expansion of
5348 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5349 // delay this check as long as possible. Once we detect we are in that
5350 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005351 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005352 return;
5353
Richard Trieu021baa32011-09-23 20:10:00 +00005354 // Diagnose implicit casts to bool.
5355 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5356 if (isa<StringLiteral>(E))
5357 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005358 // and expressions, for instance, assert(0 && "error here"), are
5359 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005360 return DiagnoseImpCast(S, E, T, CC,
5361 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005362 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5363 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5364 // This covers the literal expressions that evaluate to Objective-C
5365 // objects.
5366 return DiagnoseImpCast(S, E, T, CC,
5367 diag::warn_impcast_objective_c_literal_to_bool);
5368 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00005369 if (Source->isFunctionType()) {
5370 // Warn on function to bool. Checks free functions and static member
5371 // functions. Weakly imported functions are excluded from the check,
5372 // since it's common to test their value to check whether the linker
5373 // found a definition for them.
5374 ValueDecl *D = 0;
5375 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5376 D = R->getDecl();
5377 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5378 D = M->getMemberDecl();
5379 }
5380
5381 if (D && !D->isWeak()) {
Richard Trieu5f623222011-12-06 04:48:01 +00005382 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5383 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5384 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie10eb4b62011-12-09 21:42:37 +00005385 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5386 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5387 QualType ReturnType;
5388 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiee5323aa2013-06-21 23:54:45 +00005389 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie10eb4b62011-12-09 21:42:37 +00005390 if (!ReturnType.isNull()
5391 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5392 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5393 << FixItHint::CreateInsertion(
5394 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu5f623222011-12-06 04:48:01 +00005395 return;
5396 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00005397 }
5398 }
Richard Trieu021baa32011-09-23 20:10:00 +00005399 }
John McCall263a48b2010-01-04 23:31:57 +00005400
5401 // Strip vector types.
5402 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005403 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005404 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005405 return;
John McCallacf0ee52010-10-08 02:01:28 +00005406 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005407 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005408
5409 // If the vector cast is cast between two vectors of the same size, it is
5410 // a bitcast, not a conversion.
5411 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5412 return;
John McCall263a48b2010-01-04 23:31:57 +00005413
5414 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5415 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5416 }
5417
5418 // Strip complex types.
5419 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005420 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005421 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005422 return;
5423
John McCallacf0ee52010-10-08 02:01:28 +00005424 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005425 }
John McCall263a48b2010-01-04 23:31:57 +00005426
5427 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5428 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5429 }
5430
5431 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5432 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5433
5434 // If the source is floating point...
5435 if (SourceBT && SourceBT->isFloatingPoint()) {
5436 // ...and the target is floating point...
5437 if (TargetBT && TargetBT->isFloatingPoint()) {
5438 // ...then warn if we're dropping FP rank.
5439
5440 // Builtin FP kinds are ordered by increasing FP rank.
5441 if (SourceBT->getKind() > TargetBT->getKind()) {
5442 // Don't warn about float constants that are precisely
5443 // representable in the target type.
5444 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005445 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005446 // Value might be a float, a float vector, or a float complex.
5447 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005448 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5449 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005450 return;
5451 }
5452
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005453 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005454 return;
5455
John McCallacf0ee52010-10-08 02:01:28 +00005456 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005457 }
5458 return;
5459 }
5460
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005461 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005462 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005463 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005464 return;
5465
Chandler Carruth22c7a792011-02-17 11:05:49 +00005466 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005467 // We also want to warn on, e.g., "int i = -1.234"
5468 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5469 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5470 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5471
Chandler Carruth016ef402011-04-10 08:36:24 +00005472 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5473 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005474 } else {
5475 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5476 }
5477 }
John McCall263a48b2010-01-04 23:31:57 +00005478
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005479 // If the target is bool, warn if expr is a function or method call.
5480 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5481 isa<CallExpr>(E)) {
5482 // Check last argument of function call to see if it is an
5483 // implicit cast from a type matching the type the result
5484 // is being cast to.
5485 CallExpr *CEx = cast<CallExpr>(E);
5486 unsigned NumArgs = CEx->getNumArgs();
5487 if (NumArgs > 0) {
5488 Expr *LastA = CEx->getArg(NumArgs - 1);
5489 Expr *InnerE = LastA->IgnoreParenImpCasts();
5490 const Type *InnerType =
5491 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5492 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5493 // Warn on this floating-point to bool conversion
5494 DiagnoseImpCast(S, E, T, CC,
5495 diag::warn_impcast_floating_point_to_bool);
5496 }
5497 }
5498 }
John McCall263a48b2010-01-04 23:31:57 +00005499 return;
5500 }
5501
Richard Trieubeaf3452011-05-29 19:59:02 +00005502 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005503 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005504 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005505 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005506 SourceLocation Loc = E->getSourceRange().getBegin();
5507 if (Loc.isMacroID())
5508 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005509 if (!Loc.isMacroID() || CC.isMacroID())
5510 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5511 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005512 << FixItHint::CreateReplacement(Loc,
5513 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005514 }
5515
David Blaikie9366d2b2012-06-19 21:19:06 +00005516 if (!Source->isIntegerType() || !Target->isIntegerType())
5517 return;
5518
David Blaikie7555b6a2012-05-15 16:56:36 +00005519 // TODO: remove this early return once the false positives for constant->bool
5520 // in templates, macros, etc, are reduced or removed.
5521 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5522 return;
5523
John McCallcc7e5bf2010-05-06 08:58:33 +00005524 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005525 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005526
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005527 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005528 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005529 // TODO: this should happen for bitfield stores, too.
5530 llvm::APSInt Value(32);
5531 if (E->isIntegerConstantExpr(Value, S.Context)) {
5532 if (S.SourceMgr.isInSystemMacro(CC))
5533 return;
5534
John McCall18a2c2c2010-11-09 22:22:12 +00005535 std::string PrettySourceValue = Value.toString(10);
5536 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005537
Ted Kremenek33ba9952011-10-22 02:37:33 +00005538 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5539 S.PDiag(diag::warn_impcast_integer_precision_constant)
5540 << PrettySourceValue << PrettyTargetValue
5541 << E->getType() << T << E->getSourceRange()
5542 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005543 return;
5544 }
5545
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005546 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5547 if (S.SourceMgr.isInSystemMacro(CC))
5548 return;
5549
David Blaikie9455da02012-04-12 22:40:54 +00005550 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005551 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5552 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005553 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005554 }
5555
5556 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5557 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5558 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005559
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005560 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005561 return;
5562
John McCallcc7e5bf2010-05-06 08:58:33 +00005563 unsigned DiagID = diag::warn_impcast_integer_sign;
5564
5565 // Traditionally, gcc has warned about this under -Wsign-compare.
5566 // We also want to warn about it in -Wconversion.
5567 // So if -Wconversion is off, use a completely identical diagnostic
5568 // in the sign-compare group.
5569 // The conditional-checking code will
5570 if (ICContext) {
5571 DiagID = diag::warn_impcast_integer_sign_conditional;
5572 *ICContext = true;
5573 }
5574
John McCallacf0ee52010-10-08 02:01:28 +00005575 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005576 }
5577
Douglas Gregora78f1932011-02-22 02:45:07 +00005578 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005579 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5580 // type, to give us better diagnostics.
5581 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005582 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005583 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5584 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5585 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5586 SourceType = S.Context.getTypeDeclType(Enum);
5587 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5588 }
5589 }
5590
Douglas Gregora78f1932011-02-22 02:45:07 +00005591 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5592 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00005593 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5594 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005595 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005596 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005597 return;
5598
Douglas Gregor364f7db2011-03-12 00:14:31 +00005599 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00005600 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005601 }
Douglas Gregora78f1932011-02-22 02:45:07 +00005602
John McCall263a48b2010-01-04 23:31:57 +00005603 return;
5604}
5605
David Blaikie18e9ac72012-05-15 21:57:38 +00005606void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5607 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005608
5609void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00005610 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005611 E = E->IgnoreParenImpCasts();
5612
5613 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00005614 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005615
John McCallacf0ee52010-10-08 02:01:28 +00005616 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005617 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005618 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00005619 return;
5620}
5621
David Blaikie18e9ac72012-05-15 21:57:38 +00005622void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5623 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00005624 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005625
5626 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00005627 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5628 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005629
5630 // If -Wconversion would have warned about either of the candidates
5631 // for a signedness conversion to the context type...
5632 if (!Suspicious) return;
5633
5634 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005635 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5636 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00005637 return;
5638
John McCallcc7e5bf2010-05-06 08:58:33 +00005639 // ...then check whether it would have warned about either of the
5640 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00005641 if (E->getType() == T) return;
5642
5643 Suspicious = false;
5644 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5645 E->getType(), CC, &Suspicious);
5646 if (!Suspicious)
5647 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00005648 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005649}
5650
5651/// AnalyzeImplicitConversions - Find and report any interesting
5652/// implicit conversions in the given expression. There are a couple
5653/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005654void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005655 QualType T = OrigE->getType();
5656 Expr *E = OrigE->IgnoreParenImpCasts();
5657
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00005658 if (E->isTypeDependent() || E->isValueDependent())
5659 return;
5660
John McCallcc7e5bf2010-05-06 08:58:33 +00005661 // For conditional operators, we analyze the arguments as if they
5662 // were being fed directly into the output.
5663 if (isa<ConditionalOperator>(E)) {
5664 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00005665 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005666 return;
5667 }
5668
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005669 // Check implicit argument conversions for function calls.
5670 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5671 CheckImplicitArgumentConversions(S, Call, CC);
5672
John McCallcc7e5bf2010-05-06 08:58:33 +00005673 // Go ahead and check any implicit conversions we might have skipped.
5674 // The non-canonical typecheck is just an optimization;
5675 // CheckImplicitConversion will filter out dead implicit conversions.
5676 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005677 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005678
5679 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005680
5681 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005682 if (POE->getResultExpr())
5683 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005684 }
5685
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005686 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5687 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5688
John McCallcc7e5bf2010-05-06 08:58:33 +00005689 // Skip past explicit casts.
5690 if (isa<ExplicitCastExpr>(E)) {
5691 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00005692 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005693 }
5694
John McCalld2a53122010-11-09 23:24:47 +00005695 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5696 // Do a somewhat different check with comparison operators.
5697 if (BO->isComparisonOp())
5698 return AnalyzeComparison(S, BO);
5699
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005700 // And with simple assignments.
5701 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00005702 return AnalyzeAssignment(S, BO);
5703 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005704
5705 // These break the otherwise-useful invariant below. Fortunately,
5706 // we don't really need to recurse into them, because any internal
5707 // expressions should have been analyzed already when they were
5708 // built into statements.
5709 if (isa<StmtExpr>(E)) return;
5710
5711 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00005712 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00005713
5714 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00005715 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00005716 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00005717 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00005718 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00005719 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00005720 if (!ChildExpr)
5721 continue;
5722
Richard Trieu955231d2014-01-25 01:10:35 +00005723 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00005724 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00005725 // Ignore checking string literals that are in logical and operators.
5726 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00005727 continue;
5728 AnalyzeImplicitConversions(S, ChildExpr, CC);
5729 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005730}
5731
5732} // end anonymous namespace
5733
5734/// Diagnoses "dangerous" implicit conversions within the given
5735/// expression (which is a full expression). Implements -Wconversion
5736/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005737///
5738/// \param CC the "context" location of the implicit conversion, i.e.
5739/// the most location of the syntactic entity requiring the implicit
5740/// conversion
5741void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005742 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00005743 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00005744 return;
5745
5746 // Don't diagnose for value- or type-dependent expressions.
5747 if (E->isTypeDependent() || E->isValueDependent())
5748 return;
5749
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005750 // Check for array bounds violations in cases where the check isn't triggered
5751 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5752 // ArraySubscriptExpr is on the RHS of a variable initialization.
5753 CheckArrayAccess(E);
5754
John McCallacf0ee52010-10-08 02:01:28 +00005755 // This is not the right CC for (e.g.) a variable initialization.
5756 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005757}
5758
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005759/// Diagnose when expression is an integer constant expression and its evaluation
5760/// results in integer overflow
5761void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00005762 if (isa<BinaryOperator>(E->IgnoreParens()))
5763 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005764}
5765
Richard Smithc406cb72013-01-17 01:17:56 +00005766namespace {
5767/// \brief Visitor for expressions which looks for unsequenced operations on the
5768/// same object.
5769class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00005770 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5771
Richard Smithc406cb72013-01-17 01:17:56 +00005772 /// \brief A tree of sequenced regions within an expression. Two regions are
5773 /// unsequenced if one is an ancestor or a descendent of the other. When we
5774 /// finish processing an expression with sequencing, such as a comma
5775 /// expression, we fold its tree nodes into its parent, since they are
5776 /// unsequenced with respect to nodes we will visit later.
5777 class SequenceTree {
5778 struct Value {
5779 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5780 unsigned Parent : 31;
5781 bool Merged : 1;
5782 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005783 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00005784
5785 public:
5786 /// \brief A region within an expression which may be sequenced with respect
5787 /// to some other region.
5788 class Seq {
5789 explicit Seq(unsigned N) : Index(N) {}
5790 unsigned Index;
5791 friend class SequenceTree;
5792 public:
5793 Seq() : Index(0) {}
5794 };
5795
5796 SequenceTree() { Values.push_back(Value(0)); }
5797 Seq root() const { return Seq(0); }
5798
5799 /// \brief Create a new sequence of operations, which is an unsequenced
5800 /// subset of \p Parent. This sequence of operations is sequenced with
5801 /// respect to other children of \p Parent.
5802 Seq allocate(Seq Parent) {
5803 Values.push_back(Value(Parent.Index));
5804 return Seq(Values.size() - 1);
5805 }
5806
5807 /// \brief Merge a sequence of operations into its parent.
5808 void merge(Seq S) {
5809 Values[S.Index].Merged = true;
5810 }
5811
5812 /// \brief Determine whether two operations are unsequenced. This operation
5813 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5814 /// should have been merged into its parent as appropriate.
5815 bool isUnsequenced(Seq Cur, Seq Old) {
5816 unsigned C = representative(Cur.Index);
5817 unsigned Target = representative(Old.Index);
5818 while (C >= Target) {
5819 if (C == Target)
5820 return true;
5821 C = Values[C].Parent;
5822 }
5823 return false;
5824 }
5825
5826 private:
5827 /// \brief Pick a representative for a sequence.
5828 unsigned representative(unsigned K) {
5829 if (Values[K].Merged)
5830 // Perform path compression as we go.
5831 return Values[K].Parent = representative(Values[K].Parent);
5832 return K;
5833 }
5834 };
5835
5836 /// An object for which we can track unsequenced uses.
5837 typedef NamedDecl *Object;
5838
5839 /// Different flavors of object usage which we track. We only track the
5840 /// least-sequenced usage of each kind.
5841 enum UsageKind {
5842 /// A read of an object. Multiple unsequenced reads are OK.
5843 UK_Use,
5844 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00005845 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00005846 UK_ModAsValue,
5847 /// A modification of an object which is not sequenced before the value
5848 /// computation of the expression, such as n++.
5849 UK_ModAsSideEffect,
5850
5851 UK_Count = UK_ModAsSideEffect + 1
5852 };
5853
5854 struct Usage {
5855 Usage() : Use(0), Seq() {}
5856 Expr *Use;
5857 SequenceTree::Seq Seq;
5858 };
5859
5860 struct UsageInfo {
5861 UsageInfo() : Diagnosed(false) {}
5862 Usage Uses[UK_Count];
5863 /// Have we issued a diagnostic for this variable already?
5864 bool Diagnosed;
5865 };
5866 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5867
5868 Sema &SemaRef;
5869 /// Sequenced regions within the expression.
5870 SequenceTree Tree;
5871 /// Declaration modifications and references which we have seen.
5872 UsageInfoMap UsageMap;
5873 /// The region we are currently within.
5874 SequenceTree::Seq Region;
5875 /// Filled in with declarations which were modified as a side-effect
5876 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005877 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00005878 /// Expressions to check later. We defer checking these to reduce
5879 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005880 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00005881
5882 /// RAII object wrapping the visitation of a sequenced subexpression of an
5883 /// expression. At the end of this process, the side-effects of the evaluation
5884 /// become sequenced with respect to the value computation of the result, so
5885 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5886 /// UK_ModAsValue.
5887 struct SequencedSubexpression {
5888 SequencedSubexpression(SequenceChecker &Self)
5889 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5890 Self.ModAsSideEffect = &ModAsSideEffect;
5891 }
5892 ~SequencedSubexpression() {
5893 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5894 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5895 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5896 Self.addUsage(U, ModAsSideEffect[I].first,
5897 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5898 }
5899 Self.ModAsSideEffect = OldModAsSideEffect;
5900 }
5901
5902 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005903 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5904 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00005905 };
5906
Richard Smith40238f02013-06-20 22:21:56 +00005907 /// RAII object wrapping the visitation of a subexpression which we might
5908 /// choose to evaluate as a constant. If any subexpression is evaluated and
5909 /// found to be non-constant, this allows us to suppress the evaluation of
5910 /// the outer expression.
5911 class EvaluationTracker {
5912 public:
5913 EvaluationTracker(SequenceChecker &Self)
5914 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5915 Self.EvalTracker = this;
5916 }
5917 ~EvaluationTracker() {
5918 Self.EvalTracker = Prev;
5919 if (Prev)
5920 Prev->EvalOK &= EvalOK;
5921 }
5922
5923 bool evaluate(const Expr *E, bool &Result) {
5924 if (!EvalOK || E->isValueDependent())
5925 return false;
5926 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5927 return EvalOK;
5928 }
5929
5930 private:
5931 SequenceChecker &Self;
5932 EvaluationTracker *Prev;
5933 bool EvalOK;
5934 } *EvalTracker;
5935
Richard Smithc406cb72013-01-17 01:17:56 +00005936 /// \brief Find the object which is produced by the specified expression,
5937 /// if any.
5938 Object getObject(Expr *E, bool Mod) const {
5939 E = E->IgnoreParenCasts();
5940 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5941 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5942 return getObject(UO->getSubExpr(), Mod);
5943 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5944 if (BO->getOpcode() == BO_Comma)
5945 return getObject(BO->getRHS(), Mod);
5946 if (Mod && BO->isAssignmentOp())
5947 return getObject(BO->getLHS(), Mod);
5948 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5949 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5950 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5951 return ME->getMemberDecl();
5952 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5953 // FIXME: If this is a reference, map through to its value.
5954 return DRE->getDecl();
5955 return 0;
5956 }
5957
5958 /// \brief Note that an object was modified or used by an expression.
5959 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5960 Usage &U = UI.Uses[UK];
5961 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5962 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5963 ModAsSideEffect->push_back(std::make_pair(O, U));
5964 U.Use = Ref;
5965 U.Seq = Region;
5966 }
5967 }
5968 /// \brief Check whether a modification or use conflicts with a prior usage.
5969 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5970 bool IsModMod) {
5971 if (UI.Diagnosed)
5972 return;
5973
5974 const Usage &U = UI.Uses[OtherKind];
5975 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5976 return;
5977
5978 Expr *Mod = U.Use;
5979 Expr *ModOrUse = Ref;
5980 if (OtherKind == UK_Use)
5981 std::swap(Mod, ModOrUse);
5982
5983 SemaRef.Diag(Mod->getExprLoc(),
5984 IsModMod ? diag::warn_unsequenced_mod_mod
5985 : diag::warn_unsequenced_mod_use)
5986 << O << SourceRange(ModOrUse->getExprLoc());
5987 UI.Diagnosed = true;
5988 }
5989
5990 void notePreUse(Object O, Expr *Use) {
5991 UsageInfo &U = UsageMap[O];
5992 // Uses conflict with other modifications.
5993 checkUsage(O, U, Use, UK_ModAsValue, false);
5994 }
5995 void notePostUse(Object O, Expr *Use) {
5996 UsageInfo &U = UsageMap[O];
5997 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5998 addUsage(U, O, Use, UK_Use);
5999 }
6000
6001 void notePreMod(Object O, Expr *Mod) {
6002 UsageInfo &U = UsageMap[O];
6003 // Modifications conflict with other modifications and with uses.
6004 checkUsage(O, U, Mod, UK_ModAsValue, true);
6005 checkUsage(O, U, Mod, UK_Use, false);
6006 }
6007 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6008 UsageInfo &U = UsageMap[O];
6009 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6010 addUsage(U, O, Use, UK);
6011 }
6012
6013public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006014 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6015 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6016 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00006017 Visit(E);
6018 }
6019
6020 void VisitStmt(Stmt *S) {
6021 // Skip all statements which aren't expressions for now.
6022 }
6023
6024 void VisitExpr(Expr *E) {
6025 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006026 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006027 }
6028
6029 void VisitCastExpr(CastExpr *E) {
6030 Object O = Object();
6031 if (E->getCastKind() == CK_LValueToRValue)
6032 O = getObject(E->getSubExpr(), false);
6033
6034 if (O)
6035 notePreUse(O, E);
6036 VisitExpr(E);
6037 if (O)
6038 notePostUse(O, E);
6039 }
6040
6041 void VisitBinComma(BinaryOperator *BO) {
6042 // C++11 [expr.comma]p1:
6043 // Every value computation and side effect associated with the left
6044 // expression is sequenced before every value computation and side
6045 // effect associated with the right expression.
6046 SequenceTree::Seq LHS = Tree.allocate(Region);
6047 SequenceTree::Seq RHS = Tree.allocate(Region);
6048 SequenceTree::Seq OldRegion = Region;
6049
6050 {
6051 SequencedSubexpression SeqLHS(*this);
6052 Region = LHS;
6053 Visit(BO->getLHS());
6054 }
6055
6056 Region = RHS;
6057 Visit(BO->getRHS());
6058
6059 Region = OldRegion;
6060
6061 // Forget that LHS and RHS are sequenced. They are both unsequenced
6062 // with respect to other stuff.
6063 Tree.merge(LHS);
6064 Tree.merge(RHS);
6065 }
6066
6067 void VisitBinAssign(BinaryOperator *BO) {
6068 // The modification is sequenced after the value computation of the LHS
6069 // and RHS, so check it before inspecting the operands and update the
6070 // map afterwards.
6071 Object O = getObject(BO->getLHS(), true);
6072 if (!O)
6073 return VisitExpr(BO);
6074
6075 notePreMod(O, BO);
6076
6077 // C++11 [expr.ass]p7:
6078 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6079 // only once.
6080 //
6081 // Therefore, for a compound assignment operator, O is considered used
6082 // everywhere except within the evaluation of E1 itself.
6083 if (isa<CompoundAssignOperator>(BO))
6084 notePreUse(O, BO);
6085
6086 Visit(BO->getLHS());
6087
6088 if (isa<CompoundAssignOperator>(BO))
6089 notePostUse(O, BO);
6090
6091 Visit(BO->getRHS());
6092
Richard Smith83e37bee2013-06-26 23:16:51 +00006093 // C++11 [expr.ass]p1:
6094 // the assignment is sequenced [...] before the value computation of the
6095 // assignment expression.
6096 // C11 6.5.16/3 has no such rule.
6097 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6098 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006099 }
6100 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6101 VisitBinAssign(CAO);
6102 }
6103
6104 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6105 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6106 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6107 Object O = getObject(UO->getSubExpr(), true);
6108 if (!O)
6109 return VisitExpr(UO);
6110
6111 notePreMod(O, UO);
6112 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006113 // C++11 [expr.pre.incr]p1:
6114 // the expression ++x is equivalent to x+=1
6115 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6116 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006117 }
6118
6119 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6120 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6121 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6122 Object O = getObject(UO->getSubExpr(), true);
6123 if (!O)
6124 return VisitExpr(UO);
6125
6126 notePreMod(O, UO);
6127 Visit(UO->getSubExpr());
6128 notePostMod(O, UO, UK_ModAsSideEffect);
6129 }
6130
6131 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6132 void VisitBinLOr(BinaryOperator *BO) {
6133 // The side-effects of the LHS of an '&&' are sequenced before the
6134 // value computation of the RHS, and hence before the value computation
6135 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6136 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006137 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006138 {
6139 SequencedSubexpression Sequenced(*this);
6140 Visit(BO->getLHS());
6141 }
6142
6143 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006144 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006145 if (!Result)
6146 Visit(BO->getRHS());
6147 } else {
6148 // Check for unsequenced operations in the RHS, treating it as an
6149 // entirely separate evaluation.
6150 //
6151 // FIXME: If there are operations in the RHS which are unsequenced
6152 // with respect to operations outside the RHS, and those operations
6153 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006154 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006155 }
Richard Smithc406cb72013-01-17 01:17:56 +00006156 }
6157 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006158 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006159 {
6160 SequencedSubexpression Sequenced(*this);
6161 Visit(BO->getLHS());
6162 }
6163
6164 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006165 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006166 if (Result)
6167 Visit(BO->getRHS());
6168 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006169 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006170 }
Richard Smithc406cb72013-01-17 01:17:56 +00006171 }
6172
6173 // Only visit the condition, unless we can be sure which subexpression will
6174 // be chosen.
6175 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006176 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006177 {
6178 SequencedSubexpression Sequenced(*this);
6179 Visit(CO->getCond());
6180 }
Richard Smithc406cb72013-01-17 01:17:56 +00006181
6182 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006183 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006184 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006185 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006186 WorkList.push_back(CO->getTrueExpr());
6187 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006188 }
Richard Smithc406cb72013-01-17 01:17:56 +00006189 }
6190
Richard Smithe3dbfe02013-06-30 10:40:20 +00006191 void VisitCallExpr(CallExpr *CE) {
6192 // C++11 [intro.execution]p15:
6193 // When calling a function [...], every value computation and side effect
6194 // associated with any argument expression, or with the postfix expression
6195 // designating the called function, is sequenced before execution of every
6196 // expression or statement in the body of the function [and thus before
6197 // the value computation of its result].
6198 SequencedSubexpression Sequenced(*this);
6199 Base::VisitCallExpr(CE);
6200
6201 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6202 }
6203
Richard Smithc406cb72013-01-17 01:17:56 +00006204 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006205 // This is a call, so all subexpressions are sequenced before the result.
6206 SequencedSubexpression Sequenced(*this);
6207
Richard Smithc406cb72013-01-17 01:17:56 +00006208 if (!CCE->isListInitialization())
6209 return VisitExpr(CCE);
6210
6211 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006212 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006213 SequenceTree::Seq Parent = Region;
6214 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6215 E = CCE->arg_end();
6216 I != E; ++I) {
6217 Region = Tree.allocate(Parent);
6218 Elts.push_back(Region);
6219 Visit(*I);
6220 }
6221
6222 // Forget that the initializers are sequenced.
6223 Region = Parent;
6224 for (unsigned I = 0; I < Elts.size(); ++I)
6225 Tree.merge(Elts[I]);
6226 }
6227
6228 void VisitInitListExpr(InitListExpr *ILE) {
6229 if (!SemaRef.getLangOpts().CPlusPlus11)
6230 return VisitExpr(ILE);
6231
6232 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006233 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006234 SequenceTree::Seq Parent = Region;
6235 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6236 Expr *E = ILE->getInit(I);
6237 if (!E) continue;
6238 Region = Tree.allocate(Parent);
6239 Elts.push_back(Region);
6240 Visit(E);
6241 }
6242
6243 // Forget that the initializers are sequenced.
6244 Region = Parent;
6245 for (unsigned I = 0; I < Elts.size(); ++I)
6246 Tree.merge(Elts[I]);
6247 }
6248};
6249}
6250
6251void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006252 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006253 WorkList.push_back(E);
6254 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006255 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006256 SequenceChecker(*this, Item, WorkList);
6257 }
Richard Smithc406cb72013-01-17 01:17:56 +00006258}
6259
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006260void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6261 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006262 CheckImplicitConversions(E, CheckLoc);
6263 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006264 if (!IsConstexpr && !E->isValueDependent())
6265 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006266}
6267
John McCall1f425642010-11-11 03:21:53 +00006268void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6269 FieldDecl *BitField,
6270 Expr *Init) {
6271 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6272}
6273
Mike Stump0c2ec772010-01-21 03:59:47 +00006274/// CheckParmsForFunctionDef - Check that the parameters of the given
6275/// function are appropriate for the definition of a function. This
6276/// takes care of any checks that cannot be performed on the
6277/// declaration itself, e.g., that the types of each of the function
6278/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006279bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6280 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006281 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006282 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006283 for (; P != PEnd; ++P) {
6284 ParmVarDecl *Param = *P;
6285
Mike Stump0c2ec772010-01-21 03:59:47 +00006286 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6287 // function declarator that is part of a function definition of
6288 // that function shall not have incomplete type.
6289 //
6290 // This is also C++ [dcl.fct]p6.
6291 if (!Param->isInvalidDecl() &&
6292 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006293 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006294 Param->setInvalidDecl();
6295 HasInvalidParm = true;
6296 }
6297
6298 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6299 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006300 if (CheckParameterNames &&
6301 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006302 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006303 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006304 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006305
6306 // C99 6.7.5.3p12:
6307 // If the function declarator is not part of a definition of that
6308 // function, parameters may have incomplete type and may use the [*]
6309 // notation in their sequences of declarator specifiers to specify
6310 // variable length array types.
6311 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006312 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006313 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006314 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006315 // information is added for it.
6316 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006317 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006318 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006319 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006320 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006321
6322 // MSVC destroys objects passed by value in the callee. Therefore a
6323 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006324 // object's destructor. However, we don't perform any direct access check
6325 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006326 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6327 .getCXXABI()
6328 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006329 if (!Param->isInvalidDecl()) {
6330 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6331 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6332 if (!ClassDecl->isInvalidDecl() &&
6333 !ClassDecl->hasIrrelevantDestructor() &&
6334 !ClassDecl->isDependentContext()) {
6335 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6336 MarkFunctionReferenced(Param->getLocation(), Destructor);
6337 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6338 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006339 }
6340 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006341 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006342 }
6343
6344 return HasInvalidParm;
6345}
John McCall2b5c1b22010-08-12 21:44:57 +00006346
6347/// CheckCastAlign - Implements -Wcast-align, which warns when a
6348/// pointer cast increases the alignment requirements.
6349void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6350 // This is actually a lot of work to potentially be doing on every
6351 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006352 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6353 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006354 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006355 return;
6356
6357 // Ignore dependent types.
6358 if (T->isDependentType() || Op->getType()->isDependentType())
6359 return;
6360
6361 // Require that the destination be a pointer type.
6362 const PointerType *DestPtr = T->getAs<PointerType>();
6363 if (!DestPtr) return;
6364
6365 // If the destination has alignment 1, we're done.
6366 QualType DestPointee = DestPtr->getPointeeType();
6367 if (DestPointee->isIncompleteType()) return;
6368 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6369 if (DestAlign.isOne()) return;
6370
6371 // Require that the source be a pointer type.
6372 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6373 if (!SrcPtr) return;
6374 QualType SrcPointee = SrcPtr->getPointeeType();
6375
6376 // Whitelist casts from cv void*. We already implicitly
6377 // whitelisted casts to cv void*, since they have alignment 1.
6378 // Also whitelist casts involving incomplete types, which implicitly
6379 // includes 'void'.
6380 if (SrcPointee->isIncompleteType()) return;
6381
6382 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6383 if (SrcAlign >= DestAlign) return;
6384
6385 Diag(TRange.getBegin(), diag::warn_cast_align)
6386 << Op->getType() << T
6387 << static_cast<unsigned>(SrcAlign.getQuantity())
6388 << static_cast<unsigned>(DestAlign.getQuantity())
6389 << TRange << Op->getSourceRange();
6390}
6391
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006392static const Type* getElementType(const Expr *BaseExpr) {
6393 const Type* EltType = BaseExpr->getType().getTypePtr();
6394 if (EltType->isAnyPointerType())
6395 return EltType->getPointeeType().getTypePtr();
6396 else if (EltType->isArrayType())
6397 return EltType->getBaseElementTypeUnsafe();
6398 return EltType;
6399}
6400
Chandler Carruth28389f02011-08-05 09:10:50 +00006401/// \brief Check whether this array fits the idiom of a size-one tail padded
6402/// array member of a struct.
6403///
6404/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6405/// commonly used to emulate flexible arrays in C89 code.
6406static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6407 const NamedDecl *ND) {
6408 if (Size != 1 || !ND) return false;
6409
6410 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6411 if (!FD) return false;
6412
6413 // Don't consider sizes resulting from macro expansions or template argument
6414 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006415
6416 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006417 while (TInfo) {
6418 TypeLoc TL = TInfo->getTypeLoc();
6419 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006420 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6421 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006422 TInfo = TDL->getTypeSourceInfo();
6423 continue;
6424 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006425 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6426 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006427 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6428 return false;
6429 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006430 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006431 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006432
6433 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006434 if (!RD) return false;
6435 if (RD->isUnion()) return false;
6436 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6437 if (!CRD->isStandardLayout()) return false;
6438 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006439
Benjamin Kramer8c543672011-08-06 03:04:42 +00006440 // See if this is the last field decl in the record.
6441 const Decl *D = FD;
6442 while ((D = D->getNextDeclInContext()))
6443 if (isa<FieldDecl>(D))
6444 return false;
6445 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006446}
6447
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006448void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006449 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006450 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006451 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006452 if (IndexExpr->isValueDependent())
6453 return;
6454
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006455 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006456 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006457 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006458 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006459 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006460 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006461
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006462 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006463 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006464 return;
Richard Smith13f67182011-12-16 19:31:14 +00006465 if (IndexNegated)
6466 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006467
Chandler Carruth126b1552011-08-05 08:07:29 +00006468 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00006469 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6470 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00006471 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00006472 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00006473
Ted Kremeneke4b316c2011-02-23 23:06:04 +00006474 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006475 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00006476 if (!size.isStrictlyPositive())
6477 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006478
6479 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00006480 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006481 // Make sure we're comparing apples to apples when comparing index to size
6482 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6483 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00006484 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00006485 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006486 if (ptrarith_typesize != array_typesize) {
6487 // There's a cast to a different size type involved
6488 uint64_t ratio = array_typesize / ptrarith_typesize;
6489 // TODO: Be smarter about handling cases where array_typesize is not a
6490 // multiple of ptrarith_typesize
6491 if (ptrarith_typesize * ratio == array_typesize)
6492 size *= llvm::APInt(size.getBitWidth(), ratio);
6493 }
6494 }
6495
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006496 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006497 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006498 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006499 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006500
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006501 // For array subscripting the index must be less than size, but for pointer
6502 // arithmetic also allow the index (offset) to be equal to size since
6503 // computing the next address after the end of the array is legal and
6504 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006505 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00006506 return;
6507
6508 // Also don't warn for arrays of size 1 which are members of some
6509 // structure. These are often used to approximate flexible arrays in C89
6510 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006511 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00006512 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006513
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006514 // Suppress the warning if the subscript expression (as identified by the
6515 // ']' location) and the index expression are both from macro expansions
6516 // within a system header.
6517 if (ASE) {
6518 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6519 ASE->getRBracketLoc());
6520 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6521 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6522 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00006523 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006524 return;
6525 }
6526 }
6527
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006528 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006529 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006530 DiagID = diag::warn_array_index_exceeds_bounds;
6531
6532 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6533 PDiag(DiagID) << index.toString(10, true)
6534 << size.toString(10, true)
6535 << (unsigned)size.getLimitedValue(~0U)
6536 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006537 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006538 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006539 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006540 DiagID = diag::warn_ptr_arith_precedes_bounds;
6541 if (index.isNegative()) index = -index;
6542 }
6543
6544 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6545 PDiag(DiagID) << index.toString(10, true)
6546 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00006547 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00006548
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00006549 if (!ND) {
6550 // Try harder to find a NamedDecl to point at in the note.
6551 while (const ArraySubscriptExpr *ASE =
6552 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6553 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6554 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6555 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6556 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6557 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6558 }
6559
Chandler Carruth1af88f12011-02-17 21:10:52 +00006560 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006561 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6562 PDiag(diag::note_array_index_out_of_bounds)
6563 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00006564}
6565
Ted Kremenekdf26df72011-03-01 18:41:00 +00006566void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006567 int AllowOnePastEnd = 0;
6568 while (expr) {
6569 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00006570 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006571 case Stmt::ArraySubscriptExprClass: {
6572 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006573 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006574 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00006575 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006576 }
6577 case Stmt::UnaryOperatorClass: {
6578 // Only unwrap the * and & unary operators
6579 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6580 expr = UO->getSubExpr();
6581 switch (UO->getOpcode()) {
6582 case UO_AddrOf:
6583 AllowOnePastEnd++;
6584 break;
6585 case UO_Deref:
6586 AllowOnePastEnd--;
6587 break;
6588 default:
6589 return;
6590 }
6591 break;
6592 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006593 case Stmt::ConditionalOperatorClass: {
6594 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6595 if (const Expr *lhs = cond->getLHS())
6596 CheckArrayAccess(lhs);
6597 if (const Expr *rhs = cond->getRHS())
6598 CheckArrayAccess(rhs);
6599 return;
6600 }
6601 default:
6602 return;
6603 }
Peter Collingbourne91147592011-04-15 00:35:48 +00006604 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006605}
John McCall31168b02011-06-15 23:02:42 +00006606
6607//===--- CHECK: Objective-C retain cycles ----------------------------------//
6608
6609namespace {
6610 struct RetainCycleOwner {
6611 RetainCycleOwner() : Variable(0), Indirect(false) {}
6612 VarDecl *Variable;
6613 SourceRange Range;
6614 SourceLocation Loc;
6615 bool Indirect;
6616
6617 void setLocsFrom(Expr *e) {
6618 Loc = e->getExprLoc();
6619 Range = e->getSourceRange();
6620 }
6621 };
6622}
6623
6624/// Consider whether capturing the given variable can possibly lead to
6625/// a retain cycle.
6626static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006627 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00006628 // lifetime. In MRR, it's captured strongly if the variable is
6629 // __block and has an appropriate type.
6630 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6631 return false;
6632
6633 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006634 if (ref)
6635 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00006636 return true;
6637}
6638
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006639static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00006640 while (true) {
6641 e = e->IgnoreParens();
6642 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6643 switch (cast->getCastKind()) {
6644 case CK_BitCast:
6645 case CK_LValueBitCast:
6646 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00006647 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00006648 e = cast->getSubExpr();
6649 continue;
6650
John McCall31168b02011-06-15 23:02:42 +00006651 default:
6652 return false;
6653 }
6654 }
6655
6656 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6657 ObjCIvarDecl *ivar = ref->getDecl();
6658 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6659 return false;
6660
6661 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006662 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00006663 return false;
6664
6665 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6666 owner.Indirect = true;
6667 return true;
6668 }
6669
6670 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6671 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6672 if (!var) return false;
6673 return considerVariable(var, ref, owner);
6674 }
6675
John McCall31168b02011-06-15 23:02:42 +00006676 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6677 if (member->isArrow()) return false;
6678
6679 // Don't count this as an indirect ownership.
6680 e = member->getBase();
6681 continue;
6682 }
6683
John McCallfe96e0b2011-11-06 09:01:30 +00006684 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6685 // Only pay attention to pseudo-objects on property references.
6686 ObjCPropertyRefExpr *pre
6687 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6688 ->IgnoreParens());
6689 if (!pre) return false;
6690 if (pre->isImplicitProperty()) return false;
6691 ObjCPropertyDecl *property = pre->getExplicitProperty();
6692 if (!property->isRetaining() &&
6693 !(property->getPropertyIvarDecl() &&
6694 property->getPropertyIvarDecl()->getType()
6695 .getObjCLifetime() == Qualifiers::OCL_Strong))
6696 return false;
6697
6698 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006699 if (pre->isSuperReceiver()) {
6700 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6701 if (!owner.Variable)
6702 return false;
6703 owner.Loc = pre->getLocation();
6704 owner.Range = pre->getSourceRange();
6705 return true;
6706 }
John McCallfe96e0b2011-11-06 09:01:30 +00006707 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6708 ->getSourceExpr());
6709 continue;
6710 }
6711
John McCall31168b02011-06-15 23:02:42 +00006712 // Array ivars?
6713
6714 return false;
6715 }
6716}
6717
6718namespace {
6719 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6720 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6721 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6722 Variable(variable), Capturer(0) {}
6723
6724 VarDecl *Variable;
6725 Expr *Capturer;
6726
6727 void VisitDeclRefExpr(DeclRefExpr *ref) {
6728 if (ref->getDecl() == Variable && !Capturer)
6729 Capturer = ref;
6730 }
6731
John McCall31168b02011-06-15 23:02:42 +00006732 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6733 if (Capturer) return;
6734 Visit(ref->getBase());
6735 if (Capturer && ref->isFreeIvar())
6736 Capturer = ref;
6737 }
6738
6739 void VisitBlockExpr(BlockExpr *block) {
6740 // Look inside nested blocks
6741 if (block->getBlockDecl()->capturesVariable(Variable))
6742 Visit(block->getBlockDecl()->getBody());
6743 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00006744
6745 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6746 if (Capturer) return;
6747 if (OVE->getSourceExpr())
6748 Visit(OVE->getSourceExpr());
6749 }
John McCall31168b02011-06-15 23:02:42 +00006750 };
6751}
6752
6753/// Check whether the given argument is a block which captures a
6754/// variable.
6755static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6756 assert(owner.Variable && owner.Loc.isValid());
6757
6758 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00006759
6760 // Look through [^{...} copy] and Block_copy(^{...}).
6761 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6762 Selector Cmd = ME->getSelector();
6763 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6764 e = ME->getInstanceReceiver();
6765 if (!e)
6766 return 0;
6767 e = e->IgnoreParenCasts();
6768 }
6769 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6770 if (CE->getNumArgs() == 1) {
6771 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00006772 if (Fn) {
6773 const IdentifierInfo *FnI = Fn->getIdentifier();
6774 if (FnI && FnI->isStr("_Block_copy")) {
6775 e = CE->getArg(0)->IgnoreParenCasts();
6776 }
6777 }
Jordan Rose67e887c2012-09-17 17:54:30 +00006778 }
6779 }
6780
John McCall31168b02011-06-15 23:02:42 +00006781 BlockExpr *block = dyn_cast<BlockExpr>(e);
6782 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6783 return 0;
6784
6785 FindCaptureVisitor visitor(S.Context, owner.Variable);
6786 visitor.Visit(block->getBlockDecl()->getBody());
6787 return visitor.Capturer;
6788}
6789
6790static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6791 RetainCycleOwner &owner) {
6792 assert(capturer);
6793 assert(owner.Variable && owner.Loc.isValid());
6794
6795 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6796 << owner.Variable << capturer->getSourceRange();
6797 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6798 << owner.Indirect << owner.Range;
6799}
6800
6801/// Check for a keyword selector that starts with the word 'add' or
6802/// 'set'.
6803static bool isSetterLikeSelector(Selector sel) {
6804 if (sel.isUnarySelector()) return false;
6805
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006806 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00006807 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006808 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00006809 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006810 else if (str.startswith("add")) {
6811 // Specially whitelist 'addOperationWithBlock:'.
6812 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6813 return false;
6814 str = str.substr(3);
6815 }
John McCall31168b02011-06-15 23:02:42 +00006816 else
6817 return false;
6818
6819 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00006820 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00006821}
6822
6823/// Check a message send to see if it's likely to cause a retain cycle.
6824void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6825 // Only check instance methods whose selector looks like a setter.
6826 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6827 return;
6828
6829 // Try to find a variable that the receiver is strongly owned by.
6830 RetainCycleOwner owner;
6831 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006832 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00006833 return;
6834 } else {
6835 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6836 owner.Variable = getCurMethodDecl()->getSelfDecl();
6837 owner.Loc = msg->getSuperLoc();
6838 owner.Range = msg->getSuperLoc();
6839 }
6840
6841 // Check whether the receiver is captured by any of the arguments.
6842 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6843 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6844 return diagnoseRetainCycle(*this, capturer, owner);
6845}
6846
6847/// Check a property assign to see if it's likely to cause a retain cycle.
6848void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6849 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006850 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00006851 return;
6852
6853 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6854 diagnoseRetainCycle(*this, capturer, owner);
6855}
6856
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006857void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6858 RetainCycleOwner Owner;
6859 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6860 return;
6861
6862 // Because we don't have an expression for the variable, we have to set the
6863 // location explicitly here.
6864 Owner.Loc = Var->getLocation();
6865 Owner.Range = Var->getSourceRange();
6866
6867 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6868 diagnoseRetainCycle(*this, Capturer, Owner);
6869}
6870
Ted Kremenek9304da92012-12-21 08:04:28 +00006871static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6872 Expr *RHS, bool isProperty) {
6873 // Check if RHS is an Objective-C object literal, which also can get
6874 // immediately zapped in a weak reference. Note that we explicitly
6875 // allow ObjCStringLiterals, since those are designed to never really die.
6876 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006877
Ted Kremenek64873352012-12-21 22:46:35 +00006878 // This enum needs to match with the 'select' in
6879 // warn_objc_arc_literal_assign (off-by-1).
6880 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6881 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6882 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006883
6884 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00006885 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00006886 << (isProperty ? 0 : 1)
6887 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006888
6889 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00006890}
6891
Ted Kremenekc1f014a2012-12-21 19:45:30 +00006892static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6893 Qualifiers::ObjCLifetime LT,
6894 Expr *RHS, bool isProperty) {
6895 // Strip off any implicit cast added to get to the one ARC-specific.
6896 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6897 if (cast->getCastKind() == CK_ARCConsumeObject) {
6898 S.Diag(Loc, diag::warn_arc_retained_assign)
6899 << (LT == Qualifiers::OCL_ExplicitNone)
6900 << (isProperty ? 0 : 1)
6901 << RHS->getSourceRange();
6902 return true;
6903 }
6904 RHS = cast->getSubExpr();
6905 }
6906
6907 if (LT == Qualifiers::OCL_Weak &&
6908 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6909 return true;
6910
6911 return false;
6912}
6913
Ted Kremenekb36234d2012-12-21 08:04:20 +00006914bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6915 QualType LHS, Expr *RHS) {
6916 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6917
6918 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6919 return false;
6920
6921 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6922 return true;
6923
6924 return false;
6925}
6926
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006927void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6928 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006929 QualType LHSType;
6930 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006931 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006932 ObjCPropertyRefExpr *PRE
6933 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6934 if (PRE && !PRE->isImplicitProperty()) {
6935 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6936 if (PD)
6937 LHSType = PD->getType();
6938 }
6939
6940 if (LHSType.isNull())
6941 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00006942
6943 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6944
6945 if (LT == Qualifiers::OCL_Weak) {
6946 DiagnosticsEngine::Level Level =
6947 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6948 if (Level != DiagnosticsEngine::Ignored)
6949 getCurFunction()->markSafeWeakUse(LHS);
6950 }
6951
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006952 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6953 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00006954
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006955 // FIXME. Check for other life times.
6956 if (LT != Qualifiers::OCL_None)
6957 return;
6958
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006959 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006960 if (PRE->isImplicitProperty())
6961 return;
6962 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6963 if (!PD)
6964 return;
6965
Bill Wendling44426052012-12-20 19:22:21 +00006966 unsigned Attributes = PD->getPropertyAttributes();
6967 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006968 // when 'assign' attribute was not explicitly specified
6969 // by user, ignore it and rely on property type itself
6970 // for lifetime info.
6971 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6972 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6973 LHSType->isObjCRetainableType())
6974 return;
6975
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006976 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00006977 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006978 Diag(Loc, diag::warn_arc_retained_property_assign)
6979 << RHS->getSourceRange();
6980 return;
6981 }
6982 RHS = cast->getSubExpr();
6983 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006984 }
Bill Wendling44426052012-12-20 19:22:21 +00006985 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00006986 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6987 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00006988 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006989 }
6990}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00006991
6992//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6993
6994namespace {
6995bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6996 SourceLocation StmtLoc,
6997 const NullStmt *Body) {
6998 // Do not warn if the body is a macro that expands to nothing, e.g:
6999 //
7000 // #define CALL(x)
7001 // if (condition)
7002 // CALL(0);
7003 //
7004 if (Body->hasLeadingEmptyMacro())
7005 return false;
7006
7007 // Get line numbers of statement and body.
7008 bool StmtLineInvalid;
7009 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7010 &StmtLineInvalid);
7011 if (StmtLineInvalid)
7012 return false;
7013
7014 bool BodyLineInvalid;
7015 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7016 &BodyLineInvalid);
7017 if (BodyLineInvalid)
7018 return false;
7019
7020 // Warn if null statement and body are on the same line.
7021 if (StmtLine != BodyLine)
7022 return false;
7023
7024 return true;
7025}
7026} // Unnamed namespace
7027
7028void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7029 const Stmt *Body,
7030 unsigned DiagID) {
7031 // Since this is a syntactic check, don't emit diagnostic for template
7032 // instantiations, this just adds noise.
7033 if (CurrentInstantiationScope)
7034 return;
7035
7036 // The body should be a null statement.
7037 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7038 if (!NBody)
7039 return;
7040
7041 // Do the usual checks.
7042 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7043 return;
7044
7045 Diag(NBody->getSemiLoc(), DiagID);
7046 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7047}
7048
7049void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7050 const Stmt *PossibleBody) {
7051 assert(!CurrentInstantiationScope); // Ensured by caller
7052
7053 SourceLocation StmtLoc;
7054 const Stmt *Body;
7055 unsigned DiagID;
7056 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7057 StmtLoc = FS->getRParenLoc();
7058 Body = FS->getBody();
7059 DiagID = diag::warn_empty_for_body;
7060 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7061 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7062 Body = WS->getBody();
7063 DiagID = diag::warn_empty_while_body;
7064 } else
7065 return; // Neither `for' nor `while'.
7066
7067 // The body should be a null statement.
7068 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7069 if (!NBody)
7070 return;
7071
7072 // Skip expensive checks if diagnostic is disabled.
7073 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7074 DiagnosticsEngine::Ignored)
7075 return;
7076
7077 // Do the usual checks.
7078 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7079 return;
7080
7081 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7082 // noise level low, emit diagnostics only if for/while is followed by a
7083 // CompoundStmt, e.g.:
7084 // for (int i = 0; i < n; i++);
7085 // {
7086 // a(i);
7087 // }
7088 // or if for/while is followed by a statement with more indentation
7089 // than for/while itself:
7090 // for (int i = 0; i < n; i++);
7091 // a(i);
7092 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7093 if (!ProbableTypo) {
7094 bool BodyColInvalid;
7095 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7096 PossibleBody->getLocStart(),
7097 &BodyColInvalid);
7098 if (BodyColInvalid)
7099 return;
7100
7101 bool StmtColInvalid;
7102 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7103 S->getLocStart(),
7104 &StmtColInvalid);
7105 if (StmtColInvalid)
7106 return;
7107
7108 if (BodyCol > StmtCol)
7109 ProbableTypo = true;
7110 }
7111
7112 if (ProbableTypo) {
7113 Diag(NBody->getSemiLoc(), DiagID);
7114 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7115 }
7116}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007117
7118//===--- Layout compatibility ----------------------------------------------//
7119
7120namespace {
7121
7122bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7123
7124/// \brief Check if two enumeration types are layout-compatible.
7125bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7126 // C++11 [dcl.enum] p8:
7127 // Two enumeration types are layout-compatible if they have the same
7128 // underlying type.
7129 return ED1->isComplete() && ED2->isComplete() &&
7130 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7131}
7132
7133/// \brief Check if two fields are layout-compatible.
7134bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7135 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7136 return false;
7137
7138 if (Field1->isBitField() != Field2->isBitField())
7139 return false;
7140
7141 if (Field1->isBitField()) {
7142 // Make sure that the bit-fields are the same length.
7143 unsigned Bits1 = Field1->getBitWidthValue(C);
7144 unsigned Bits2 = Field2->getBitWidthValue(C);
7145
7146 if (Bits1 != Bits2)
7147 return false;
7148 }
7149
7150 return true;
7151}
7152
7153/// \brief Check if two standard-layout structs are layout-compatible.
7154/// (C++11 [class.mem] p17)
7155bool isLayoutCompatibleStruct(ASTContext &C,
7156 RecordDecl *RD1,
7157 RecordDecl *RD2) {
7158 // If both records are C++ classes, check that base classes match.
7159 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7160 // If one of records is a CXXRecordDecl we are in C++ mode,
7161 // thus the other one is a CXXRecordDecl, too.
7162 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7163 // Check number of base classes.
7164 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7165 return false;
7166
7167 // Check the base classes.
7168 for (CXXRecordDecl::base_class_const_iterator
7169 Base1 = D1CXX->bases_begin(),
7170 BaseEnd1 = D1CXX->bases_end(),
7171 Base2 = D2CXX->bases_begin();
7172 Base1 != BaseEnd1;
7173 ++Base1, ++Base2) {
7174 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7175 return false;
7176 }
7177 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7178 // If only RD2 is a C++ class, it should have zero base classes.
7179 if (D2CXX->getNumBases() > 0)
7180 return false;
7181 }
7182
7183 // Check the fields.
7184 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7185 Field2End = RD2->field_end(),
7186 Field1 = RD1->field_begin(),
7187 Field1End = RD1->field_end();
7188 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7189 if (!isLayoutCompatible(C, *Field1, *Field2))
7190 return false;
7191 }
7192 if (Field1 != Field1End || Field2 != Field2End)
7193 return false;
7194
7195 return true;
7196}
7197
7198/// \brief Check if two standard-layout unions are layout-compatible.
7199/// (C++11 [class.mem] p18)
7200bool isLayoutCompatibleUnion(ASTContext &C,
7201 RecordDecl *RD1,
7202 RecordDecl *RD2) {
7203 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7204 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7205 Field2End = RD2->field_end();
7206 Field2 != Field2End; ++Field2) {
7207 UnmatchedFields.insert(*Field2);
7208 }
7209
7210 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7211 Field1End = RD1->field_end();
7212 Field1 != Field1End; ++Field1) {
7213 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7214 I = UnmatchedFields.begin(),
7215 E = UnmatchedFields.end();
7216
7217 for ( ; I != E; ++I) {
7218 if (isLayoutCompatible(C, *Field1, *I)) {
7219 bool Result = UnmatchedFields.erase(*I);
7220 (void) Result;
7221 assert(Result);
7222 break;
7223 }
7224 }
7225 if (I == E)
7226 return false;
7227 }
7228
7229 return UnmatchedFields.empty();
7230}
7231
7232bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7233 if (RD1->isUnion() != RD2->isUnion())
7234 return false;
7235
7236 if (RD1->isUnion())
7237 return isLayoutCompatibleUnion(C, RD1, RD2);
7238 else
7239 return isLayoutCompatibleStruct(C, RD1, RD2);
7240}
7241
7242/// \brief Check if two types are layout-compatible in C++11 sense.
7243bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7244 if (T1.isNull() || T2.isNull())
7245 return false;
7246
7247 // C++11 [basic.types] p11:
7248 // If two types T1 and T2 are the same type, then T1 and T2 are
7249 // layout-compatible types.
7250 if (C.hasSameType(T1, T2))
7251 return true;
7252
7253 T1 = T1.getCanonicalType().getUnqualifiedType();
7254 T2 = T2.getCanonicalType().getUnqualifiedType();
7255
7256 const Type::TypeClass TC1 = T1->getTypeClass();
7257 const Type::TypeClass TC2 = T2->getTypeClass();
7258
7259 if (TC1 != TC2)
7260 return false;
7261
7262 if (TC1 == Type::Enum) {
7263 return isLayoutCompatible(C,
7264 cast<EnumType>(T1)->getDecl(),
7265 cast<EnumType>(T2)->getDecl());
7266 } else if (TC1 == Type::Record) {
7267 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7268 return false;
7269
7270 return isLayoutCompatible(C,
7271 cast<RecordType>(T1)->getDecl(),
7272 cast<RecordType>(T2)->getDecl());
7273 }
7274
7275 return false;
7276}
7277}
7278
7279//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7280
7281namespace {
7282/// \brief Given a type tag expression find the type tag itself.
7283///
7284/// \param TypeExpr Type tag expression, as it appears in user's code.
7285///
7286/// \param VD Declaration of an identifier that appears in a type tag.
7287///
7288/// \param MagicValue Type tag magic value.
7289bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7290 const ValueDecl **VD, uint64_t *MagicValue) {
7291 while(true) {
7292 if (!TypeExpr)
7293 return false;
7294
7295 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7296
7297 switch (TypeExpr->getStmtClass()) {
7298 case Stmt::UnaryOperatorClass: {
7299 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7300 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7301 TypeExpr = UO->getSubExpr();
7302 continue;
7303 }
7304 return false;
7305 }
7306
7307 case Stmt::DeclRefExprClass: {
7308 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7309 *VD = DRE->getDecl();
7310 return true;
7311 }
7312
7313 case Stmt::IntegerLiteralClass: {
7314 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7315 llvm::APInt MagicValueAPInt = IL->getValue();
7316 if (MagicValueAPInt.getActiveBits() <= 64) {
7317 *MagicValue = MagicValueAPInt.getZExtValue();
7318 return true;
7319 } else
7320 return false;
7321 }
7322
7323 case Stmt::BinaryConditionalOperatorClass:
7324 case Stmt::ConditionalOperatorClass: {
7325 const AbstractConditionalOperator *ACO =
7326 cast<AbstractConditionalOperator>(TypeExpr);
7327 bool Result;
7328 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7329 if (Result)
7330 TypeExpr = ACO->getTrueExpr();
7331 else
7332 TypeExpr = ACO->getFalseExpr();
7333 continue;
7334 }
7335 return false;
7336 }
7337
7338 case Stmt::BinaryOperatorClass: {
7339 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7340 if (BO->getOpcode() == BO_Comma) {
7341 TypeExpr = BO->getRHS();
7342 continue;
7343 }
7344 return false;
7345 }
7346
7347 default:
7348 return false;
7349 }
7350 }
7351}
7352
7353/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7354///
7355/// \param TypeExpr Expression that specifies a type tag.
7356///
7357/// \param MagicValues Registered magic values.
7358///
7359/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7360/// kind.
7361///
7362/// \param TypeInfo Information about the corresponding C type.
7363///
7364/// \returns true if the corresponding C type was found.
7365bool GetMatchingCType(
7366 const IdentifierInfo *ArgumentKind,
7367 const Expr *TypeExpr, const ASTContext &Ctx,
7368 const llvm::DenseMap<Sema::TypeTagMagicValue,
7369 Sema::TypeTagData> *MagicValues,
7370 bool &FoundWrongKind,
7371 Sema::TypeTagData &TypeInfo) {
7372 FoundWrongKind = false;
7373
7374 // Variable declaration that has type_tag_for_datatype attribute.
7375 const ValueDecl *VD = NULL;
7376
7377 uint64_t MagicValue;
7378
7379 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7380 return false;
7381
7382 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00007383 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007384 if (I->getArgumentKind() != ArgumentKind) {
7385 FoundWrongKind = true;
7386 return false;
7387 }
7388 TypeInfo.Type = I->getMatchingCType();
7389 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7390 TypeInfo.MustBeNull = I->getMustBeNull();
7391 return true;
7392 }
7393 return false;
7394 }
7395
7396 if (!MagicValues)
7397 return false;
7398
7399 llvm::DenseMap<Sema::TypeTagMagicValue,
7400 Sema::TypeTagData>::const_iterator I =
7401 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7402 if (I == MagicValues->end())
7403 return false;
7404
7405 TypeInfo = I->second;
7406 return true;
7407}
7408} // unnamed namespace
7409
7410void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7411 uint64_t MagicValue, QualType Type,
7412 bool LayoutCompatible,
7413 bool MustBeNull) {
7414 if (!TypeTagForDatatypeMagicValues)
7415 TypeTagForDatatypeMagicValues.reset(
7416 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7417
7418 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7419 (*TypeTagForDatatypeMagicValues)[Magic] =
7420 TypeTagData(Type, LayoutCompatible, MustBeNull);
7421}
7422
7423namespace {
7424bool IsSameCharType(QualType T1, QualType T2) {
7425 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7426 if (!BT1)
7427 return false;
7428
7429 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7430 if (!BT2)
7431 return false;
7432
7433 BuiltinType::Kind T1Kind = BT1->getKind();
7434 BuiltinType::Kind T2Kind = BT2->getKind();
7435
7436 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7437 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7438 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7439 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7440}
7441} // unnamed namespace
7442
7443void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7444 const Expr * const *ExprArgs) {
7445 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7446 bool IsPointerAttr = Attr->getIsPointer();
7447
7448 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7449 bool FoundWrongKind;
7450 TypeTagData TypeInfo;
7451 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7452 TypeTagForDatatypeMagicValues.get(),
7453 FoundWrongKind, TypeInfo)) {
7454 if (FoundWrongKind)
7455 Diag(TypeTagExpr->getExprLoc(),
7456 diag::warn_type_tag_for_datatype_wrong_kind)
7457 << TypeTagExpr->getSourceRange();
7458 return;
7459 }
7460
7461 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7462 if (IsPointerAttr) {
7463 // Skip implicit cast of pointer to `void *' (as a function argument).
7464 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007465 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007466 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007467 ArgumentExpr = ICE->getSubExpr();
7468 }
7469 QualType ArgumentType = ArgumentExpr->getType();
7470
7471 // Passing a `void*' pointer shouldn't trigger a warning.
7472 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7473 return;
7474
7475 if (TypeInfo.MustBeNull) {
7476 // Type tag with matching void type requires a null pointer.
7477 if (!ArgumentExpr->isNullPointerConstant(Context,
7478 Expr::NPC_ValueDependentIsNotNull)) {
7479 Diag(ArgumentExpr->getExprLoc(),
7480 diag::warn_type_safety_null_pointer_required)
7481 << ArgumentKind->getName()
7482 << ArgumentExpr->getSourceRange()
7483 << TypeTagExpr->getSourceRange();
7484 }
7485 return;
7486 }
7487
7488 QualType RequiredType = TypeInfo.Type;
7489 if (IsPointerAttr)
7490 RequiredType = Context.getPointerType(RequiredType);
7491
7492 bool mismatch = false;
7493 if (!TypeInfo.LayoutCompatible) {
7494 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7495
7496 // C++11 [basic.fundamental] p1:
7497 // Plain char, signed char, and unsigned char are three distinct types.
7498 //
7499 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7500 // char' depending on the current char signedness mode.
7501 if (mismatch)
7502 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7503 RequiredType->getPointeeType())) ||
7504 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7505 mismatch = false;
7506 } else
7507 if (IsPointerAttr)
7508 mismatch = !isLayoutCompatible(Context,
7509 ArgumentType->getPointeeType(),
7510 RequiredType->getPointeeType());
7511 else
7512 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7513
7514 if (mismatch)
7515 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00007516 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007517 << TypeInfo.LayoutCompatible << RequiredType
7518 << ArgumentExpr->getSourceRange()
7519 << TypeTagExpr->getSourceRange();
7520}