blob: 32bf6e01c9f0a9b4695baf0eff25101d8186287a [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:
Reid Kleckner597e81d2014-03-26 15:38:33 +0000145 case Builtin::BI__va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000146 if (SemaBuiltinVAStart(TheCall))
147 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000148 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000149 case Builtin::BI__builtin_isgreater:
150 case Builtin::BI__builtin_isgreaterequal:
151 case Builtin::BI__builtin_isless:
152 case Builtin::BI__builtin_islessequal:
153 case Builtin::BI__builtin_islessgreater:
154 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000155 if (SemaBuiltinUnorderedCompare(TheCall))
156 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000157 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000158 case Builtin::BI__builtin_fpclassify:
159 if (SemaBuiltinFPClassification(TheCall, 6))
160 return ExprError();
161 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000162 case Builtin::BI__builtin_isfinite:
163 case Builtin::BI__builtin_isinf:
164 case Builtin::BI__builtin_isinf_sign:
165 case Builtin::BI__builtin_isnan:
166 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000167 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000168 return ExprError();
169 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000170 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000171 return SemaBuiltinShuffleVector(TheCall);
172 // TheCall will be freed by the smart pointer here, but that's fine, since
173 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000174 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000175 if (SemaBuiltinPrefetch(TheCall))
176 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000177 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000178 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000179 if (SemaBuiltinObjectSize(TheCall))
180 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000181 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000182 case Builtin::BI__builtin_longjmp:
183 if (SemaBuiltinLongjmp(TheCall))
184 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000185 break;
John McCallbebede42011-02-26 05:39:39 +0000186
187 case Builtin::BI__builtin_classify_type:
188 if (checkArgCount(*this, TheCall, 1)) return true;
189 TheCall->setType(Context.IntTy);
190 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000191 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000192 if (checkArgCount(*this, TheCall, 1)) return true;
193 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000194 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000195 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000196 case Builtin::BI__sync_fetch_and_add_1:
197 case Builtin::BI__sync_fetch_and_add_2:
198 case Builtin::BI__sync_fetch_and_add_4:
199 case Builtin::BI__sync_fetch_and_add_8:
200 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000201 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000202 case Builtin::BI__sync_fetch_and_sub_1:
203 case Builtin::BI__sync_fetch_and_sub_2:
204 case Builtin::BI__sync_fetch_and_sub_4:
205 case Builtin::BI__sync_fetch_and_sub_8:
206 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000207 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000208 case Builtin::BI__sync_fetch_and_or_1:
209 case Builtin::BI__sync_fetch_and_or_2:
210 case Builtin::BI__sync_fetch_and_or_4:
211 case Builtin::BI__sync_fetch_and_or_8:
212 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000213 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000214 case Builtin::BI__sync_fetch_and_and_1:
215 case Builtin::BI__sync_fetch_and_and_2:
216 case Builtin::BI__sync_fetch_and_and_4:
217 case Builtin::BI__sync_fetch_and_and_8:
218 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000219 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000220 case Builtin::BI__sync_fetch_and_xor_1:
221 case Builtin::BI__sync_fetch_and_xor_2:
222 case Builtin::BI__sync_fetch_and_xor_4:
223 case Builtin::BI__sync_fetch_and_xor_8:
224 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000225 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000226 case Builtin::BI__sync_add_and_fetch_1:
227 case Builtin::BI__sync_add_and_fetch_2:
228 case Builtin::BI__sync_add_and_fetch_4:
229 case Builtin::BI__sync_add_and_fetch_8:
230 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000231 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000232 case Builtin::BI__sync_sub_and_fetch_1:
233 case Builtin::BI__sync_sub_and_fetch_2:
234 case Builtin::BI__sync_sub_and_fetch_4:
235 case Builtin::BI__sync_sub_and_fetch_8:
236 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000237 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000238 case Builtin::BI__sync_and_and_fetch_1:
239 case Builtin::BI__sync_and_and_fetch_2:
240 case Builtin::BI__sync_and_and_fetch_4:
241 case Builtin::BI__sync_and_and_fetch_8:
242 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000243 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000244 case Builtin::BI__sync_or_and_fetch_1:
245 case Builtin::BI__sync_or_and_fetch_2:
246 case Builtin::BI__sync_or_and_fetch_4:
247 case Builtin::BI__sync_or_and_fetch_8:
248 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000249 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000250 case Builtin::BI__sync_xor_and_fetch_1:
251 case Builtin::BI__sync_xor_and_fetch_2:
252 case Builtin::BI__sync_xor_and_fetch_4:
253 case Builtin::BI__sync_xor_and_fetch_8:
254 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000255 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000256 case Builtin::BI__sync_val_compare_and_swap_1:
257 case Builtin::BI__sync_val_compare_and_swap_2:
258 case Builtin::BI__sync_val_compare_and_swap_4:
259 case Builtin::BI__sync_val_compare_and_swap_8:
260 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000261 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000262 case Builtin::BI__sync_bool_compare_and_swap_1:
263 case Builtin::BI__sync_bool_compare_and_swap_2:
264 case Builtin::BI__sync_bool_compare_and_swap_4:
265 case Builtin::BI__sync_bool_compare_and_swap_8:
266 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000267 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000268 case Builtin::BI__sync_lock_test_and_set_1:
269 case Builtin::BI__sync_lock_test_and_set_2:
270 case Builtin::BI__sync_lock_test_and_set_4:
271 case Builtin::BI__sync_lock_test_and_set_8:
272 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000273 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000274 case Builtin::BI__sync_lock_release_1:
275 case Builtin::BI__sync_lock_release_2:
276 case Builtin::BI__sync_lock_release_4:
277 case Builtin::BI__sync_lock_release_8:
278 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000279 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000280 case Builtin::BI__sync_swap_1:
281 case Builtin::BI__sync_swap_2:
282 case Builtin::BI__sync_swap_4:
283 case Builtin::BI__sync_swap_8:
284 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000285 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000286#define BUILTIN(ID, TYPE, ATTRS)
287#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
288 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000289 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000290#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000291 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000292 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000293 return ExprError();
294 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000295 case Builtin::BI__builtin_addressof:
296 if (SemaBuiltinAddressof(*this, TheCall))
297 return ExprError();
298 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000299 }
300
301 // Since the target specific builtins for each arch overlap, only check those
302 // of the arch we are compiling for.
303 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000304 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000305 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000306 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000307 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000308 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000309 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
310 return ExprError();
311 break;
Tim Northover2fe823a2013-08-01 09:23:19 +0000312 case llvm::Triple::aarch64:
Christian Pirker9b019ae2014-02-25 13:51:00 +0000313 case llvm::Triple::aarch64_be:
Tim Northover2fe823a2013-08-01 09:23:19 +0000314 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
315 return ExprError();
316 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000317 case llvm::Triple::mips:
318 case llvm::Triple::mipsel:
319 case llvm::Triple::mips64:
320 case llvm::Triple::mips64el:
321 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
322 return ExprError();
323 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000324 case llvm::Triple::x86:
325 case llvm::Triple::x86_64:
326 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
327 return ExprError();
328 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000329 default:
330 break;
331 }
332 }
333
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000334 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000335}
336
Nate Begeman91e1fea2010-06-14 05:21:25 +0000337// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000338static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000339 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000340 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000341 switch (Type.getEltType()) {
342 case NeonTypeFlags::Int8:
343 case NeonTypeFlags::Poly8:
344 return shift ? 7 : (8 << IsQuad) - 1;
345 case NeonTypeFlags::Int16:
346 case NeonTypeFlags::Poly16:
347 return shift ? 15 : (4 << IsQuad) - 1;
348 case NeonTypeFlags::Int32:
349 return shift ? 31 : (2 << IsQuad) - 1;
350 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000351 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000352 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000353 case NeonTypeFlags::Poly128:
354 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000355 case NeonTypeFlags::Float16:
356 assert(!shift && "cannot shift float types!");
357 return (4 << IsQuad) - 1;
358 case NeonTypeFlags::Float32:
359 assert(!shift && "cannot shift float types!");
360 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000361 case NeonTypeFlags::Float64:
362 assert(!shift && "cannot shift float types!");
363 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000364 }
David Blaikie8a40f702012-01-17 06:56:22 +0000365 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000366}
367
Bob Wilsone4d77232011-11-08 05:04:11 +0000368/// getNeonEltType - Return the QualType corresponding to the elements of
369/// the vector type specified by the NeonTypeFlags. This is used to check
370/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000371static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
372 bool IsAArch64) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000373 switch (Flags.getEltType()) {
374 case NeonTypeFlags::Int8:
375 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
376 case NeonTypeFlags::Int16:
377 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
378 case NeonTypeFlags::Int32:
379 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
380 case NeonTypeFlags::Int64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000381 if (IsAArch64)
382 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
383 else
384 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
385 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000386 case NeonTypeFlags::Poly8:
Kevin Qincaac85e2013-11-14 03:29:16 +0000387 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000388 case NeonTypeFlags::Poly16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000389 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
390 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000391 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000392 case NeonTypeFlags::Poly128:
393 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000394 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000395 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000396 case NeonTypeFlags::Float32:
397 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000398 case NeonTypeFlags::Float64:
399 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000400 }
David Blaikie8a40f702012-01-17 06:56:22 +0000401 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000402}
403
Tim Northover12670412014-02-19 10:37:05 +0000404bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000405 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000406 uint64_t mask = 0;
407 unsigned TV = 0;
408 int PtrArgNum = -1;
409 bool HasConstPtr = false;
410 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000411#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000412#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000413#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000414 }
415
416 // For NEON intrinsics which are overloaded on vector element type, validate
417 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000418 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000419 if (mask) {
420 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
421 return true;
422
423 TV = Result.getLimitedValue(64);
424 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
425 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000426 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000427 }
428
429 if (PtrArgNum >= 0) {
430 // Check that pointer arguments have the specified type.
431 Expr *Arg = TheCall->getArg(PtrArgNum);
432 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
433 Arg = ICE->getSubExpr();
434 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
435 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000436
437 bool IsAArch64 =
438 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::aarch64;
439 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, IsAArch64);
Tim Northover2fe823a2013-08-01 09:23:19 +0000440 if (HasConstPtr)
441 EltTy = EltTy.withConst();
442 QualType LHSTy = Context.getPointerType(EltTy);
443 AssignConvertType ConvTy;
444 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
445 if (RHS.isInvalid())
446 return true;
447 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
448 RHS.get(), AA_Assigning))
449 return true;
450 }
451
452 // For NEON intrinsics which take an immediate value as part of the
453 // instruction, range check them here.
454 unsigned i = 0, l = 0, u = 0;
455 switch (BuiltinID) {
456 default:
457 return false;
Tim Northover12670412014-02-19 10:37:05 +0000458#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000459#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000460#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000461 }
462 ;
463
464 // We can't check the value of a dependent argument.
465 if (TheCall->getArg(i)->isTypeDependent() ||
466 TheCall->getArg(i)->isValueDependent())
467 return false;
468
469 // Check that the immediate argument is actually a constant.
470 if (SemaBuiltinConstantArg(TheCall, i, Result))
471 return true;
472
473 // Range check against the upper/lower values for this isntruction.
474 unsigned Val = Result.getZExtValue();
475 if (Val < l || Val > (u + l))
476 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
477 << l << u + l << TheCall->getArg(i)->getSourceRange();
478
479 return false;
480}
481
Tim Northover12670412014-02-19 10:37:05 +0000482bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
483 CallExpr *TheCall) {
484 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
485 return true;
486
487 return false;
488}
489
Tim Northover6aacd492013-07-16 09:47:53 +0000490bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
491 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
492 BuiltinID == ARM::BI__builtin_arm_strex) &&
493 "unexpected ARM builtin");
494 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
495
496 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
497
498 // Ensure that we have the proper number of arguments.
499 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
500 return true;
501
502 // Inspect the pointer argument of the atomic builtin. This should always be
503 // a pointer type, whose element is an integral scalar or pointer type.
504 // Because it is a pointer type, we don't have to worry about any implicit
505 // casts here.
506 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
507 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
508 if (PointerArgRes.isInvalid())
509 return true;
510 PointerArg = PointerArgRes.take();
511
512 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
513 if (!pointerType) {
514 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
515 << PointerArg->getType() << PointerArg->getSourceRange();
516 return true;
517 }
518
519 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
520 // task is to insert the appropriate casts into the AST. First work out just
521 // what the appropriate type is.
522 QualType ValType = pointerType->getPointeeType();
523 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
524 if (IsLdrex)
525 AddrType.addConst();
526
527 // Issue a warning if the cast is dodgy.
528 CastKind CastNeeded = CK_NoOp;
529 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
530 CastNeeded = CK_BitCast;
531 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
532 << PointerArg->getType()
533 << Context.getPointerType(AddrType)
534 << AA_Passing << PointerArg->getSourceRange();
535 }
536
537 // Finally, do the cast and replace the argument with the corrected version.
538 AddrType = Context.getPointerType(AddrType);
539 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
540 if (PointerArgRes.isInvalid())
541 return true;
542 PointerArg = PointerArgRes.take();
543
544 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
545
546 // In general, we allow ints, floats and pointers to be loaded and stored.
547 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
548 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
549 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
550 << PointerArg->getType() << PointerArg->getSourceRange();
551 return true;
552 }
553
554 // But ARM doesn't have instructions to deal with 128-bit versions.
555 if (Context.getTypeSize(ValType) > 64) {
556 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
557 << PointerArg->getType() << PointerArg->getSourceRange();
558 return true;
559 }
560
561 switch (ValType.getObjCLifetime()) {
562 case Qualifiers::OCL_None:
563 case Qualifiers::OCL_ExplicitNone:
564 // okay
565 break;
566
567 case Qualifiers::OCL_Weak:
568 case Qualifiers::OCL_Strong:
569 case Qualifiers::OCL_Autoreleasing:
570 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
571 << ValType << PointerArg->getSourceRange();
572 return true;
573 }
574
575
576 if (IsLdrex) {
577 TheCall->setType(ValType);
578 return false;
579 }
580
581 // Initialize the argument to be stored.
582 ExprResult ValArg = TheCall->getArg(0);
583 InitializedEntity Entity = InitializedEntity::InitializeParameter(
584 Context, ValType, /*consume*/ false);
585 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
586 if (ValArg.isInvalid())
587 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000588 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000589
590 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
591 // but the custom checker bypasses all default analysis.
592 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000593 return false;
594}
595
Nate Begeman4904e322010-06-08 02:47:44 +0000596bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000597 llvm::APSInt Result;
598
Tim Northover6aacd492013-07-16 09:47:53 +0000599 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
600 BuiltinID == ARM::BI__builtin_arm_strex) {
601 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
602 }
603
Tim Northover12670412014-02-19 10:37:05 +0000604 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
605 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000606
Bob Wilsond836d3d2014-03-09 23:02:27 +0000607 // For NEON intrinsics which take an immediate value as part of the
Nate Begemand773fe62010-06-13 04:47:52 +0000608 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000609 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000610 switch (BuiltinID) {
611 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000612 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
613 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000614 case ARM::BI__builtin_arm_vcvtr_f:
615 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000616 case ARM::BI__builtin_arm_dmb:
617 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begemand773fe62010-06-13 04:47:52 +0000618 };
619
Douglas Gregor98c3cfc2012-06-29 01:05:22 +0000620 // We can't check the value of a dependent argument.
621 if (TheCall->getArg(i)->isTypeDependent() ||
622 TheCall->getArg(i)->isValueDependent())
623 return false;
624
Nate Begeman91e1fea2010-06-14 05:21:25 +0000625 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000626 if (SemaBuiltinConstantArg(TheCall, i, Result))
627 return true;
628
Nate Begeman91e1fea2010-06-14 05:21:25 +0000629 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000630 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000631 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000632 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000633 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000634
Nate Begemanf568b072010-08-03 21:32:34 +0000635 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000636 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000637}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000638
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000639bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
640 unsigned i = 0, l = 0, u = 0;
641 switch (BuiltinID) {
642 default: return false;
643 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
644 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000645 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
646 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
647 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
648 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
649 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000650 };
651
652 // We can't check the value of a dependent argument.
653 if (TheCall->getArg(i)->isTypeDependent() ||
654 TheCall->getArg(i)->isValueDependent())
655 return false;
656
657 // Check that the immediate argument is actually a constant.
658 llvm::APSInt Result;
659 if (SemaBuiltinConstantArg(TheCall, i, Result))
660 return true;
661
662 // Range check against the upper/lower values for this instruction.
663 unsigned Val = Result.getZExtValue();
664 if (Val < l || Val > u)
665 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
666 << l << u << TheCall->getArg(i)->getSourceRange();
667
668 return false;
669}
670
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000671bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
672 switch (BuiltinID) {
673 case X86::BI_mm_prefetch:
674 return SemaBuiltinMMPrefetch(TheCall);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000675 }
676 return false;
677}
678
Richard Smith55ce3522012-06-25 20:30:08 +0000679/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
680/// parameter with the FormatAttr's correct format_idx and firstDataArg.
681/// Returns true when the format fits the function and the FormatStringInfo has
682/// been populated.
683bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
684 FormatStringInfo *FSI) {
685 FSI->HasVAListArg = Format->getFirstArg() == 0;
686 FSI->FormatIdx = Format->getFormatIdx() - 1;
687 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000688
Richard Smith55ce3522012-06-25 20:30:08 +0000689 // The way the format attribute works in GCC, the implicit this argument
690 // of member functions is counted. However, it doesn't appear in our own
691 // lists, so decrement format_idx in that case.
692 if (IsCXXMember) {
693 if(FSI->FormatIdx == 0)
694 return false;
695 --FSI->FormatIdx;
696 if (FSI->FirstDataArg != 0)
697 --FSI->FirstDataArg;
698 }
699 return true;
700}
Mike Stump11289f42009-09-09 15:08:12 +0000701
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000702/// Checks if a the given expression evaluates to null.
703///
704/// \brief Returns true if the value evaluates to null.
705static bool CheckNonNullExpr(Sema &S,
706 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000707 // As a special case, transparent unions initialized with zero are
708 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000709 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000710 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
711 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000712 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000713 if (const InitListExpr *ILE =
714 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000715 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000716 }
717
718 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000719 return (!Expr->isValueDependent() &&
720 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
721 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000722}
723
724static void CheckNonNullArgument(Sema &S,
725 const Expr *ArgExpr,
726 SourceLocation CallSiteLoc) {
727 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000728 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
729}
730
Ted Kremenek2bc73332014-01-17 06:24:43 +0000731static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000732 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000733 const Expr * const *ExprArgs,
734 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000735 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000736 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000737 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
738 e = NonNull->args_end();
739 i != e; ++i) {
740 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000741 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000742 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000743
744 // Check the attributes on the parameters.
745 ArrayRef<ParmVarDecl*> parms;
746 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
747 parms = FD->parameters();
748 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
749 parms = MD->parameters();
750
751 unsigned argIndex = 0;
752 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
753 I != E; ++I, ++argIndex) {
754 const ParmVarDecl *PVD = *I;
755 if (PVD->hasAttr<NonNullAttr>())
756 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
757 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000758}
759
Richard Smith55ce3522012-06-25 20:30:08 +0000760/// Handles the checks for format strings, non-POD arguments to vararg
761/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000762void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
763 unsigned NumParams, bool IsMemberFunction,
764 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000765 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000766 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000767 if (CurContext->isDependentContext())
768 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000769
Ted Kremenekb8176da2010-09-09 04:33:05 +0000770 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000771 llvm::SmallBitVector CheckedVarArgs;
772 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000773 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000774 // Only create vector if there are format attributes.
775 CheckedVarArgs.resize(Args.size());
776
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000777 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000778 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000779 }
Richard Smithd7293d72013-08-05 18:49:43 +0000780 }
Richard Smith55ce3522012-06-25 20:30:08 +0000781
782 // Refuse POD arguments that weren't caught by the format string
783 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000784 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000785 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000786 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000787 if (const Expr *Arg = Args[ArgIdx]) {
788 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
789 checkVariadicArgument(Arg, CallType);
790 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000791 }
Richard Smithd7293d72013-08-05 18:49:43 +0000792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
Richard Trieu41bc0992013-06-22 00:20:41 +0000794 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000795 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000796
Richard Trieu41bc0992013-06-22 00:20:41 +0000797 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000798 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
799 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000800 }
Richard Smith55ce3522012-06-25 20:30:08 +0000801}
802
803/// CheckConstructorCall - Check a constructor call for correctness and safety
804/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000805void Sema::CheckConstructorCall(FunctionDecl *FDecl,
806 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000807 const FunctionProtoType *Proto,
808 SourceLocation Loc) {
809 VariadicCallType CallType =
810 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000811 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000812 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
813}
814
815/// CheckFunctionCall - Check a direct function call for various correctness
816/// and safety properties not strictly enforced by the C type system.
817bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
818 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000819 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
820 isa<CXXMethodDecl>(FDecl);
821 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
822 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000823 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
824 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000825 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000826 Expr** Args = TheCall->getArgs();
827 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000828 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000829 // If this is a call to a member operator, hide the first argument
830 // from checkCall.
831 // FIXME: Our choice of AST representation here is less than ideal.
832 ++Args;
833 --NumArgs;
834 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000835 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000836 IsMemberFunction, TheCall->getRParenLoc(),
837 TheCall->getCallee()->getSourceRange(), CallType);
838
839 IdentifierInfo *FnInfo = FDecl->getIdentifier();
840 // None of the checks below are needed for functions that don't have
841 // simple names (e.g., C++ conversion functions).
842 if (!FnInfo)
843 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000844
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000845 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
846
Anna Zaks22122702012-01-17 00:37:07 +0000847 unsigned CMId = FDecl->getMemoryFunctionKind();
848 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000849 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000850
Anna Zaks201d4892012-01-13 21:52:01 +0000851 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000852 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000853 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000854 else if (CMId == Builtin::BIstrncat)
855 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000856 else
Anna Zaks22122702012-01-17 00:37:07 +0000857 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000858
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000859 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000860}
861
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000862bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000863 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000864 VariadicCallType CallType =
865 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000866
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000867 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000868 /*IsMemberFunction=*/false,
869 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000870
871 return false;
872}
873
Richard Trieu664c4c62013-06-20 21:03:13 +0000874bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
875 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000876 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
877 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000878 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000879
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000880 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000881 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000882 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000883
Richard Trieu664c4c62013-06-20 21:03:13 +0000884 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000885 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000886 CallType = VariadicDoesNotApply;
887 } else if (Ty->isBlockPointerType()) {
888 CallType = VariadicBlock;
889 } else { // Ty->isFunctionPointerType()
890 CallType = VariadicFunction;
891 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000892 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000893
Alp Toker9cacbab2014-01-20 20:26:09 +0000894 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
895 TheCall->getNumArgs()),
896 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000897 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000898
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000899 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000900}
901
Richard Trieu41bc0992013-06-22 00:20:41 +0000902/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
903/// such as function pointers returned from functions.
904bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
905 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
906 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000907 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000908
Alp Toker9cacbab2014-01-20 20:26:09 +0000909 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
910 TheCall->getArgs(), TheCall->getNumArgs()),
911 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000912 TheCall->getCallee()->getSourceRange(), CallType);
913
914 return false;
915}
916
Tim Northovere94a34c2014-03-11 10:49:14 +0000917static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
918 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
919 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
920 return false;
921
922 switch (Op) {
923 case AtomicExpr::AO__c11_atomic_init:
924 llvm_unreachable("There is no ordering argument for an init");
925
926 case AtomicExpr::AO__c11_atomic_load:
927 case AtomicExpr::AO__atomic_load_n:
928 case AtomicExpr::AO__atomic_load:
929 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
930 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
931
932 case AtomicExpr::AO__c11_atomic_store:
933 case AtomicExpr::AO__atomic_store:
934 case AtomicExpr::AO__atomic_store_n:
935 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
936 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
937 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
938
939 default:
940 return true;
941 }
942}
943
Richard Smithfeea8832012-04-12 05:08:17 +0000944ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
945 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000946 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
947 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000948
Richard Smithfeea8832012-04-12 05:08:17 +0000949 // All these operations take one of the following forms:
950 enum {
951 // C __c11_atomic_init(A *, C)
952 Init,
953 // C __c11_atomic_load(A *, int)
954 Load,
955 // void __atomic_load(A *, CP, int)
956 Copy,
957 // C __c11_atomic_add(A *, M, int)
958 Arithmetic,
959 // C __atomic_exchange_n(A *, CP, int)
960 Xchg,
961 // void __atomic_exchange(A *, C *, CP, int)
962 GNUXchg,
963 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
964 C11CmpXchg,
965 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
966 GNUCmpXchg
967 } Form = Init;
968 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
969 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
970 // where:
971 // C is an appropriate type,
972 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
973 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
974 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
975 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000976
Richard Smithfeea8832012-04-12 05:08:17 +0000977 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
978 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
979 && "need to update code for modified C11 atomics");
980 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
981 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
982 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
983 Op == AtomicExpr::AO__atomic_store_n ||
984 Op == AtomicExpr::AO__atomic_exchange_n ||
985 Op == AtomicExpr::AO__atomic_compare_exchange_n;
986 bool IsAddSub = false;
987
988 switch (Op) {
989 case AtomicExpr::AO__c11_atomic_init:
990 Form = Init;
991 break;
992
993 case AtomicExpr::AO__c11_atomic_load:
994 case AtomicExpr::AO__atomic_load_n:
995 Form = Load;
996 break;
997
998 case AtomicExpr::AO__c11_atomic_store:
999 case AtomicExpr::AO__atomic_load:
1000 case AtomicExpr::AO__atomic_store:
1001 case AtomicExpr::AO__atomic_store_n:
1002 Form = Copy;
1003 break;
1004
1005 case AtomicExpr::AO__c11_atomic_fetch_add:
1006 case AtomicExpr::AO__c11_atomic_fetch_sub:
1007 case AtomicExpr::AO__atomic_fetch_add:
1008 case AtomicExpr::AO__atomic_fetch_sub:
1009 case AtomicExpr::AO__atomic_add_fetch:
1010 case AtomicExpr::AO__atomic_sub_fetch:
1011 IsAddSub = true;
1012 // Fall through.
1013 case AtomicExpr::AO__c11_atomic_fetch_and:
1014 case AtomicExpr::AO__c11_atomic_fetch_or:
1015 case AtomicExpr::AO__c11_atomic_fetch_xor:
1016 case AtomicExpr::AO__atomic_fetch_and:
1017 case AtomicExpr::AO__atomic_fetch_or:
1018 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001019 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001020 case AtomicExpr::AO__atomic_and_fetch:
1021 case AtomicExpr::AO__atomic_or_fetch:
1022 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001023 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001024 Form = Arithmetic;
1025 break;
1026
1027 case AtomicExpr::AO__c11_atomic_exchange:
1028 case AtomicExpr::AO__atomic_exchange_n:
1029 Form = Xchg;
1030 break;
1031
1032 case AtomicExpr::AO__atomic_exchange:
1033 Form = GNUXchg;
1034 break;
1035
1036 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1037 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1038 Form = C11CmpXchg;
1039 break;
1040
1041 case AtomicExpr::AO__atomic_compare_exchange:
1042 case AtomicExpr::AO__atomic_compare_exchange_n:
1043 Form = GNUCmpXchg;
1044 break;
1045 }
1046
1047 // Check we have the right number of arguments.
1048 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001049 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001050 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001051 << TheCall->getCallee()->getSourceRange();
1052 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001053 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1054 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001055 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001056 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001057 << TheCall->getCallee()->getSourceRange();
1058 return ExprError();
1059 }
1060
Richard Smithfeea8832012-04-12 05:08:17 +00001061 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001062 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001063 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1064 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1065 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001066 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001067 << Ptr->getType() << Ptr->getSourceRange();
1068 return ExprError();
1069 }
1070
Richard Smithfeea8832012-04-12 05:08:17 +00001071 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1072 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1073 QualType ValType = AtomTy; // 'C'
1074 if (IsC11) {
1075 if (!AtomTy->isAtomicType()) {
1076 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1077 << Ptr->getType() << Ptr->getSourceRange();
1078 return ExprError();
1079 }
Richard Smithe00921a2012-09-15 06:09:58 +00001080 if (AtomTy.isConstQualified()) {
1081 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1082 << Ptr->getType() << Ptr->getSourceRange();
1083 return ExprError();
1084 }
Richard Smithfeea8832012-04-12 05:08:17 +00001085 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001086 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001087
Richard Smithfeea8832012-04-12 05:08:17 +00001088 // For an arithmetic operation, the implied arithmetic must be well-formed.
1089 if (Form == Arithmetic) {
1090 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1091 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1092 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1093 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1094 return ExprError();
1095 }
1096 if (!IsAddSub && !ValType->isIntegerType()) {
1097 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1098 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1099 return ExprError();
1100 }
1101 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1102 // For __atomic_*_n operations, the value type must be a scalar integral or
1103 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001104 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001105 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1106 return ExprError();
1107 }
1108
Eli Friedmanaa769812013-09-11 03:49:34 +00001109 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1110 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001111 // For GNU atomics, require a trivially-copyable type. This is not part of
1112 // the GNU atomics specification, but we enforce it for sanity.
1113 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001114 << Ptr->getType() << Ptr->getSourceRange();
1115 return ExprError();
1116 }
1117
Richard Smithfeea8832012-04-12 05:08:17 +00001118 // FIXME: For any builtin other than a load, the ValType must not be
1119 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001120
1121 switch (ValType.getObjCLifetime()) {
1122 case Qualifiers::OCL_None:
1123 case Qualifiers::OCL_ExplicitNone:
1124 // okay
1125 break;
1126
1127 case Qualifiers::OCL_Weak:
1128 case Qualifiers::OCL_Strong:
1129 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001130 // FIXME: Can this happen? By this point, ValType should be known
1131 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001132 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1133 << ValType << Ptr->getSourceRange();
1134 return ExprError();
1135 }
1136
1137 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001138 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001139 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001140 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001141 ResultType = Context.BoolTy;
1142
Richard Smithfeea8832012-04-12 05:08:17 +00001143 // The type of a parameter passed 'by value'. In the GNU atomics, such
1144 // arguments are actually passed as pointers.
1145 QualType ByValType = ValType; // 'CP'
1146 if (!IsC11 && !IsN)
1147 ByValType = Ptr->getType();
1148
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001149 // The first argument --- the pointer --- has a fixed type; we
1150 // deduce the types of the rest of the arguments accordingly. Walk
1151 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001152 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001153 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001154 if (i < NumVals[Form] + 1) {
1155 switch (i) {
1156 case 1:
1157 // The second argument is the non-atomic operand. For arithmetic, this
1158 // is always passed by value, and for a compare_exchange it is always
1159 // passed by address. For the rest, GNU uses by-address and C11 uses
1160 // by-value.
1161 assert(Form != Load);
1162 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1163 Ty = ValType;
1164 else if (Form == Copy || Form == Xchg)
1165 Ty = ByValType;
1166 else if (Form == Arithmetic)
1167 Ty = Context.getPointerDiffType();
1168 else
1169 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1170 break;
1171 case 2:
1172 // The third argument to compare_exchange / GNU exchange is a
1173 // (pointer to a) desired value.
1174 Ty = ByValType;
1175 break;
1176 case 3:
1177 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1178 Ty = Context.BoolTy;
1179 break;
1180 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001181 } else {
1182 // The order(s) are always converted to int.
1183 Ty = Context.IntTy;
1184 }
Richard Smithfeea8832012-04-12 05:08:17 +00001185
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001186 InitializedEntity Entity =
1187 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001188 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001189 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1190 if (Arg.isInvalid())
1191 return true;
1192 TheCall->setArg(i, Arg.get());
1193 }
1194
Richard Smithfeea8832012-04-12 05:08:17 +00001195 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001196 SmallVector<Expr*, 5> SubExprs;
1197 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001198 switch (Form) {
1199 case Init:
1200 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001201 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001202 break;
1203 case Load:
1204 SubExprs.push_back(TheCall->getArg(1)); // Order
1205 break;
1206 case Copy:
1207 case Arithmetic:
1208 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001209 SubExprs.push_back(TheCall->getArg(2)); // Order
1210 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001211 break;
1212 case GNUXchg:
1213 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1214 SubExprs.push_back(TheCall->getArg(3)); // Order
1215 SubExprs.push_back(TheCall->getArg(1)); // Val1
1216 SubExprs.push_back(TheCall->getArg(2)); // Val2
1217 break;
1218 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001219 SubExprs.push_back(TheCall->getArg(3)); // Order
1220 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001221 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001222 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001223 break;
1224 case GNUCmpXchg:
1225 SubExprs.push_back(TheCall->getArg(4)); // Order
1226 SubExprs.push_back(TheCall->getArg(1)); // Val1
1227 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1228 SubExprs.push_back(TheCall->getArg(2)); // Val2
1229 SubExprs.push_back(TheCall->getArg(3)); // Weak
1230 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001231 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001232
1233 if (SubExprs.size() >= 2 && Form != Init) {
1234 llvm::APSInt Result(32);
1235 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1236 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001237 Diag(SubExprs[1]->getLocStart(),
1238 diag::warn_atomic_op_has_invalid_memory_order)
1239 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001240 }
1241
Fariborz Jahanian615de762013-05-28 17:37:39 +00001242 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1243 SubExprs, ResultType, Op,
1244 TheCall->getRParenLoc());
1245
1246 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1247 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1248 Context.AtomicUsesUnsupportedLibcall(AE))
1249 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1250 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001251
Fariborz Jahanian615de762013-05-28 17:37:39 +00001252 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001253}
1254
1255
John McCall29ad95b2011-08-27 01:09:30 +00001256/// checkBuiltinArgument - Given a call to a builtin function, perform
1257/// normal type-checking on the given argument, updating the call in
1258/// place. This is useful when a builtin function requires custom
1259/// type-checking for some of its arguments but not necessarily all of
1260/// them.
1261///
1262/// Returns true on error.
1263static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1264 FunctionDecl *Fn = E->getDirectCallee();
1265 assert(Fn && "builtin call without direct callee!");
1266
1267 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1268 InitializedEntity Entity =
1269 InitializedEntity::InitializeParameter(S.Context, Param);
1270
1271 ExprResult Arg = E->getArg(0);
1272 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1273 if (Arg.isInvalid())
1274 return true;
1275
1276 E->setArg(ArgIndex, Arg.take());
1277 return false;
1278}
1279
Chris Lattnerdc046542009-05-08 06:58:22 +00001280/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1281/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1282/// type of its first argument. The main ActOnCallExpr routines have already
1283/// promoted the types of arguments because all of these calls are prototyped as
1284/// void(...).
1285///
1286/// This function goes through and does final semantic checking for these
1287/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001288ExprResult
1289Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001290 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001291 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1292 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1293
1294 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001295 if (TheCall->getNumArgs() < 1) {
1296 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1297 << 0 << 1 << TheCall->getNumArgs()
1298 << TheCall->getCallee()->getSourceRange();
1299 return ExprError();
1300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301
Chris Lattnerdc046542009-05-08 06:58:22 +00001302 // Inspect the first argument of the atomic builtin. This should always be
1303 // a pointer type, whose element is an integral scalar or pointer type.
1304 // Because it is a pointer type, we don't have to worry about any implicit
1305 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001306 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001307 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001308 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1309 if (FirstArgResult.isInvalid())
1310 return ExprError();
1311 FirstArg = FirstArgResult.take();
1312 TheCall->setArg(0, FirstArg);
1313
John McCall31168b02011-06-15 23:02:42 +00001314 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1315 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001316 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1317 << FirstArg->getType() << FirstArg->getSourceRange();
1318 return ExprError();
1319 }
Mike Stump11289f42009-09-09 15:08:12 +00001320
John McCall31168b02011-06-15 23:02:42 +00001321 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001322 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001323 !ValType->isBlockPointerType()) {
1324 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1325 << FirstArg->getType() << FirstArg->getSourceRange();
1326 return ExprError();
1327 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001328
John McCall31168b02011-06-15 23:02:42 +00001329 switch (ValType.getObjCLifetime()) {
1330 case Qualifiers::OCL_None:
1331 case Qualifiers::OCL_ExplicitNone:
1332 // okay
1333 break;
1334
1335 case Qualifiers::OCL_Weak:
1336 case Qualifiers::OCL_Strong:
1337 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001338 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001339 << ValType << FirstArg->getSourceRange();
1340 return ExprError();
1341 }
1342
John McCallb50451a2011-10-05 07:41:44 +00001343 // Strip any qualifiers off ValType.
1344 ValType = ValType.getUnqualifiedType();
1345
Chandler Carruth3973af72010-07-18 20:54:12 +00001346 // The majority of builtins return a value, but a few have special return
1347 // types, so allow them to override appropriately below.
1348 QualType ResultType = ValType;
1349
Chris Lattnerdc046542009-05-08 06:58:22 +00001350 // We need to figure out which concrete builtin this maps onto. For example,
1351 // __sync_fetch_and_add with a 2 byte object turns into
1352 // __sync_fetch_and_add_2.
1353#define BUILTIN_ROW(x) \
1354 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1355 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001356
Chris Lattnerdc046542009-05-08 06:58:22 +00001357 static const unsigned BuiltinIndices[][5] = {
1358 BUILTIN_ROW(__sync_fetch_and_add),
1359 BUILTIN_ROW(__sync_fetch_and_sub),
1360 BUILTIN_ROW(__sync_fetch_and_or),
1361 BUILTIN_ROW(__sync_fetch_and_and),
1362 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001363
Chris Lattnerdc046542009-05-08 06:58:22 +00001364 BUILTIN_ROW(__sync_add_and_fetch),
1365 BUILTIN_ROW(__sync_sub_and_fetch),
1366 BUILTIN_ROW(__sync_and_and_fetch),
1367 BUILTIN_ROW(__sync_or_and_fetch),
1368 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001369
Chris Lattnerdc046542009-05-08 06:58:22 +00001370 BUILTIN_ROW(__sync_val_compare_and_swap),
1371 BUILTIN_ROW(__sync_bool_compare_and_swap),
1372 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001373 BUILTIN_ROW(__sync_lock_release),
1374 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001375 };
Mike Stump11289f42009-09-09 15:08:12 +00001376#undef BUILTIN_ROW
1377
Chris Lattnerdc046542009-05-08 06:58:22 +00001378 // Determine the index of the size.
1379 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001380 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001381 case 1: SizeIndex = 0; break;
1382 case 2: SizeIndex = 1; break;
1383 case 4: SizeIndex = 2; break;
1384 case 8: SizeIndex = 3; break;
1385 case 16: SizeIndex = 4; break;
1386 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001387 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1388 << FirstArg->getType() << FirstArg->getSourceRange();
1389 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001390 }
Mike Stump11289f42009-09-09 15:08:12 +00001391
Chris Lattnerdc046542009-05-08 06:58:22 +00001392 // Each of these builtins has one pointer argument, followed by some number of
1393 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1394 // that we ignore. Find out which row of BuiltinIndices to read from as well
1395 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001396 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001397 unsigned BuiltinIndex, NumFixed = 1;
1398 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001399 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001400 case Builtin::BI__sync_fetch_and_add:
1401 case Builtin::BI__sync_fetch_and_add_1:
1402 case Builtin::BI__sync_fetch_and_add_2:
1403 case Builtin::BI__sync_fetch_and_add_4:
1404 case Builtin::BI__sync_fetch_and_add_8:
1405 case Builtin::BI__sync_fetch_and_add_16:
1406 BuiltinIndex = 0;
1407 break;
1408
1409 case Builtin::BI__sync_fetch_and_sub:
1410 case Builtin::BI__sync_fetch_and_sub_1:
1411 case Builtin::BI__sync_fetch_and_sub_2:
1412 case Builtin::BI__sync_fetch_and_sub_4:
1413 case Builtin::BI__sync_fetch_and_sub_8:
1414 case Builtin::BI__sync_fetch_and_sub_16:
1415 BuiltinIndex = 1;
1416 break;
1417
1418 case Builtin::BI__sync_fetch_and_or:
1419 case Builtin::BI__sync_fetch_and_or_1:
1420 case Builtin::BI__sync_fetch_and_or_2:
1421 case Builtin::BI__sync_fetch_and_or_4:
1422 case Builtin::BI__sync_fetch_and_or_8:
1423 case Builtin::BI__sync_fetch_and_or_16:
1424 BuiltinIndex = 2;
1425 break;
1426
1427 case Builtin::BI__sync_fetch_and_and:
1428 case Builtin::BI__sync_fetch_and_and_1:
1429 case Builtin::BI__sync_fetch_and_and_2:
1430 case Builtin::BI__sync_fetch_and_and_4:
1431 case Builtin::BI__sync_fetch_and_and_8:
1432 case Builtin::BI__sync_fetch_and_and_16:
1433 BuiltinIndex = 3;
1434 break;
Mike Stump11289f42009-09-09 15:08:12 +00001435
Douglas Gregor73722482011-11-28 16:30:08 +00001436 case Builtin::BI__sync_fetch_and_xor:
1437 case Builtin::BI__sync_fetch_and_xor_1:
1438 case Builtin::BI__sync_fetch_and_xor_2:
1439 case Builtin::BI__sync_fetch_and_xor_4:
1440 case Builtin::BI__sync_fetch_and_xor_8:
1441 case Builtin::BI__sync_fetch_and_xor_16:
1442 BuiltinIndex = 4;
1443 break;
1444
1445 case Builtin::BI__sync_add_and_fetch:
1446 case Builtin::BI__sync_add_and_fetch_1:
1447 case Builtin::BI__sync_add_and_fetch_2:
1448 case Builtin::BI__sync_add_and_fetch_4:
1449 case Builtin::BI__sync_add_and_fetch_8:
1450 case Builtin::BI__sync_add_and_fetch_16:
1451 BuiltinIndex = 5;
1452 break;
1453
1454 case Builtin::BI__sync_sub_and_fetch:
1455 case Builtin::BI__sync_sub_and_fetch_1:
1456 case Builtin::BI__sync_sub_and_fetch_2:
1457 case Builtin::BI__sync_sub_and_fetch_4:
1458 case Builtin::BI__sync_sub_and_fetch_8:
1459 case Builtin::BI__sync_sub_and_fetch_16:
1460 BuiltinIndex = 6;
1461 break;
1462
1463 case Builtin::BI__sync_and_and_fetch:
1464 case Builtin::BI__sync_and_and_fetch_1:
1465 case Builtin::BI__sync_and_and_fetch_2:
1466 case Builtin::BI__sync_and_and_fetch_4:
1467 case Builtin::BI__sync_and_and_fetch_8:
1468 case Builtin::BI__sync_and_and_fetch_16:
1469 BuiltinIndex = 7;
1470 break;
1471
1472 case Builtin::BI__sync_or_and_fetch:
1473 case Builtin::BI__sync_or_and_fetch_1:
1474 case Builtin::BI__sync_or_and_fetch_2:
1475 case Builtin::BI__sync_or_and_fetch_4:
1476 case Builtin::BI__sync_or_and_fetch_8:
1477 case Builtin::BI__sync_or_and_fetch_16:
1478 BuiltinIndex = 8;
1479 break;
1480
1481 case Builtin::BI__sync_xor_and_fetch:
1482 case Builtin::BI__sync_xor_and_fetch_1:
1483 case Builtin::BI__sync_xor_and_fetch_2:
1484 case Builtin::BI__sync_xor_and_fetch_4:
1485 case Builtin::BI__sync_xor_and_fetch_8:
1486 case Builtin::BI__sync_xor_and_fetch_16:
1487 BuiltinIndex = 9;
1488 break;
Mike Stump11289f42009-09-09 15:08:12 +00001489
Chris Lattnerdc046542009-05-08 06:58:22 +00001490 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001491 case Builtin::BI__sync_val_compare_and_swap_1:
1492 case Builtin::BI__sync_val_compare_and_swap_2:
1493 case Builtin::BI__sync_val_compare_and_swap_4:
1494 case Builtin::BI__sync_val_compare_and_swap_8:
1495 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001496 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001497 NumFixed = 2;
1498 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001499
Chris Lattnerdc046542009-05-08 06:58:22 +00001500 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001501 case Builtin::BI__sync_bool_compare_and_swap_1:
1502 case Builtin::BI__sync_bool_compare_and_swap_2:
1503 case Builtin::BI__sync_bool_compare_and_swap_4:
1504 case Builtin::BI__sync_bool_compare_and_swap_8:
1505 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001506 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001507 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001508 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001509 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001510
1511 case Builtin::BI__sync_lock_test_and_set:
1512 case Builtin::BI__sync_lock_test_and_set_1:
1513 case Builtin::BI__sync_lock_test_and_set_2:
1514 case Builtin::BI__sync_lock_test_and_set_4:
1515 case Builtin::BI__sync_lock_test_and_set_8:
1516 case Builtin::BI__sync_lock_test_and_set_16:
1517 BuiltinIndex = 12;
1518 break;
1519
Chris Lattnerdc046542009-05-08 06:58:22 +00001520 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001521 case Builtin::BI__sync_lock_release_1:
1522 case Builtin::BI__sync_lock_release_2:
1523 case Builtin::BI__sync_lock_release_4:
1524 case Builtin::BI__sync_lock_release_8:
1525 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001526 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001527 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001528 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001529 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001530
1531 case Builtin::BI__sync_swap:
1532 case Builtin::BI__sync_swap_1:
1533 case Builtin::BI__sync_swap_2:
1534 case Builtin::BI__sync_swap_4:
1535 case Builtin::BI__sync_swap_8:
1536 case Builtin::BI__sync_swap_16:
1537 BuiltinIndex = 14;
1538 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001539 }
Mike Stump11289f42009-09-09 15:08:12 +00001540
Chris Lattnerdc046542009-05-08 06:58:22 +00001541 // Now that we know how many fixed arguments we expect, first check that we
1542 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001543 if (TheCall->getNumArgs() < 1+NumFixed) {
1544 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1545 << 0 << 1+NumFixed << TheCall->getNumArgs()
1546 << TheCall->getCallee()->getSourceRange();
1547 return ExprError();
1548 }
Mike Stump11289f42009-09-09 15:08:12 +00001549
Chris Lattner5b9241b2009-05-08 15:36:58 +00001550 // Get the decl for the concrete builtin from this, we can tell what the
1551 // concrete integer type we should convert to is.
1552 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1553 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001554 FunctionDecl *NewBuiltinDecl;
1555 if (NewBuiltinID == BuiltinID)
1556 NewBuiltinDecl = FDecl;
1557 else {
1558 // Perform builtin lookup to avoid redeclaring it.
1559 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1560 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1561 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1562 assert(Res.getFoundDecl());
1563 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1564 if (NewBuiltinDecl == 0)
1565 return ExprError();
1566 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001567
John McCallcf142162010-08-07 06:22:56 +00001568 // The first argument --- the pointer --- has a fixed type; we
1569 // deduce the types of the rest of the arguments accordingly. Walk
1570 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001571 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001572 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001573
Chris Lattnerdc046542009-05-08 06:58:22 +00001574 // GCC does an implicit conversion to the pointer or integer ValType. This
1575 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001576 // Initialize the argument.
1577 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1578 ValType, /*consume*/ false);
1579 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001580 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001581 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001582
Chris Lattnerdc046542009-05-08 06:58:22 +00001583 // Okay, we have something that *can* be converted to the right type. Check
1584 // to see if there is a potentially weird extension going on here. This can
1585 // happen when you do an atomic operation on something like an char* and
1586 // pass in 42. The 42 gets converted to char. This is even more strange
1587 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001588 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001589 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001590 }
Mike Stump11289f42009-09-09 15:08:12 +00001591
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001592 ASTContext& Context = this->getASTContext();
1593
1594 // Create a new DeclRefExpr to refer to the new decl.
1595 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1596 Context,
1597 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001598 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001599 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001600 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001601 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001602 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001603 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001604
Chris Lattnerdc046542009-05-08 06:58:22 +00001605 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001606 // FIXME: This loses syntactic information.
1607 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1608 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1609 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001610 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001611
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001612 // Change the result type of the call to match the original value type. This
1613 // is arbitrary, but the codegen for these builtins ins design to handle it
1614 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001615 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001616
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001617 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001618}
1619
Chris Lattner6436fb62009-02-18 06:01:06 +00001620/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001621/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001622/// Note: It might also make sense to do the UTF-16 conversion here (would
1623/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001624bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001625 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001626 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1627
Douglas Gregorfb65e592011-07-27 05:40:30 +00001628 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001629 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1630 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001631 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001632 }
Mike Stump11289f42009-09-09 15:08:12 +00001633
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001634 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001635 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001636 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001637 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001638 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001639 UTF16 *ToPtr = &ToBuf[0];
1640
1641 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1642 &ToPtr, ToPtr + NumBytes,
1643 strictConversion);
1644 // Check for conversion failure.
1645 if (Result != conversionOK)
1646 Diag(Arg->getLocStart(),
1647 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1648 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001649 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001650}
1651
Chris Lattnere202e6a2007-12-20 00:05:45 +00001652/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1653/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001654bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1655 Expr *Fn = TheCall->getCallee();
1656 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001657 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001658 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001659 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1660 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001661 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001662 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001663 return true;
1664 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001665
1666 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001667 return Diag(TheCall->getLocEnd(),
1668 diag::err_typecheck_call_too_few_args_at_least)
1669 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001670 }
1671
John McCall29ad95b2011-08-27 01:09:30 +00001672 // Type-check the first argument normally.
1673 if (checkBuiltinArgument(*this, TheCall, 0))
1674 return true;
1675
Chris Lattnere202e6a2007-12-20 00:05:45 +00001676 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001677 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001678 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001679 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001680 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001681 else if (FunctionDecl *FD = getCurFunctionDecl())
1682 isVariadic = FD->isVariadic();
1683 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001684 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001685
Chris Lattnere202e6a2007-12-20 00:05:45 +00001686 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001687 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1688 return true;
1689 }
Mike Stump11289f42009-09-09 15:08:12 +00001690
Chris Lattner43be2e62007-12-19 23:59:04 +00001691 // Verify that the second argument to the builtin is the last argument of the
1692 // current function or method.
1693 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001694 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001695
Nico Weber9eea7642013-05-24 23:31:57 +00001696 // These are valid if SecondArgIsLastNamedArgument is false after the next
1697 // block.
1698 QualType Type;
1699 SourceLocation ParamLoc;
1700
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001701 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1702 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001703 // FIXME: This isn't correct for methods (results in bogus warning).
1704 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001705 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001706 if (CurBlock)
1707 LastArg = *(CurBlock->TheDecl->param_end()-1);
1708 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001709 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001710 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001711 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001712 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001713
1714 Type = PV->getType();
1715 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001716 }
1717 }
Mike Stump11289f42009-09-09 15:08:12 +00001718
Chris Lattner43be2e62007-12-19 23:59:04 +00001719 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001720 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001721 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001722 else if (Type->isReferenceType()) {
1723 Diag(Arg->getLocStart(),
1724 diag::warn_va_start_of_reference_type_is_undefined);
1725 Diag(ParamLoc, diag::note_parameter_type) << Type;
1726 }
1727
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001728 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001729 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001730}
Chris Lattner43be2e62007-12-19 23:59:04 +00001731
Chris Lattner2da14fb2007-12-20 00:26:33 +00001732/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1733/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001734bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1735 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001736 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001737 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001738 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001739 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001740 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001741 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001742 << SourceRange(TheCall->getArg(2)->getLocStart(),
1743 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001744
John Wiegley01296292011-04-08 18:41:53 +00001745 ExprResult OrigArg0 = TheCall->getArg(0);
1746 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001747
Chris Lattner2da14fb2007-12-20 00:26:33 +00001748 // Do standard promotions between the two arguments, returning their common
1749 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001750 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001751 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1752 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001753
1754 // Make sure any conversions are pushed back into the call; this is
1755 // type safe since unordered compare builtins are declared as "_Bool
1756 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001757 TheCall->setArg(0, OrigArg0.get());
1758 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001759
John Wiegley01296292011-04-08 18:41:53 +00001760 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001761 return false;
1762
Chris Lattner2da14fb2007-12-20 00:26:33 +00001763 // If the common type isn't a real floating type, then the arguments were
1764 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001765 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001766 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001767 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001768 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1769 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001770
Chris Lattner2da14fb2007-12-20 00:26:33 +00001771 return false;
1772}
1773
Benjamin Kramer634fc102010-02-15 22:42:31 +00001774/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1775/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001776/// to check everything. We expect the last argument to be a floating point
1777/// value.
1778bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1779 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001780 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001781 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001782 if (TheCall->getNumArgs() > NumArgs)
1783 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001784 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001785 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001786 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001787 (*(TheCall->arg_end()-1))->getLocEnd());
1788
Benjamin Kramer64aae502010-02-16 10:07:31 +00001789 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001790
Eli Friedman7e4faac2009-08-31 20:06:00 +00001791 if (OrigArg->isTypeDependent())
1792 return false;
1793
Chris Lattner68784ef2010-05-06 05:50:07 +00001794 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001795 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001796 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001797 diag::err_typecheck_call_invalid_unary_fp)
1798 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001799
Chris Lattner68784ef2010-05-06 05:50:07 +00001800 // If this is an implicit conversion from float -> double, remove it.
1801 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1802 Expr *CastArg = Cast->getSubExpr();
1803 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1804 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1805 "promotion from float to double is the only expected cast here");
1806 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001807 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001808 }
1809 }
1810
Eli Friedman7e4faac2009-08-31 20:06:00 +00001811 return false;
1812}
1813
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001814/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1815// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001816ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001817 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001818 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001819 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001820 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1821 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001822
Nate Begemana0110022010-06-08 00:16:34 +00001823 // Determine which of the following types of shufflevector we're checking:
1824 // 1) unary, vector mask: (lhs, mask)
1825 // 2) binary, vector mask: (lhs, rhs, mask)
1826 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1827 QualType resType = TheCall->getArg(0)->getType();
1828 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001829
Douglas Gregorc25f7662009-05-19 22:10:17 +00001830 if (!TheCall->getArg(0)->isTypeDependent() &&
1831 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001832 QualType LHSType = TheCall->getArg(0)->getType();
1833 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001834
Craig Topperbaca3892013-07-29 06:47:04 +00001835 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1836 return ExprError(Diag(TheCall->getLocStart(),
1837 diag::err_shufflevector_non_vector)
1838 << SourceRange(TheCall->getArg(0)->getLocStart(),
1839 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001840
Nate Begemana0110022010-06-08 00:16:34 +00001841 numElements = LHSType->getAs<VectorType>()->getNumElements();
1842 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001843
Nate Begemana0110022010-06-08 00:16:34 +00001844 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1845 // with mask. If so, verify that RHS is an integer vector type with the
1846 // same number of elts as lhs.
1847 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001848 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001849 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001850 return ExprError(Diag(TheCall->getLocStart(),
1851 diag::err_shufflevector_incompatible_vector)
1852 << SourceRange(TheCall->getArg(1)->getLocStart(),
1853 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001854 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001855 return ExprError(Diag(TheCall->getLocStart(),
1856 diag::err_shufflevector_incompatible_vector)
1857 << SourceRange(TheCall->getArg(0)->getLocStart(),
1858 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001859 } else if (numElements != numResElements) {
1860 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001861 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001862 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001863 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001864 }
1865
1866 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001867 if (TheCall->getArg(i)->isTypeDependent() ||
1868 TheCall->getArg(i)->isValueDependent())
1869 continue;
1870
Nate Begemana0110022010-06-08 00:16:34 +00001871 llvm::APSInt Result(32);
1872 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1873 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001874 diag::err_shufflevector_nonconstant_argument)
1875 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001876
Craig Topper50ad5b72013-08-03 17:40:38 +00001877 // Allow -1 which will be translated to undef in the IR.
1878 if (Result.isSigned() && Result.isAllOnesValue())
1879 continue;
1880
Chris Lattner7ab824e2008-08-10 02:05:13 +00001881 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001882 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001883 diag::err_shufflevector_argument_too_large)
1884 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001885 }
1886
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001887 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001888
Chris Lattner7ab824e2008-08-10 02:05:13 +00001889 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001890 exprs.push_back(TheCall->getArg(i));
1891 TheCall->setArg(i, 0);
1892 }
1893
Benjamin Kramerc215e762012-08-24 11:54:20 +00001894 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001895 TheCall->getCallee()->getLocStart(),
1896 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001897}
Chris Lattner43be2e62007-12-19 23:59:04 +00001898
Hal Finkelc4d7c822013-09-18 03:29:45 +00001899/// SemaConvertVectorExpr - Handle __builtin_convertvector
1900ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1901 SourceLocation BuiltinLoc,
1902 SourceLocation RParenLoc) {
1903 ExprValueKind VK = VK_RValue;
1904 ExprObjectKind OK = OK_Ordinary;
1905 QualType DstTy = TInfo->getType();
1906 QualType SrcTy = E->getType();
1907
1908 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1909 return ExprError(Diag(BuiltinLoc,
1910 diag::err_convertvector_non_vector)
1911 << E->getSourceRange());
1912 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1913 return ExprError(Diag(BuiltinLoc,
1914 diag::err_convertvector_non_vector_type));
1915
1916 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1917 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1918 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1919 if (SrcElts != DstElts)
1920 return ExprError(Diag(BuiltinLoc,
1921 diag::err_convertvector_incompatible_vector)
1922 << E->getSourceRange());
1923 }
1924
1925 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1926 BuiltinLoc, RParenLoc));
1927
1928}
1929
Daniel Dunbarb7257262008-07-21 22:59:13 +00001930/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1931// This is declared to take (const void*, ...) and can take two
1932// optional constant int args.
1933bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001934 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001935
Chris Lattner3b054132008-11-19 05:08:23 +00001936 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001937 return Diag(TheCall->getLocEnd(),
1938 diag::err_typecheck_call_too_many_args_at_most)
1939 << 0 /*function call*/ << 3 << NumArgs
1940 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001941
1942 // Argument 0 is checked for us and the remaining arguments must be
1943 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001944 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001945 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001946
1947 // We can't check the value of a dependent argument.
1948 if (Arg->isTypeDependent() || Arg->isValueDependent())
1949 continue;
1950
Eli Friedman5efba262009-12-04 00:30:06 +00001951 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001952 if (SemaBuiltinConstantArg(TheCall, i, Result))
1953 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001954
Daniel Dunbarb7257262008-07-21 22:59:13 +00001955 // FIXME: gcc issues a warning and rewrites these to 0. These
1956 // seems especially odd for the third argument since the default
1957 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001958 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001959 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001960 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001961 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001962 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001963 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001964 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001965 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001966 }
1967 }
1968
Chris Lattner3b054132008-11-19 05:08:23 +00001969 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001970}
1971
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001972/// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
1973// This is declared to take (const char*, int)
1974bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
1975 Expr *Arg = TheCall->getArg(1);
1976
1977 // We can't check the value of a dependent argument.
1978 if (Arg->isTypeDependent() || Arg->isValueDependent())
1979 return false;
1980
1981 llvm::APSInt Result;
1982 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1983 return true;
1984
1985 if (Result.getLimitedValue() > 3)
1986 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1987 << "0" << "3" << Arg->getSourceRange();
1988
1989 return false;
1990}
1991
Eric Christopher8d0c6212010-04-17 02:26:23 +00001992/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1993/// TheCall is a constant expression.
1994bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1995 llvm::APSInt &Result) {
1996 Expr *Arg = TheCall->getArg(ArgNum);
1997 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1998 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1999
2000 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2001
2002 if (!Arg->isIntegerConstantExpr(Result, Context))
2003 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002004 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002005
Chris Lattnerd545ad12009-09-23 06:06:36 +00002006 return false;
2007}
2008
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002009/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
2010/// int type). This simply type checks that type is one of the defined
2011/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00002012// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002013bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002014 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002015
2016 // We can't check the value of a dependent argument.
2017 if (TheCall->getArg(1)->isTypeDependent() ||
2018 TheCall->getArg(1)->isValueDependent())
2019 return false;
2020
Eric Christopher8d0c6212010-04-17 02:26:23 +00002021 // Check constant-ness first.
2022 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2023 return true;
2024
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002025 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002026 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00002027 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2028 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002029 }
2030
2031 return false;
2032}
2033
Eli Friedmanc97d0142009-05-03 06:04:26 +00002034/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002035/// This checks that val is a constant 1.
2036bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2037 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002038 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002039
Eric Christopher8d0c6212010-04-17 02:26:23 +00002040 // TODO: This is less than ideal. Overload this to take a value.
2041 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2042 return true;
2043
2044 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002045 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2046 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2047
2048 return false;
2049}
2050
Richard Smithd7293d72013-08-05 18:49:43 +00002051namespace {
2052enum StringLiteralCheckType {
2053 SLCT_NotALiteral,
2054 SLCT_UncheckedLiteral,
2055 SLCT_CheckedLiteral
2056};
2057}
2058
Richard Smith55ce3522012-06-25 20:30:08 +00002059// Determine if an expression is a string literal or constant string.
2060// If this function returns false on the arguments to a function expecting a
2061// format string, we will usually need to emit a warning.
2062// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002063static StringLiteralCheckType
2064checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2065 bool HasVAListArg, unsigned format_idx,
2066 unsigned firstDataArg, Sema::FormatStringType Type,
2067 Sema::VariadicCallType CallType, bool InFunctionCall,
2068 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002069 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002070 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002071 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002072
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002073 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002074
Richard Smithd7293d72013-08-05 18:49:43 +00002075 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002076 // Technically -Wformat-nonliteral does not warn about this case.
2077 // The behavior of printf and friends in this case is implementation
2078 // dependent. Ideally if the format string cannot be null then
2079 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002080 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002081
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002082 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002083 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002084 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002085 // The expression is a literal if both sub-expressions were, and it was
2086 // completely checked only if both sub-expressions were checked.
2087 const AbstractConditionalOperator *C =
2088 cast<AbstractConditionalOperator>(E);
2089 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002090 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002091 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002092 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002093 if (Left == SLCT_NotALiteral)
2094 return SLCT_NotALiteral;
2095 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002096 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002097 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002098 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002099 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002100 }
2101
2102 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002103 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2104 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002105 }
2106
John McCallc07a0c72011-02-17 10:25:35 +00002107 case Stmt::OpaqueValueExprClass:
2108 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2109 E = src;
2110 goto tryAgain;
2111 }
Richard Smith55ce3522012-06-25 20:30:08 +00002112 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002113
Ted Kremeneka8890832011-02-24 23:03:04 +00002114 case Stmt::PredefinedExprClass:
2115 // While __func__, etc., are technically not string literals, they
2116 // cannot contain format specifiers and thus are not a security
2117 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002118 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002119
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002120 case Stmt::DeclRefExprClass: {
2121 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002122
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002123 // As an exception, do not flag errors for variables binding to
2124 // const string literals.
2125 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2126 bool isConstant = false;
2127 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002128
Richard Smithd7293d72013-08-05 18:49:43 +00002129 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2130 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002131 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002132 isConstant = T.isConstant(S.Context) &&
2133 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002134 } else if (T->isObjCObjectPointerType()) {
2135 // In ObjC, there is usually no "const ObjectPointer" type,
2136 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002137 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002138 }
Mike Stump11289f42009-09-09 15:08:12 +00002139
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002140 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002141 if (const Expr *Init = VD->getAnyInitializer()) {
2142 // Look through initializers like const char c[] = { "foo" }
2143 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2144 if (InitList->isStringLiteralInit())
2145 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2146 }
Richard Smithd7293d72013-08-05 18:49:43 +00002147 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002148 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002149 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002150 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002151 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002152 }
Mike Stump11289f42009-09-09 15:08:12 +00002153
Anders Carlssonb012ca92009-06-28 19:55:58 +00002154 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2155 // special check to see if the format string is a function parameter
2156 // of the function calling the printf function. If the function
2157 // has an attribute indicating it is a printf-like function, then we
2158 // should suppress warnings concerning non-literals being used in a call
2159 // to a vprintf function. For example:
2160 //
2161 // void
2162 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2163 // va_list ap;
2164 // va_start(ap, fmt);
2165 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2166 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002167 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002168 if (HasVAListArg) {
2169 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2170 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2171 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002172 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002173 // adjust for implicit parameter
2174 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2175 if (MD->isInstance())
2176 ++PVIndex;
2177 // We also check if the formats are compatible.
2178 // We can't pass a 'scanf' string to a 'printf' function.
2179 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002180 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002181 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002182 }
2183 }
2184 }
2185 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002186 }
Mike Stump11289f42009-09-09 15:08:12 +00002187
Richard Smith55ce3522012-06-25 20:30:08 +00002188 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002189 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002190
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002191 case Stmt::CallExprClass:
2192 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002193 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002194 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2195 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2196 unsigned ArgIndex = FA->getFormatIdx();
2197 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2198 if (MD->isInstance())
2199 --ArgIndex;
2200 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002201
Richard Smithd7293d72013-08-05 18:49:43 +00002202 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002203 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002204 Type, CallType, InFunctionCall,
2205 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002206 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2207 unsigned BuiltinID = FD->getBuiltinID();
2208 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2209 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2210 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002211 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002212 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002213 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002214 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002215 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002216 }
2217 }
Mike Stump11289f42009-09-09 15:08:12 +00002218
Richard Smith55ce3522012-06-25 20:30:08 +00002219 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002220 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002221 case Stmt::ObjCStringLiteralClass:
2222 case Stmt::StringLiteralClass: {
2223 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002224
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002225 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002226 StrE = ObjCFExpr->getString();
2227 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002228 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002229
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002230 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002231 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2232 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002233 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002234 }
Mike Stump11289f42009-09-09 15:08:12 +00002235
Richard Smith55ce3522012-06-25 20:30:08 +00002236 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002237 }
Mike Stump11289f42009-09-09 15:08:12 +00002238
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002239 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002240 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002241 }
2242}
2243
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002244Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002245 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002246 .Case("scanf", FST_Scanf)
2247 .Cases("printf", "printf0", FST_Printf)
2248 .Cases("NSString", "CFString", FST_NSString)
2249 .Case("strftime", FST_Strftime)
2250 .Case("strfmon", FST_Strfmon)
2251 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2252 .Default(FST_Unknown);
2253}
2254
Jordan Rose3e0ec582012-07-19 18:10:23 +00002255/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002256/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002257/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002258bool Sema::CheckFormatArguments(const FormatAttr *Format,
2259 ArrayRef<const Expr *> Args,
2260 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002261 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002262 SourceLocation Loc, SourceRange Range,
2263 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002264 FormatStringInfo FSI;
2265 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002266 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002267 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002268 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002269 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002270}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002271
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002272bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002273 bool HasVAListArg, unsigned format_idx,
2274 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002275 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002276 SourceLocation Loc, SourceRange Range,
2277 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002278 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002279 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002280 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002281 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002282 }
Mike Stump11289f42009-09-09 15:08:12 +00002283
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002284 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002285
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002286 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002287 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002288 // Dynamically generated format strings are difficult to
2289 // automatically vet at compile time. Requiring that format strings
2290 // are string literals: (1) permits the checking of format strings by
2291 // the compiler and thereby (2) can practically remove the source of
2292 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002293
Mike Stump11289f42009-09-09 15:08:12 +00002294 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002295 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002296 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002297 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002298 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002299 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2300 format_idx, firstDataArg, Type, CallType,
2301 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002302 if (CT != SLCT_NotALiteral)
2303 // Literal format string found, check done!
2304 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002305
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002306 // Strftime is particular as it always uses a single 'time' argument,
2307 // so it is safe to pass a non-literal string.
2308 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002309 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002310
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002311 // Do not emit diag when the string param is a macro expansion and the
2312 // format is either NSString or CFString. This is a hack to prevent
2313 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2314 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002315 if (Type == FST_NSString &&
2316 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002317 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002318
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002319 // If there are no arguments specified, warn with -Wformat-security, otherwise
2320 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002321 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002322 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002323 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002324 << OrigFormatExpr->getSourceRange();
2325 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002326 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002327 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002328 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002329 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002330}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002331
Ted Kremenekab278de2010-01-28 23:39:18 +00002332namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002333class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2334protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002335 Sema &S;
2336 const StringLiteral *FExpr;
2337 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002338 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002339 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002340 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002341 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002342 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002343 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002344 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002345 bool usesPositionalArgs;
2346 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002347 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002348 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002349 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002350public:
Ted Kremenek02087932010-07-16 02:11:22 +00002351 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002352 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002353 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002354 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002355 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002356 Sema::VariadicCallType callType,
2357 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002358 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002359 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2360 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002361 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002362 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002363 inFunctionCall(inFunctionCall), CallType(callType),
2364 CheckedVarArgs(CheckedVarArgs) {
2365 CoveredArgs.resize(numDataArgs);
2366 CoveredArgs.reset();
2367 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002368
Ted Kremenek019d2242010-01-29 01:50:07 +00002369 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002370
Ted Kremenek02087932010-07-16 02:11:22 +00002371 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002372 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002373
Jordan Rose92303592012-09-08 04:00:03 +00002374 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002375 const analyze_format_string::FormatSpecifier &FS,
2376 const analyze_format_string::ConversionSpecifier &CS,
2377 const char *startSpecifier, unsigned specifierLen,
2378 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002379
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002380 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002381 const analyze_format_string::FormatSpecifier &FS,
2382 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002383
2384 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002385 const analyze_format_string::ConversionSpecifier &CS,
2386 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002387
Craig Toppere14c0f82014-03-12 04:55:44 +00002388 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002389
Craig Toppere14c0f82014-03-12 04:55:44 +00002390 void HandleInvalidPosition(const char *startSpecifier,
2391 unsigned specifierLen,
2392 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002393
Craig Toppere14c0f82014-03-12 04:55:44 +00002394 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002395
Craig Toppere14c0f82014-03-12 04:55:44 +00002396 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002397
Richard Trieu03cf7b72011-10-28 00:41:25 +00002398 template <typename Range>
2399 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2400 const Expr *ArgumentExpr,
2401 PartialDiagnostic PDiag,
2402 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
Ted Kremenek02087932010-07-16 02:11:22 +00002406protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002407 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2408 const char *startSpec,
2409 unsigned specifierLen,
2410 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002411
2412 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2413 const char *startSpec,
2414 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002415
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002416 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002417 CharSourceRange getSpecifierRange(const char *startSpecifier,
2418 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002419 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002420
Ted Kremenek5739de72010-01-29 01:06:55 +00002421 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002422
2423 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2424 const analyze_format_string::ConversionSpecifier &CS,
2425 const char *startSpecifier, unsigned specifierLen,
2426 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002427
2428 template <typename Range>
2429 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2430 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002431 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002432};
2433}
2434
Ted Kremenek02087932010-07-16 02:11:22 +00002435SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002436 return OrigFormatExpr->getSourceRange();
2437}
2438
Ted Kremenek02087932010-07-16 02:11:22 +00002439CharSourceRange CheckFormatHandler::
2440getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002441 SourceLocation Start = getLocationOfByte(startSpecifier);
2442 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2443
2444 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002445 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002446
2447 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002448}
2449
Ted Kremenek02087932010-07-16 02:11:22 +00002450SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002451 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002452}
2453
Ted Kremenek02087932010-07-16 02:11:22 +00002454void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2455 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002456 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2457 getLocationOfByte(startSpecifier),
2458 /*IsStringLocation*/true,
2459 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002460}
2461
Jordan Rose92303592012-09-08 04:00:03 +00002462void CheckFormatHandler::HandleInvalidLengthModifier(
2463 const analyze_format_string::FormatSpecifier &FS,
2464 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002465 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002466 using namespace analyze_format_string;
2467
2468 const LengthModifier &LM = FS.getLengthModifier();
2469 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2470
2471 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002472 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002473 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002474 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002475 getLocationOfByte(LM.getStart()),
2476 /*IsStringLocation*/true,
2477 getSpecifierRange(startSpecifier, specifierLen));
2478
2479 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2480 << FixedLM->toString()
2481 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2482
2483 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002484 FixItHint Hint;
2485 if (DiagID == diag::warn_format_nonsensical_length)
2486 Hint = FixItHint::CreateRemoval(LMRange);
2487
2488 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002489 getLocationOfByte(LM.getStart()),
2490 /*IsStringLocation*/true,
2491 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002492 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002493 }
2494}
2495
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002496void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002497 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002498 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002499 using namespace analyze_format_string;
2500
2501 const LengthModifier &LM = FS.getLengthModifier();
2502 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2503
2504 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002505 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002506 if (FixedLM) {
2507 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2508 << LM.toString() << 0,
2509 getLocationOfByte(LM.getStart()),
2510 /*IsStringLocation*/true,
2511 getSpecifierRange(startSpecifier, specifierLen));
2512
2513 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2514 << FixedLM->toString()
2515 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2516
2517 } else {
2518 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2519 << LM.toString() << 0,
2520 getLocationOfByte(LM.getStart()),
2521 /*IsStringLocation*/true,
2522 getSpecifierRange(startSpecifier, specifierLen));
2523 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002524}
2525
2526void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2527 const analyze_format_string::ConversionSpecifier &CS,
2528 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002529 using namespace analyze_format_string;
2530
2531 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002532 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002533 if (FixedCS) {
2534 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2535 << CS.toString() << /*conversion specifier*/1,
2536 getLocationOfByte(CS.getStart()),
2537 /*IsStringLocation*/true,
2538 getSpecifierRange(startSpecifier, specifierLen));
2539
2540 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2541 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2542 << FixedCS->toString()
2543 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2544 } else {
2545 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2546 << CS.toString() << /*conversion specifier*/1,
2547 getLocationOfByte(CS.getStart()),
2548 /*IsStringLocation*/true,
2549 getSpecifierRange(startSpecifier, specifierLen));
2550 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002551}
2552
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002553void CheckFormatHandler::HandlePosition(const char *startPos,
2554 unsigned posLen) {
2555 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2556 getLocationOfByte(startPos),
2557 /*IsStringLocation*/true,
2558 getSpecifierRange(startPos, posLen));
2559}
2560
Ted Kremenekd1668192010-02-27 01:41:03 +00002561void
Ted Kremenek02087932010-07-16 02:11:22 +00002562CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2563 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002564 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2565 << (unsigned) p,
2566 getLocationOfByte(startPos), /*IsStringLocation*/true,
2567 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002568}
2569
Ted Kremenek02087932010-07-16 02:11:22 +00002570void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002571 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002572 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2573 getLocationOfByte(startPos),
2574 /*IsStringLocation*/true,
2575 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002576}
2577
Ted Kremenek02087932010-07-16 02:11:22 +00002578void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002579 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002580 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002581 EmitFormatDiagnostic(
2582 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2583 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2584 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002585 }
Ted Kremenek02087932010-07-16 02:11:22 +00002586}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002587
Jordan Rose58bbe422012-07-19 18:10:08 +00002588// Note that this may return NULL if there was an error parsing or building
2589// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002590const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002591 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002592}
2593
2594void CheckFormatHandler::DoneProcessing() {
2595 // Does the number of data arguments exceed the number of
2596 // format conversions in the format string?
2597 if (!HasVAListArg) {
2598 // Find any arguments that weren't covered.
2599 CoveredArgs.flip();
2600 signed notCoveredArg = CoveredArgs.find_first();
2601 if (notCoveredArg >= 0) {
2602 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002603 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2604 SourceLocation Loc = E->getLocStart();
2605 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2606 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2607 Loc, /*IsStringLocation*/false,
2608 getFormatStringRange());
2609 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002610 }
Ted Kremenek02087932010-07-16 02:11:22 +00002611 }
2612 }
2613}
2614
Ted Kremenekce815422010-07-19 21:25:57 +00002615bool
2616CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2617 SourceLocation Loc,
2618 const char *startSpec,
2619 unsigned specifierLen,
2620 const char *csStart,
2621 unsigned csLen) {
2622
2623 bool keepGoing = true;
2624 if (argIndex < NumDataArgs) {
2625 // Consider the argument coverered, even though the specifier doesn't
2626 // make sense.
2627 CoveredArgs.set(argIndex);
2628 }
2629 else {
2630 // If argIndex exceeds the number of data arguments we
2631 // don't issue a warning because that is just a cascade of warnings (and
2632 // they may have intended '%%' anyway). We don't want to continue processing
2633 // the format string after this point, however, as we will like just get
2634 // gibberish when trying to match arguments.
2635 keepGoing = false;
2636 }
2637
Richard Trieu03cf7b72011-10-28 00:41:25 +00002638 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2639 << StringRef(csStart, csLen),
2640 Loc, /*IsStringLocation*/true,
2641 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002642
2643 return keepGoing;
2644}
2645
Richard Trieu03cf7b72011-10-28 00:41:25 +00002646void
2647CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2648 const char *startSpec,
2649 unsigned specifierLen) {
2650 EmitFormatDiagnostic(
2651 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2652 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2653}
2654
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002655bool
2656CheckFormatHandler::CheckNumArgs(
2657 const analyze_format_string::FormatSpecifier &FS,
2658 const analyze_format_string::ConversionSpecifier &CS,
2659 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2660
2661 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002662 PartialDiagnostic PDiag = FS.usesPositionalArg()
2663 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2664 << (argIndex+1) << NumDataArgs)
2665 : S.PDiag(diag::warn_printf_insufficient_data_args);
2666 EmitFormatDiagnostic(
2667 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2668 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002669 return false;
2670 }
2671 return true;
2672}
2673
Richard Trieu03cf7b72011-10-28 00:41:25 +00002674template<typename Range>
2675void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2676 SourceLocation Loc,
2677 bool IsStringLocation,
2678 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002679 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002680 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002681 Loc, IsStringLocation, StringRange, FixIt);
2682}
2683
2684/// \brief If the format string is not within the funcion call, emit a note
2685/// so that the function call and string are in diagnostic messages.
2686///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002687/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002688/// call and only one diagnostic message will be produced. Otherwise, an
2689/// extra note will be emitted pointing to location of the format string.
2690///
2691/// \param ArgumentExpr the expression that is passed as the format string
2692/// argument in the function call. Used for getting locations when two
2693/// diagnostics are emitted.
2694///
2695/// \param PDiag the callee should already have provided any strings for the
2696/// diagnostic message. This function only adds locations and fixits
2697/// to diagnostics.
2698///
2699/// \param Loc primary location for diagnostic. If two diagnostics are
2700/// required, one will be at Loc and a new SourceLocation will be created for
2701/// the other one.
2702///
2703/// \param IsStringLocation if true, Loc points to the format string should be
2704/// used for the note. Otherwise, Loc points to the argument list and will
2705/// be used with PDiag.
2706///
2707/// \param StringRange some or all of the string to highlight. This is
2708/// templated so it can accept either a CharSourceRange or a SourceRange.
2709///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002710/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002711template<typename Range>
2712void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2713 const Expr *ArgumentExpr,
2714 PartialDiagnostic PDiag,
2715 SourceLocation Loc,
2716 bool IsStringLocation,
2717 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002718 ArrayRef<FixItHint> FixIt) {
2719 if (InFunctionCall) {
2720 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2721 D << StringRange;
2722 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2723 I != E; ++I) {
2724 D << *I;
2725 }
2726 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002727 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2728 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002729
2730 const Sema::SemaDiagnosticBuilder &Note =
2731 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2732 diag::note_format_string_defined);
2733
2734 Note << StringRange;
2735 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2736 I != E; ++I) {
2737 Note << *I;
2738 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002739 }
2740}
2741
Ted Kremenek02087932010-07-16 02:11:22 +00002742//===--- CHECK: Printf format string checking ------------------------------===//
2743
2744namespace {
2745class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002746 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002747public:
2748 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2749 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002750 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002751 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002752 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002753 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002754 Sema::VariadicCallType CallType,
2755 llvm::SmallBitVector &CheckedVarArgs)
2756 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2757 numDataArgs, beg, hasVAListArg, Args,
2758 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2759 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002760 {}
2761
Craig Toppere14c0f82014-03-12 04:55:44 +00002762
Ted Kremenek02087932010-07-16 02:11:22 +00002763 bool HandleInvalidPrintfConversionSpecifier(
2764 const analyze_printf::PrintfSpecifier &FS,
2765 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002766 unsigned specifierLen) override;
2767
Ted Kremenek02087932010-07-16 02:11:22 +00002768 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2769 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002770 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002771 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2772 const char *StartSpecifier,
2773 unsigned SpecifierLen,
2774 const Expr *E);
2775
Ted Kremenek02087932010-07-16 02:11:22 +00002776 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2777 const char *startSpecifier, unsigned specifierLen);
2778 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2779 const analyze_printf::OptionalAmount &Amt,
2780 unsigned type,
2781 const char *startSpecifier, unsigned specifierLen);
2782 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2783 const analyze_printf::OptionalFlag &flag,
2784 const char *startSpecifier, unsigned specifierLen);
2785 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2786 const analyze_printf::OptionalFlag &ignoredFlag,
2787 const analyze_printf::OptionalFlag &flag,
2788 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002789 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002790 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002791
Ted Kremenek02087932010-07-16 02:11:22 +00002792};
2793}
2794
2795bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2796 const analyze_printf::PrintfSpecifier &FS,
2797 const char *startSpecifier,
2798 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002799 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002800 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002801
Ted Kremenekce815422010-07-19 21:25:57 +00002802 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2803 getLocationOfByte(CS.getStart()),
2804 startSpecifier, specifierLen,
2805 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002806}
2807
Ted Kremenek02087932010-07-16 02:11:22 +00002808bool CheckPrintfHandler::HandleAmount(
2809 const analyze_format_string::OptionalAmount &Amt,
2810 unsigned k, const char *startSpecifier,
2811 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002812
2813 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002814 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002815 unsigned argIndex = Amt.getArgIndex();
2816 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002817 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2818 << k,
2819 getLocationOfByte(Amt.getStart()),
2820 /*IsStringLocation*/true,
2821 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002822 // Don't do any more checking. We will just emit
2823 // spurious errors.
2824 return false;
2825 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002826
Ted Kremenek5739de72010-01-29 01:06:55 +00002827 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002828 // Although not in conformance with C99, we also allow the argument to be
2829 // an 'unsigned int' as that is a reasonably safe case. GCC also
2830 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002831 CoveredArgs.set(argIndex);
2832 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002833 if (!Arg)
2834 return false;
2835
Ted Kremenek5739de72010-01-29 01:06:55 +00002836 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002837
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002838 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2839 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002840
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002841 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002843 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002844 << T << Arg->getSourceRange(),
2845 getLocationOfByte(Amt.getStart()),
2846 /*IsStringLocation*/true,
2847 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002848 // Don't do any more checking. We will just emit
2849 // spurious errors.
2850 return false;
2851 }
2852 }
2853 }
2854 return true;
2855}
Ted Kremenek5739de72010-01-29 01:06:55 +00002856
Tom Careb49ec692010-06-17 19:00:27 +00002857void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002858 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002859 const analyze_printf::OptionalAmount &Amt,
2860 unsigned type,
2861 const char *startSpecifier,
2862 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002863 const analyze_printf::PrintfConversionSpecifier &CS =
2864 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002865
Richard Trieu03cf7b72011-10-28 00:41:25 +00002866 FixItHint fixit =
2867 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2868 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2869 Amt.getConstantLength()))
2870 : FixItHint();
2871
2872 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2873 << type << CS.toString(),
2874 getLocationOfByte(Amt.getStart()),
2875 /*IsStringLocation*/true,
2876 getSpecifierRange(startSpecifier, specifierLen),
2877 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002878}
2879
Ted Kremenek02087932010-07-16 02:11:22 +00002880void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002881 const analyze_printf::OptionalFlag &flag,
2882 const char *startSpecifier,
2883 unsigned specifierLen) {
2884 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002885 const analyze_printf::PrintfConversionSpecifier &CS =
2886 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002887 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2888 << flag.toString() << CS.toString(),
2889 getLocationOfByte(flag.getPosition()),
2890 /*IsStringLocation*/true,
2891 getSpecifierRange(startSpecifier, specifierLen),
2892 FixItHint::CreateRemoval(
2893 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002894}
2895
2896void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002897 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002898 const analyze_printf::OptionalFlag &ignoredFlag,
2899 const analyze_printf::OptionalFlag &flag,
2900 const char *startSpecifier,
2901 unsigned specifierLen) {
2902 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002903 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2904 << ignoredFlag.toString() << flag.toString(),
2905 getLocationOfByte(ignoredFlag.getPosition()),
2906 /*IsStringLocation*/true,
2907 getSpecifierRange(startSpecifier, specifierLen),
2908 FixItHint::CreateRemoval(
2909 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002910}
2911
Richard Smith55ce3522012-06-25 20:30:08 +00002912// Determines if the specified is a C++ class or struct containing
2913// a member with the specified name and kind (e.g. a CXXMethodDecl named
2914// "c_str()").
2915template<typename MemberKind>
2916static llvm::SmallPtrSet<MemberKind*, 1>
2917CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2918 const RecordType *RT = Ty->getAs<RecordType>();
2919 llvm::SmallPtrSet<MemberKind*, 1> Results;
2920
2921 if (!RT)
2922 return Results;
2923 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002924 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002925 return Results;
2926
2927 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2928 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002929 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002930
2931 // We just need to include all members of the right kind turned up by the
2932 // filter, at this point.
2933 if (S.LookupQualifiedName(R, RT->getDecl()))
2934 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2935 NamedDecl *decl = (*I)->getUnderlyingDecl();
2936 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2937 Results.insert(FK);
2938 }
2939 return Results;
2940}
2941
Richard Smith2868a732014-02-28 01:36:39 +00002942/// Check if we could call '.c_str()' on an object.
2943///
2944/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2945/// allow the call, or if it would be ambiguous).
2946bool Sema::hasCStrMethod(const Expr *E) {
2947 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2948 MethodSet Results =
2949 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2950 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2951 MI != ME; ++MI)
2952 if ((*MI)->getMinRequiredArguments() == 0)
2953 return true;
2954 return false;
2955}
2956
Richard Smith55ce3522012-06-25 20:30:08 +00002957// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002958// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002959// Returns true when a c_str() conversion method is found.
2960bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002961 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002962 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2963
2964 MethodSet Results =
2965 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2966
2967 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2968 MI != ME; ++MI) {
2969 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002970 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002971 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002972 // FIXME: Suggest parens if the expression needs them.
2973 SourceLocation EndLoc =
2974 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2975 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2976 << "c_str()"
2977 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2978 return true;
2979 }
2980 }
2981
2982 return false;
2983}
2984
Ted Kremenekab278de2010-01-28 23:39:18 +00002985bool
Ted Kremenek02087932010-07-16 02:11:22 +00002986CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002987 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002988 const char *startSpecifier,
2989 unsigned specifierLen) {
2990
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002991 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002992 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002993 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002994
Ted Kremenek6cd69422010-07-19 22:01:06 +00002995 if (FS.consumesDataArgument()) {
2996 if (atFirstArg) {
2997 atFirstArg = false;
2998 usesPositionalArgs = FS.usesPositionalArg();
2999 }
3000 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003001 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3002 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003003 return false;
3004 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003005 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003006
Ted Kremenekd1668192010-02-27 01:41:03 +00003007 // First check if the field width, precision, and conversion specifier
3008 // have matching data arguments.
3009 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3010 startSpecifier, specifierLen)) {
3011 return false;
3012 }
3013
3014 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3015 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003016 return false;
3017 }
3018
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003019 if (!CS.consumesDataArgument()) {
3020 // FIXME: Technically specifying a precision or field width here
3021 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003022 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003023 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003024
Ted Kremenek4a49d982010-02-26 19:18:41 +00003025 // Consume the argument.
3026 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003027 if (argIndex < NumDataArgs) {
3028 // The check to see if the argIndex is valid will come later.
3029 // We set the bit here because we may exit early from this
3030 // function if we encounter some other error.
3031 CoveredArgs.set(argIndex);
3032 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003033
3034 // Check for using an Objective-C specific conversion specifier
3035 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003036 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003037 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3038 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003039 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003040
Tom Careb49ec692010-06-17 19:00:27 +00003041 // Check for invalid use of field width
3042 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003043 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003044 startSpecifier, specifierLen);
3045 }
3046
3047 // Check for invalid use of precision
3048 if (!FS.hasValidPrecision()) {
3049 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3050 startSpecifier, specifierLen);
3051 }
3052
3053 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003054 if (!FS.hasValidThousandsGroupingPrefix())
3055 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003056 if (!FS.hasValidLeadingZeros())
3057 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3058 if (!FS.hasValidPlusPrefix())
3059 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003060 if (!FS.hasValidSpacePrefix())
3061 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003062 if (!FS.hasValidAlternativeForm())
3063 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3064 if (!FS.hasValidLeftJustified())
3065 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3066
3067 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003068 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3069 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3070 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003071 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3072 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3073 startSpecifier, specifierLen);
3074
3075 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003076 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003077 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3078 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003079 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003080 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003081 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003082 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3083 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003084
Jordan Rose92303592012-09-08 04:00:03 +00003085 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3086 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3087
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003088 // The remaining checks depend on the data arguments.
3089 if (HasVAListArg)
3090 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003091
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003092 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003093 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003094
Jordan Rose58bbe422012-07-19 18:10:08 +00003095 const Expr *Arg = getDataArg(argIndex);
3096 if (!Arg)
3097 return true;
3098
3099 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003100}
3101
Jordan Roseaee34382012-09-05 22:56:26 +00003102static bool requiresParensToAddCast(const Expr *E) {
3103 // FIXME: We should have a general way to reason about operator
3104 // precedence and whether parens are actually needed here.
3105 // Take care of a few common cases where they aren't.
3106 const Expr *Inside = E->IgnoreImpCasts();
3107 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3108 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3109
3110 switch (Inside->getStmtClass()) {
3111 case Stmt::ArraySubscriptExprClass:
3112 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003113 case Stmt::CharacterLiteralClass:
3114 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003115 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003116 case Stmt::FloatingLiteralClass:
3117 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003118 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003119 case Stmt::ObjCArrayLiteralClass:
3120 case Stmt::ObjCBoolLiteralExprClass:
3121 case Stmt::ObjCBoxedExprClass:
3122 case Stmt::ObjCDictionaryLiteralClass:
3123 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003124 case Stmt::ObjCIvarRefExprClass:
3125 case Stmt::ObjCMessageExprClass:
3126 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003127 case Stmt::ObjCStringLiteralClass:
3128 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003129 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003130 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003131 case Stmt::UnaryOperatorClass:
3132 return false;
3133 default:
3134 return true;
3135 }
3136}
3137
Richard Smith55ce3522012-06-25 20:30:08 +00003138bool
3139CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3140 const char *StartSpecifier,
3141 unsigned SpecifierLen,
3142 const Expr *E) {
3143 using namespace analyze_format_string;
3144 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003145 // Now type check the data expression that matches the
3146 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003147 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3148 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003149 if (!AT.isValid())
3150 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003151
Jordan Rose598ec092012-12-05 18:44:40 +00003152 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003153 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3154 ExprTy = TET->getUnderlyingExpr()->getType();
3155 }
3156
Jordan Rose598ec092012-12-05 18:44:40 +00003157 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003158 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003159
Jordan Rose22b74712012-09-05 22:56:19 +00003160 // Look through argument promotions for our error message's reported type.
3161 // This includes the integral and floating promotions, but excludes array
3162 // and function pointer decay; seeing that an argument intended to be a
3163 // string has type 'char [6]' is probably more confusing than 'char *'.
3164 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3165 if (ICE->getCastKind() == CK_IntegralCast ||
3166 ICE->getCastKind() == CK_FloatingCast) {
3167 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003168 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003169
3170 // Check if we didn't match because of an implicit cast from a 'char'
3171 // or 'short' to an 'int'. This is done because printf is a varargs
3172 // function.
3173 if (ICE->getType() == S.Context.IntTy ||
3174 ICE->getType() == S.Context.UnsignedIntTy) {
3175 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003176 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003177 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003178 }
Jordan Rose98709982012-06-04 22:48:57 +00003179 }
Jordan Rose598ec092012-12-05 18:44:40 +00003180 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3181 // Special case for 'a', which has type 'int' in C.
3182 // Note, however, that we do /not/ want to treat multibyte constants like
3183 // 'MooV' as characters! This form is deprecated but still exists.
3184 if (ExprTy == S.Context.IntTy)
3185 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3186 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003187 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003188
Jordan Rose0e5badd2012-12-05 18:44:49 +00003189 // %C in an Objective-C context prints a unichar, not a wchar_t.
3190 // If the argument is an integer of some kind, believe the %C and suggest
3191 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003192 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003193 if (ObjCContext &&
3194 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3195 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3196 !ExprTy->isCharType()) {
3197 // 'unichar' is defined as a typedef of unsigned short, but we should
3198 // prefer using the typedef if it is visible.
3199 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003200
3201 // While we are here, check if the value is an IntegerLiteral that happens
3202 // to be within the valid range.
3203 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3204 const llvm::APInt &V = IL->getValue();
3205 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3206 return true;
3207 }
3208
Jordan Rose0e5badd2012-12-05 18:44:49 +00003209 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3210 Sema::LookupOrdinaryName);
3211 if (S.LookupName(Result, S.getCurScope())) {
3212 NamedDecl *ND = Result.getFoundDecl();
3213 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3214 if (TD->getUnderlyingType() == IntendedTy)
3215 IntendedTy = S.Context.getTypedefType(TD);
3216 }
3217 }
3218 }
3219
3220 // Special-case some of Darwin's platform-independence types by suggesting
3221 // casts to primitive types that are known to be large enough.
3222 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003223 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003224 // Use a 'while' to peel off layers of typedefs.
3225 QualType TyTy = IntendedTy;
3226 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003227 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003228 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003229 .Case("NSInteger", S.Context.LongTy)
3230 .Case("NSUInteger", S.Context.UnsignedLongTy)
3231 .Case("SInt32", S.Context.IntTy)
3232 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003233 .Default(QualType());
3234
3235 if (!CastTy.isNull()) {
3236 ShouldNotPrintDirectly = true;
3237 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003238 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003239 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003240 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003241 }
3242 }
3243
Jordan Rose22b74712012-09-05 22:56:19 +00003244 // We may be able to offer a FixItHint if it is a supported type.
3245 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003246 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003247 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003248
Jordan Rose22b74712012-09-05 22:56:19 +00003249 if (success) {
3250 // Get the fix string from the fixed format specifier
3251 SmallString<16> buf;
3252 llvm::raw_svector_ostream os(buf);
3253 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003254
Jordan Roseaee34382012-09-05 22:56:26 +00003255 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3256
Jordan Rose0e5badd2012-12-05 18:44:49 +00003257 if (IntendedTy == ExprTy) {
3258 // In this case, the specifier is wrong and should be changed to match
3259 // the argument.
3260 EmitFormatDiagnostic(
3261 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3262 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3263 << E->getSourceRange(),
3264 E->getLocStart(),
3265 /*IsStringLocation*/false,
3266 SpecRange,
3267 FixItHint::CreateReplacement(SpecRange, os.str()));
3268
3269 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003270 // The canonical type for formatting this value is different from the
3271 // actual type of the expression. (This occurs, for example, with Darwin's
3272 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3273 // should be printed as 'long' for 64-bit compatibility.)
3274 // Rather than emitting a normal format/argument mismatch, we want to
3275 // add a cast to the recommended type (and correct the format string
3276 // if necessary).
3277 SmallString<16> CastBuf;
3278 llvm::raw_svector_ostream CastFix(CastBuf);
3279 CastFix << "(";
3280 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3281 CastFix << ")";
3282
3283 SmallVector<FixItHint,4> Hints;
3284 if (!AT.matchesType(S.Context, IntendedTy))
3285 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3286
3287 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3288 // If there's already a cast present, just replace it.
3289 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3290 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3291
3292 } else if (!requiresParensToAddCast(E)) {
3293 // If the expression has high enough precedence,
3294 // just write the C-style cast.
3295 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3296 CastFix.str()));
3297 } else {
3298 // Otherwise, add parens around the expression as well as the cast.
3299 CastFix << "(";
3300 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3301 CastFix.str()));
3302
3303 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3304 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3305 }
3306
Jordan Rose0e5badd2012-12-05 18:44:49 +00003307 if (ShouldNotPrintDirectly) {
3308 // The expression has a type that should not be printed directly.
3309 // We extract the name from the typedef because we don't want to show
3310 // the underlying type in the diagnostic.
3311 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003312
Jordan Rose0e5badd2012-12-05 18:44:49 +00003313 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3314 << Name << IntendedTy
3315 << E->getSourceRange(),
3316 E->getLocStart(), /*IsStringLocation=*/false,
3317 SpecRange, Hints);
3318 } else {
3319 // In this case, the expression could be printed using a different
3320 // specifier, but we've decided that the specifier is probably correct
3321 // and we should cast instead. Just use the normal warning message.
3322 EmitFormatDiagnostic(
3323 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3324 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3325 << E->getSourceRange(),
3326 E->getLocStart(), /*IsStringLocation*/false,
3327 SpecRange, Hints);
3328 }
Jordan Roseaee34382012-09-05 22:56:26 +00003329 }
Jordan Rose22b74712012-09-05 22:56:19 +00003330 } else {
3331 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3332 SpecifierLen);
3333 // Since the warning for passing non-POD types to variadic functions
3334 // was deferred until now, we emit a warning for non-POD
3335 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003336 switch (S.isValidVarArgType(ExprTy)) {
3337 case Sema::VAK_Valid:
3338 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003339 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003340 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3341 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3342 << CSR
3343 << E->getSourceRange(),
3344 E->getLocStart(), /*IsStringLocation*/false, CSR);
3345 break;
3346
3347 case Sema::VAK_Undefined:
3348 EmitFormatDiagnostic(
3349 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003350 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003351 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003352 << CallType
3353 << AT.getRepresentativeTypeName(S.Context)
3354 << CSR
3355 << E->getSourceRange(),
3356 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003357 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003358 break;
3359
3360 case Sema::VAK_Invalid:
3361 if (ExprTy->isObjCObjectType())
3362 EmitFormatDiagnostic(
3363 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3364 << S.getLangOpts().CPlusPlus11
3365 << ExprTy
3366 << CallType
3367 << AT.getRepresentativeTypeName(S.Context)
3368 << CSR
3369 << E->getSourceRange(),
3370 E->getLocStart(), /*IsStringLocation*/false, CSR);
3371 else
3372 // FIXME: If this is an initializer list, suggest removing the braces
3373 // or inserting a cast to the target type.
3374 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3375 << isa<InitListExpr>(E) << ExprTy << CallType
3376 << AT.getRepresentativeTypeName(S.Context)
3377 << E->getSourceRange();
3378 break;
3379 }
3380
3381 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3382 "format string specifier index out of range");
3383 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003384 }
3385
Ted Kremenekab278de2010-01-28 23:39:18 +00003386 return true;
3387}
3388
Ted Kremenek02087932010-07-16 02:11:22 +00003389//===--- CHECK: Scanf format string checking ------------------------------===//
3390
3391namespace {
3392class CheckScanfHandler : public CheckFormatHandler {
3393public:
3394 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3395 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003396 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003397 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003398 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003399 Sema::VariadicCallType CallType,
3400 llvm::SmallBitVector &CheckedVarArgs)
3401 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3402 numDataArgs, beg, hasVAListArg,
3403 Args, formatIdx, inFunctionCall, CallType,
3404 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003405 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003406
3407 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3408 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003409 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003410
3411 bool HandleInvalidScanfConversionSpecifier(
3412 const analyze_scanf::ScanfSpecifier &FS,
3413 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003414 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003415
Craig Toppere14c0f82014-03-12 04:55:44 +00003416 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003417};
Ted Kremenek019d2242010-01-29 01:50:07 +00003418}
Ted Kremenekab278de2010-01-28 23:39:18 +00003419
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003420void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3421 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003422 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3423 getLocationOfByte(end), /*IsStringLocation*/true,
3424 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003425}
3426
Ted Kremenekce815422010-07-19 21:25:57 +00003427bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3428 const analyze_scanf::ScanfSpecifier &FS,
3429 const char *startSpecifier,
3430 unsigned specifierLen) {
3431
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003432 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003433 FS.getConversionSpecifier();
3434
3435 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3436 getLocationOfByte(CS.getStart()),
3437 startSpecifier, specifierLen,
3438 CS.getStart(), CS.getLength());
3439}
3440
Ted Kremenek02087932010-07-16 02:11:22 +00003441bool CheckScanfHandler::HandleScanfSpecifier(
3442 const analyze_scanf::ScanfSpecifier &FS,
3443 const char *startSpecifier,
3444 unsigned specifierLen) {
3445
3446 using namespace analyze_scanf;
3447 using namespace analyze_format_string;
3448
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003449 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003450
Ted Kremenek6cd69422010-07-19 22:01:06 +00003451 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3452 // be used to decide if we are using positional arguments consistently.
3453 if (FS.consumesDataArgument()) {
3454 if (atFirstArg) {
3455 atFirstArg = false;
3456 usesPositionalArgs = FS.usesPositionalArg();
3457 }
3458 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003459 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3460 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003461 return false;
3462 }
Ted Kremenek02087932010-07-16 02:11:22 +00003463 }
3464
3465 // Check if the field with is non-zero.
3466 const OptionalAmount &Amt = FS.getFieldWidth();
3467 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3468 if (Amt.getConstantAmount() == 0) {
3469 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3470 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003471 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3472 getLocationOfByte(Amt.getStart()),
3473 /*IsStringLocation*/true, R,
3474 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003475 }
3476 }
3477
3478 if (!FS.consumesDataArgument()) {
3479 // FIXME: Technically specifying a precision or field width here
3480 // makes no sense. Worth issuing a warning at some point.
3481 return true;
3482 }
3483
3484 // Consume the argument.
3485 unsigned argIndex = FS.getArgIndex();
3486 if (argIndex < NumDataArgs) {
3487 // The check to see if the argIndex is valid will come later.
3488 // We set the bit here because we may exit early from this
3489 // function if we encounter some other error.
3490 CoveredArgs.set(argIndex);
3491 }
3492
Ted Kremenek4407ea42010-07-20 20:04:47 +00003493 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003494 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003495 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3496 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003497 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003498 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003499 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003500 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3501 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003502
Jordan Rose92303592012-09-08 04:00:03 +00003503 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3504 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3505
Ted Kremenek02087932010-07-16 02:11:22 +00003506 // The remaining checks depend on the data arguments.
3507 if (HasVAListArg)
3508 return true;
3509
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003510 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003511 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003512
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003513 // Check that the argument type matches the format specifier.
3514 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003515 if (!Ex)
3516 return true;
3517
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003518 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3519 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003520 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003521 bool success = fixedFS.fixType(Ex->getType(),
3522 Ex->IgnoreImpCasts()->getType(),
3523 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003524
3525 if (success) {
3526 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003527 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003528 llvm::raw_svector_ostream os(buf);
3529 fixedFS.toString(os);
3530
3531 EmitFormatDiagnostic(
3532 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003533 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003534 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003535 Ex->getLocStart(),
3536 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003537 getSpecifierRange(startSpecifier, specifierLen),
3538 FixItHint::CreateReplacement(
3539 getSpecifierRange(startSpecifier, specifierLen),
3540 os.str()));
3541 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003542 EmitFormatDiagnostic(
3543 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003544 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003545 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003546 Ex->getLocStart(),
3547 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003548 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003549 }
3550 }
3551
Ted Kremenek02087932010-07-16 02:11:22 +00003552 return true;
3553}
3554
3555void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003556 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003557 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003558 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003559 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003560 bool inFunctionCall, VariadicCallType CallType,
3561 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003562
Ted Kremenekab278de2010-01-28 23:39:18 +00003563 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003564 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003565 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003566 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003567 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3568 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003569 return;
3570 }
Ted Kremenek02087932010-07-16 02:11:22 +00003571
Ted Kremenekab278de2010-01-28 23:39:18 +00003572 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003573 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003574 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003575 // Account for cases where the string literal is truncated in a declaration.
3576 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3577 assert(T && "String literal not of constant array type!");
3578 size_t TypeSize = T->getSize().getZExtValue();
3579 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003580 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003581
3582 // Emit a warning if the string literal is truncated and does not contain an
3583 // embedded null character.
3584 if (TypeSize <= StrRef.size() &&
3585 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3586 CheckFormatHandler::EmitFormatDiagnostic(
3587 *this, inFunctionCall, Args[format_idx],
3588 PDiag(diag::warn_printf_format_string_not_null_terminated),
3589 FExpr->getLocStart(),
3590 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3591 return;
3592 }
3593
Ted Kremenekab278de2010-01-28 23:39:18 +00003594 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003595 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003596 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003597 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003598 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3599 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003600 return;
3601 }
Ted Kremenek02087932010-07-16 02:11:22 +00003602
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003603 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003604 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003605 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003606 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003607 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003608
Hans Wennborg23926bd2011-12-15 10:25:47 +00003609 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003610 getLangOpts(),
3611 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003612 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003613 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003614 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003615 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003616 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003617
Hans Wennborg23926bd2011-12-15 10:25:47 +00003618 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003619 getLangOpts(),
3620 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003621 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003622 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003623}
3624
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003625//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3626
3627// Returns the related absolute value function that is larger, of 0 if one
3628// does not exist.
3629static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3630 switch (AbsFunction) {
3631 default:
3632 return 0;
3633
3634 case Builtin::BI__builtin_abs:
3635 return Builtin::BI__builtin_labs;
3636 case Builtin::BI__builtin_labs:
3637 return Builtin::BI__builtin_llabs;
3638 case Builtin::BI__builtin_llabs:
3639 return 0;
3640
3641 case Builtin::BI__builtin_fabsf:
3642 return Builtin::BI__builtin_fabs;
3643 case Builtin::BI__builtin_fabs:
3644 return Builtin::BI__builtin_fabsl;
3645 case Builtin::BI__builtin_fabsl:
3646 return 0;
3647
3648 case Builtin::BI__builtin_cabsf:
3649 return Builtin::BI__builtin_cabs;
3650 case Builtin::BI__builtin_cabs:
3651 return Builtin::BI__builtin_cabsl;
3652 case Builtin::BI__builtin_cabsl:
3653 return 0;
3654
3655 case Builtin::BIabs:
3656 return Builtin::BIlabs;
3657 case Builtin::BIlabs:
3658 return Builtin::BIllabs;
3659 case Builtin::BIllabs:
3660 return 0;
3661
3662 case Builtin::BIfabsf:
3663 return Builtin::BIfabs;
3664 case Builtin::BIfabs:
3665 return Builtin::BIfabsl;
3666 case Builtin::BIfabsl:
3667 return 0;
3668
3669 case Builtin::BIcabsf:
3670 return Builtin::BIcabs;
3671 case Builtin::BIcabs:
3672 return Builtin::BIcabsl;
3673 case Builtin::BIcabsl:
3674 return 0;
3675 }
3676}
3677
3678// Returns the argument type of the absolute value function.
3679static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3680 unsigned AbsType) {
3681 if (AbsType == 0)
3682 return QualType();
3683
3684 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3685 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3686 if (Error != ASTContext::GE_None)
3687 return QualType();
3688
3689 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3690 if (!FT)
3691 return QualType();
3692
3693 if (FT->getNumParams() != 1)
3694 return QualType();
3695
3696 return FT->getParamType(0);
3697}
3698
3699// Returns the best absolute value function, or zero, based on type and
3700// current absolute value function.
3701static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3702 unsigned AbsFunctionKind) {
3703 unsigned BestKind = 0;
3704 uint64_t ArgSize = Context.getTypeSize(ArgType);
3705 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3706 Kind = getLargerAbsoluteValueFunction(Kind)) {
3707 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3708 if (Context.getTypeSize(ParamType) >= ArgSize) {
3709 if (BestKind == 0)
3710 BestKind = Kind;
3711 else if (Context.hasSameType(ParamType, ArgType)) {
3712 BestKind = Kind;
3713 break;
3714 }
3715 }
3716 }
3717 return BestKind;
3718}
3719
3720enum AbsoluteValueKind {
3721 AVK_Integer,
3722 AVK_Floating,
3723 AVK_Complex
3724};
3725
3726static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3727 if (T->isIntegralOrEnumerationType())
3728 return AVK_Integer;
3729 if (T->isRealFloatingType())
3730 return AVK_Floating;
3731 if (T->isAnyComplexType())
3732 return AVK_Complex;
3733
3734 llvm_unreachable("Type not integer, floating, or complex");
3735}
3736
3737// Changes the absolute value function to a different type. Preserves whether
3738// the function is a builtin.
3739static unsigned changeAbsFunction(unsigned AbsKind,
3740 AbsoluteValueKind ValueKind) {
3741 switch (ValueKind) {
3742 case AVK_Integer:
3743 switch (AbsKind) {
3744 default:
3745 return 0;
3746 case Builtin::BI__builtin_fabsf:
3747 case Builtin::BI__builtin_fabs:
3748 case Builtin::BI__builtin_fabsl:
3749 case Builtin::BI__builtin_cabsf:
3750 case Builtin::BI__builtin_cabs:
3751 case Builtin::BI__builtin_cabsl:
3752 return Builtin::BI__builtin_abs;
3753 case Builtin::BIfabsf:
3754 case Builtin::BIfabs:
3755 case Builtin::BIfabsl:
3756 case Builtin::BIcabsf:
3757 case Builtin::BIcabs:
3758 case Builtin::BIcabsl:
3759 return Builtin::BIabs;
3760 }
3761 case AVK_Floating:
3762 switch (AbsKind) {
3763 default:
3764 return 0;
3765 case Builtin::BI__builtin_abs:
3766 case Builtin::BI__builtin_labs:
3767 case Builtin::BI__builtin_llabs:
3768 case Builtin::BI__builtin_cabsf:
3769 case Builtin::BI__builtin_cabs:
3770 case Builtin::BI__builtin_cabsl:
3771 return Builtin::BI__builtin_fabsf;
3772 case Builtin::BIabs:
3773 case Builtin::BIlabs:
3774 case Builtin::BIllabs:
3775 case Builtin::BIcabsf:
3776 case Builtin::BIcabs:
3777 case Builtin::BIcabsl:
3778 return Builtin::BIfabsf;
3779 }
3780 case AVK_Complex:
3781 switch (AbsKind) {
3782 default:
3783 return 0;
3784 case Builtin::BI__builtin_abs:
3785 case Builtin::BI__builtin_labs:
3786 case Builtin::BI__builtin_llabs:
3787 case Builtin::BI__builtin_fabsf:
3788 case Builtin::BI__builtin_fabs:
3789 case Builtin::BI__builtin_fabsl:
3790 return Builtin::BI__builtin_cabsf;
3791 case Builtin::BIabs:
3792 case Builtin::BIlabs:
3793 case Builtin::BIllabs:
3794 case Builtin::BIfabsf:
3795 case Builtin::BIfabs:
3796 case Builtin::BIfabsl:
3797 return Builtin::BIcabsf;
3798 }
3799 }
3800 llvm_unreachable("Unable to convert function");
3801}
3802
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003803static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003804 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3805 if (!FnInfo)
3806 return 0;
3807
3808 switch (FDecl->getBuiltinID()) {
3809 default:
3810 return 0;
3811 case Builtin::BI__builtin_abs:
3812 case Builtin::BI__builtin_fabs:
3813 case Builtin::BI__builtin_fabsf:
3814 case Builtin::BI__builtin_fabsl:
3815 case Builtin::BI__builtin_labs:
3816 case Builtin::BI__builtin_llabs:
3817 case Builtin::BI__builtin_cabs:
3818 case Builtin::BI__builtin_cabsf:
3819 case Builtin::BI__builtin_cabsl:
3820 case Builtin::BIabs:
3821 case Builtin::BIlabs:
3822 case Builtin::BIllabs:
3823 case Builtin::BIfabs:
3824 case Builtin::BIfabsf:
3825 case Builtin::BIfabsl:
3826 case Builtin::BIcabs:
3827 case Builtin::BIcabsf:
3828 case Builtin::BIcabsl:
3829 return FDecl->getBuiltinID();
3830 }
3831 llvm_unreachable("Unknown Builtin type");
3832}
3833
3834// If the replacement is valid, emit a note with replacement function.
3835// Additionally, suggest including the proper header if not already included.
3836static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
3837 unsigned AbsKind) {
3838 std::string AbsName = S.Context.BuiltinInfo.GetName(AbsKind);
3839
3840 // Look up absolute value function in TU scope.
3841 DeclarationName DN(&S.Context.Idents.get(AbsName));
3842 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
Richard Trieufe771c02014-03-06 02:25:04 +00003843 R.suppressDiagnostics();
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003844 S.LookupName(R, S.TUScope);
3845
3846 // Skip notes if multiple results found in lookup.
3847 if (!R.empty() && !R.isSingleResult())
3848 return;
3849
3850 FunctionDecl *FD = 0;
3851 bool FoundFunction = R.isSingleResult();
3852 // When one result is found, see if it is the correct function.
3853 if (R.isSingleResult()) {
3854 FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3855 if (!FD || FD->getBuiltinID() != AbsKind)
3856 return;
3857 }
3858
3859 // Look for local name conflict, prepend "::" as necessary.
3860 R.clear();
3861 S.LookupName(R, S.getCurScope());
3862
3863 if (!FoundFunction) {
3864 if (!R.empty()) {
3865 AbsName = "::" + AbsName;
3866 }
3867 } else { // FoundFunction
3868 if (R.isSingleResult()) {
3869 if (R.getFoundDecl() != FD) {
3870 AbsName = "::" + AbsName;
3871 }
3872 } else if (!R.empty()) {
3873 AbsName = "::" + AbsName;
3874 }
3875 }
3876
3877 S.Diag(Loc, diag::note_replace_abs_function)
3878 << AbsName << FixItHint::CreateReplacement(Range, AbsName);
3879
3880 if (!FoundFunction) {
3881 S.Diag(Loc, diag::note_please_include_header)
3882 << S.Context.BuiltinInfo.getHeaderName(AbsKind)
3883 << S.Context.BuiltinInfo.GetName(AbsKind);
3884 }
3885}
3886
3887// Warn when using the wrong abs() function.
3888void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3889 const FunctionDecl *FDecl,
3890 IdentifierInfo *FnInfo) {
3891 if (Call->getNumArgs() != 1)
3892 return;
3893
3894 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
3895 if (AbsKind == 0)
3896 return;
3897
3898 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3899 QualType ParamType = Call->getArg(0)->getType();
3900
3901 // Unsigned types can not be negative. Suggest to drop the absolute value
3902 // function.
3903 if (ArgType->isUnsignedIntegerType()) {
3904 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3905 Diag(Call->getExprLoc(), diag::note_remove_abs)
3906 << FDecl
3907 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3908 return;
3909 }
3910
3911 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3912 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3913
3914 // The argument and parameter are the same kind. Check if they are the right
3915 // size.
3916 if (ArgValueKind == ParamValueKind) {
3917 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3918 return;
3919
3920 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3921 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3922 << FDecl << ArgType << ParamType;
3923
3924 if (NewAbsKind == 0)
3925 return;
3926
3927 emitReplacement(*this, Call->getExprLoc(),
3928 Call->getCallee()->getSourceRange(), NewAbsKind);
3929 return;
3930 }
3931
3932 // ArgValueKind != ParamValueKind
3933 // The wrong type of absolute value function was used. Attempt to find the
3934 // proper one.
3935 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3936 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3937 if (NewAbsKind == 0)
3938 return;
3939
3940 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3941 << FDecl << ParamValueKind << ArgValueKind;
3942
3943 emitReplacement(*this, Call->getExprLoc(),
3944 Call->getCallee()->getSourceRange(), NewAbsKind);
3945 return;
3946}
3947
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003948//===--- CHECK: Standard memory functions ---------------------------------===//
3949
Nico Weber0e6daef2013-12-26 23:38:39 +00003950/// \brief Takes the expression passed to the size_t parameter of functions
3951/// such as memcmp, strncat, etc and warns if it's a comparison.
3952///
3953/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3954static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3955 IdentifierInfo *FnName,
3956 SourceLocation FnLoc,
3957 SourceLocation RParenLoc) {
3958 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3959 if (!Size)
3960 return false;
3961
3962 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3963 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3964 return false;
3965
3966 Preprocessor &PP = S.getPreprocessor();
3967 SourceRange SizeRange = Size->getSourceRange();
3968 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3969 << SizeRange << FnName;
3970 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3971 << FnName
3972 << FixItHint::CreateInsertion(
3973 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3974 ")")
3975 << FixItHint::CreateRemoval(RParenLoc);
3976 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3977 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3978 << FixItHint::CreateInsertion(
3979 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3980
3981 return true;
3982}
3983
Douglas Gregora74926b2011-05-03 20:05:22 +00003984/// \brief Determine whether the given type is a dynamic class type (e.g.,
3985/// whether it has a vtable).
3986static bool isDynamicClassType(QualType T) {
3987 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3988 if (CXXRecordDecl *Definition = Record->getDefinition())
3989 if (Definition->isDynamicClass())
3990 return true;
3991
3992 return false;
3993}
3994
Chandler Carruth889ed862011-06-21 23:04:20 +00003995/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003996/// otherwise returns NULL.
3997static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003998 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003999 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4000 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4001 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004002
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004003 return 0;
4004}
4005
Chandler Carruth889ed862011-06-21 23:04:20 +00004006/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004007static QualType getSizeOfArgType(const Expr* E) {
4008 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4009 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4010 if (SizeOf->getKind() == clang::UETT_SizeOf)
4011 return SizeOf->getTypeOfArgument();
4012
4013 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004014}
4015
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004016/// \brief Check for dangerous or invalid arguments to memset().
4017///
Chandler Carruthac687262011-06-03 06:23:57 +00004018/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004019/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4020/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004021///
4022/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004023void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004024 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004025 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004026 assert(BId != 0);
4027
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004028 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004029 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004030 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004031 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004032 return;
4033
Anna Zaks22122702012-01-17 00:37:07 +00004034 unsigned LastArg = (BId == Builtin::BImemset ||
4035 BId == Builtin::BIstrndup ? 1 : 2);
4036 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004037 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004038
Nico Weber0e6daef2013-12-26 23:38:39 +00004039 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4040 Call->getLocStart(), Call->getRParenLoc()))
4041 return;
4042
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004043 // We have special checking when the length is a sizeof expression.
4044 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4045 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4046 llvm::FoldingSetNodeID SizeOfArgID;
4047
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004048 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4049 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004050 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004051
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004052 QualType DestTy = Dest->getType();
4053 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4054 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004055
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004056 // Never warn about void type pointers. This can be used to suppress
4057 // false positives.
4058 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004059 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004060
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004061 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4062 // actually comparing the expressions for equality. Because computing the
4063 // expression IDs can be expensive, we only do this if the diagnostic is
4064 // enabled.
4065 if (SizeOfArg &&
4066 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4067 SizeOfArg->getExprLoc())) {
4068 // We only compute IDs for expressions if the warning is enabled, and
4069 // cache the sizeof arg's ID.
4070 if (SizeOfArgID == llvm::FoldingSetNodeID())
4071 SizeOfArg->Profile(SizeOfArgID, Context, true);
4072 llvm::FoldingSetNodeID DestID;
4073 Dest->Profile(DestID, Context, true);
4074 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004075 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4076 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004077 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004078 StringRef ReadableName = FnName->getName();
4079
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004080 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004081 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004082 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004083 if (!PointeeTy->isIncompleteType() &&
4084 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004085 ActionIdx = 2; // If the pointee's size is sizeof(char),
4086 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004087
4088 // If the function is defined as a builtin macro, do not show macro
4089 // expansion.
4090 SourceLocation SL = SizeOfArg->getExprLoc();
4091 SourceRange DSR = Dest->getSourceRange();
4092 SourceRange SSR = SizeOfArg->getSourceRange();
4093 SourceManager &SM = PP.getSourceManager();
4094
4095 if (SM.isMacroArgExpansion(SL)) {
4096 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4097 SL = SM.getSpellingLoc(SL);
4098 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4099 SM.getSpellingLoc(DSR.getEnd()));
4100 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4101 SM.getSpellingLoc(SSR.getEnd()));
4102 }
4103
Anna Zaksd08d9152012-05-30 23:14:52 +00004104 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004105 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004106 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004107 << PointeeTy
4108 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004109 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004110 << SSR);
4111 DiagRuntimeBehavior(SL, SizeOfArg,
4112 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4113 << ActionIdx
4114 << SSR);
4115
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004116 break;
4117 }
4118 }
4119
4120 // Also check for cases where the sizeof argument is the exact same
4121 // type as the memory argument, and where it points to a user-defined
4122 // record type.
4123 if (SizeOfArgTy != QualType()) {
4124 if (PointeeTy->isRecordType() &&
4125 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4126 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4127 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4128 << FnName << SizeOfArgTy << ArgIdx
4129 << PointeeTy << Dest->getSourceRange()
4130 << LenExpr->getSourceRange());
4131 break;
4132 }
Nico Weberc5e73862011-06-14 16:14:58 +00004133 }
4134
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004135 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00004136 if (isDynamicClassType(PointeeTy)) {
4137
4138 unsigned OperationType = 0;
4139 // "overwritten" if we're warning about the destination for any call
4140 // but memcmp; otherwise a verb appropriate to the call.
4141 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4142 if (BId == Builtin::BImemcpy)
4143 OperationType = 1;
4144 else if(BId == Builtin::BImemmove)
4145 OperationType = 2;
4146 else if (BId == Builtin::BImemcmp)
4147 OperationType = 3;
4148 }
4149
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004150 DiagRuntimeBehavior(
4151 Dest->getExprLoc(), Dest,
4152 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004153 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00004154 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00004155 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004156 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004157 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4158 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004159 DiagRuntimeBehavior(
4160 Dest->getExprLoc(), Dest,
4161 PDiag(diag::warn_arc_object_memaccess)
4162 << ArgIdx << FnName << PointeeTy
4163 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004164 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004165 continue;
John McCall31168b02011-06-15 23:02:42 +00004166
4167 DiagRuntimeBehavior(
4168 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004169 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004170 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4171 break;
4172 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004173 }
4174}
4175
Ted Kremenek6865f772011-08-18 20:55:45 +00004176// A little helper routine: ignore addition and subtraction of integer literals.
4177// This intentionally does not ignore all integer constant expressions because
4178// we don't want to remove sizeof().
4179static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4180 Ex = Ex->IgnoreParenCasts();
4181
4182 for (;;) {
4183 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4184 if (!BO || !BO->isAdditiveOp())
4185 break;
4186
4187 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4188 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4189
4190 if (isa<IntegerLiteral>(RHS))
4191 Ex = LHS;
4192 else if (isa<IntegerLiteral>(LHS))
4193 Ex = RHS;
4194 else
4195 break;
4196 }
4197
4198 return Ex;
4199}
4200
Anna Zaks13b08572012-08-08 21:42:23 +00004201static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4202 ASTContext &Context) {
4203 // Only handle constant-sized or VLAs, but not flexible members.
4204 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4205 // Only issue the FIXIT for arrays of size > 1.
4206 if (CAT->getSize().getSExtValue() <= 1)
4207 return false;
4208 } else if (!Ty->isVariableArrayType()) {
4209 return false;
4210 }
4211 return true;
4212}
4213
Ted Kremenek6865f772011-08-18 20:55:45 +00004214// Warn if the user has made the 'size' argument to strlcpy or strlcat
4215// be the size of the source, instead of the destination.
4216void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4217 IdentifierInfo *FnName) {
4218
4219 // Don't crash if the user has the wrong number of arguments
4220 if (Call->getNumArgs() != 3)
4221 return;
4222
4223 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4224 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4225 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00004226
4227 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4228 Call->getLocStart(), Call->getRParenLoc()))
4229 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004230
4231 // Look for 'strlcpy(dst, x, sizeof(x))'
4232 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4233 CompareWithSrc = Ex;
4234 else {
4235 // Look for 'strlcpy(dst, x, strlen(x))'
4236 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004237 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4238 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004239 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4240 }
4241 }
4242
4243 if (!CompareWithSrc)
4244 return;
4245
4246 // Determine if the argument to sizeof/strlen is equal to the source
4247 // argument. In principle there's all kinds of things you could do
4248 // here, for instance creating an == expression and evaluating it with
4249 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4250 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4251 if (!SrcArgDRE)
4252 return;
4253
4254 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4255 if (!CompareWithSrcDRE ||
4256 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4257 return;
4258
4259 const Expr *OriginalSizeArg = Call->getArg(2);
4260 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4261 << OriginalSizeArg->getSourceRange() << FnName;
4262
4263 // Output a FIXIT hint if the destination is an array (rather than a
4264 // pointer to an array). This could be enhanced to handle some
4265 // pointers if we know the actual size, like if DstArg is 'array+2'
4266 // we could say 'sizeof(array)-2'.
4267 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004268 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004269 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004270
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004271 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004272 llvm::raw_svector_ostream OS(sizeString);
4273 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004274 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004275 OS << ")";
4276
4277 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4278 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4279 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004280}
4281
Anna Zaks314cd092012-02-01 19:08:57 +00004282/// Check if two expressions refer to the same declaration.
4283static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4284 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4285 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4286 return D1->getDecl() == D2->getDecl();
4287 return false;
4288}
4289
4290static const Expr *getStrlenExprArg(const Expr *E) {
4291 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4292 const FunctionDecl *FD = CE->getDirectCallee();
4293 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4294 return 0;
4295 return CE->getArg(0)->IgnoreParenCasts();
4296 }
4297 return 0;
4298}
4299
4300// Warn on anti-patterns as the 'size' argument to strncat.
4301// The correct size argument should look like following:
4302// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4303void Sema::CheckStrncatArguments(const CallExpr *CE,
4304 IdentifierInfo *FnName) {
4305 // Don't crash if the user has the wrong number of arguments.
4306 if (CE->getNumArgs() < 3)
4307 return;
4308 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4309 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4310 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4311
Nico Weber0e6daef2013-12-26 23:38:39 +00004312 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4313 CE->getRParenLoc()))
4314 return;
4315
Anna Zaks314cd092012-02-01 19:08:57 +00004316 // Identify common expressions, which are wrongly used as the size argument
4317 // to strncat and may lead to buffer overflows.
4318 unsigned PatternType = 0;
4319 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4320 // - sizeof(dst)
4321 if (referToTheSameDecl(SizeOfArg, DstArg))
4322 PatternType = 1;
4323 // - sizeof(src)
4324 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4325 PatternType = 2;
4326 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4327 if (BE->getOpcode() == BO_Sub) {
4328 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4329 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4330 // - sizeof(dst) - strlen(dst)
4331 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4332 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4333 PatternType = 1;
4334 // - sizeof(src) - (anything)
4335 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4336 PatternType = 2;
4337 }
4338 }
4339
4340 if (PatternType == 0)
4341 return;
4342
Anna Zaks5069aa32012-02-03 01:27:37 +00004343 // Generate the diagnostic.
4344 SourceLocation SL = LenArg->getLocStart();
4345 SourceRange SR = LenArg->getSourceRange();
4346 SourceManager &SM = PP.getSourceManager();
4347
4348 // If the function is defined as a builtin macro, do not show macro expansion.
4349 if (SM.isMacroArgExpansion(SL)) {
4350 SL = SM.getSpellingLoc(SL);
4351 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4352 SM.getSpellingLoc(SR.getEnd()));
4353 }
4354
Anna Zaks13b08572012-08-08 21:42:23 +00004355 // Check if the destination is an array (rather than a pointer to an array).
4356 QualType DstTy = DstArg->getType();
4357 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4358 Context);
4359 if (!isKnownSizeArray) {
4360 if (PatternType == 1)
4361 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4362 else
4363 Diag(SL, diag::warn_strncat_src_size) << SR;
4364 return;
4365 }
4366
Anna Zaks314cd092012-02-01 19:08:57 +00004367 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004368 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004369 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004370 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004371
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004372 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004373 llvm::raw_svector_ostream OS(sizeString);
4374 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004375 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004376 OS << ") - ";
4377 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00004378 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004379 OS << ") - 1";
4380
Anna Zaks5069aa32012-02-03 01:27:37 +00004381 Diag(SL, diag::note_strncat_wrong_size)
4382 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004383}
4384
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004385//===--- CHECK: Return Address of Stack Variable --------------------------===//
4386
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004387static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4388 Decl *ParentDecl);
4389static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4390 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004391
4392/// CheckReturnStackAddr - Check if a return statement returns the address
4393/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004394static void
4395CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4396 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004397
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004398 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004399 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004400
4401 // Perform checking for returned stack addresses, local blocks,
4402 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004403 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004404 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004405 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004406 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004407 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004408 }
4409
4410 if (stackE == 0)
4411 return; // Nothing suspicious was found.
4412
4413 SourceLocation diagLoc;
4414 SourceRange diagRange;
4415 if (refVars.empty()) {
4416 diagLoc = stackE->getLocStart();
4417 diagRange = stackE->getSourceRange();
4418 } else {
4419 // We followed through a reference variable. 'stackE' contains the
4420 // problematic expression but we will warn at the return statement pointing
4421 // at the reference variable. We will later display the "trail" of
4422 // reference variables using notes.
4423 diagLoc = refVars[0]->getLocStart();
4424 diagRange = refVars[0]->getSourceRange();
4425 }
4426
4427 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004428 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004429 : diag::warn_ret_stack_addr)
4430 << DR->getDecl()->getDeclName() << diagRange;
4431 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004432 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004433 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004434 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004435 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004436 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4437 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004438 << diagRange;
4439 }
4440
4441 // Display the "trail" of reference variables that we followed until we
4442 // found the problematic expression using notes.
4443 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4444 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4445 // If this var binds to another reference var, show the range of the next
4446 // var, otherwise the var binds to the problematic expression, in which case
4447 // show the range of the expression.
4448 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4449 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004450 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4451 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004452 }
4453}
4454
4455/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4456/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004457/// to a location on the stack, a local block, an address of a label, or a
4458/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004459/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004460/// encounter a subexpression that (1) clearly does not lead to one of the
4461/// above problematic expressions (2) is something we cannot determine leads to
4462/// a problematic expression based on such local checking.
4463///
4464/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4465/// the expression that they point to. Such variables are added to the
4466/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004467///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004468/// EvalAddr processes expressions that are pointers that are used as
4469/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004470/// At the base case of the recursion is a check for the above problematic
4471/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004472///
4473/// This implementation handles:
4474///
4475/// * pointer-to-pointer casts
4476/// * implicit conversions from array references to pointers
4477/// * taking the address of fields
4478/// * arbitrary interplay between "&" and "*" operators
4479/// * pointer arithmetic from an address of a stack variable
4480/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004481static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4482 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004483 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004484 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004485
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004486 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004487 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004488 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004489 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004490 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004491
Peter Collingbourne91147592011-04-15 00:35:48 +00004492 E = E->IgnoreParens();
4493
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004494 // Our "symbolic interpreter" is just a dispatch off the currently
4495 // viewed AST node. We then recursively traverse the AST by calling
4496 // EvalAddr and EvalVal appropriately.
4497 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004498 case Stmt::DeclRefExprClass: {
4499 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4500
Richard Smith40f08eb2014-01-30 22:05:38 +00004501 // If we leave the immediate function, the lifetime isn't about to end.
4502 if (DR->refersToEnclosingLocal())
4503 return 0;
4504
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004505 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4506 // If this is a reference variable, follow through to the expression that
4507 // it points to.
4508 if (V->hasLocalStorage() &&
4509 V->getType()->isReferenceType() && V->hasInit()) {
4510 // Add the reference variable to the "trail".
4511 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004512 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004513 }
4514
4515 return NULL;
4516 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004517
Chris Lattner934edb22007-12-28 05:31:15 +00004518 case Stmt::UnaryOperatorClass: {
4519 // The only unary operator that make sense to handle here
4520 // is AddrOf. All others don't make sense as pointers.
4521 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004522
John McCalle3027922010-08-25 11:45:40 +00004523 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004524 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004525 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004526 return NULL;
4527 }
Mike Stump11289f42009-09-09 15:08:12 +00004528
Chris Lattner934edb22007-12-28 05:31:15 +00004529 case Stmt::BinaryOperatorClass: {
4530 // Handle pointer arithmetic. All other binary operators are not valid
4531 // in this context.
4532 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004533 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004534
John McCalle3027922010-08-25 11:45:40 +00004535 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004536 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004537
Chris Lattner934edb22007-12-28 05:31:15 +00004538 Expr *Base = B->getLHS();
4539
4540 // Determine which argument is the real pointer base. It could be
4541 // the RHS argument instead of the LHS.
4542 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004543
Chris Lattner934edb22007-12-28 05:31:15 +00004544 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004545 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004546 }
Steve Naroff2752a172008-09-10 19:17:48 +00004547
Chris Lattner934edb22007-12-28 05:31:15 +00004548 // For conditional operators we need to see if either the LHS or RHS are
4549 // valid DeclRefExpr*s. If one of them is valid, we return it.
4550 case Stmt::ConditionalOperatorClass: {
4551 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004552
Chris Lattner934edb22007-12-28 05:31:15 +00004553 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004554 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4555 if (Expr *LHSExpr = C->getLHS()) {
4556 // In C++, we can have a throw-expression, which has 'void' type.
4557 if (!LHSExpr->getType()->isVoidType())
4558 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004559 return LHS;
4560 }
Chris Lattner934edb22007-12-28 05:31:15 +00004561
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004562 // In C++, we can have a throw-expression, which has 'void' type.
4563 if (C->getRHS()->getType()->isVoidType())
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004564 return 0;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004565
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004566 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004567 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004568
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004569 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004570 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004571 return E; // local block.
4572 return NULL;
4573
4574 case Stmt::AddrLabelExprClass:
4575 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004576
John McCall28fc7092011-11-10 05:35:25 +00004577 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004578 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4579 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004580
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004581 // For casts, we need to handle conversions from arrays to
4582 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004583 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004584 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004585 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004586 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004587 case Stmt::CXXStaticCastExprClass:
4588 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004589 case Stmt::CXXConstCastExprClass:
4590 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004591 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4592 switch (cast<CastExpr>(E)->getCastKind()) {
4593 case CK_BitCast:
4594 case CK_LValueToRValue:
4595 case CK_NoOp:
4596 case CK_BaseToDerived:
4597 case CK_DerivedToBase:
4598 case CK_UncheckedDerivedToBase:
4599 case CK_Dynamic:
4600 case CK_CPointerToObjCPointerCast:
4601 case CK_BlockPointerToObjCPointerCast:
4602 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004603 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004604
4605 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004606 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004607
4608 default:
4609 return 0;
4610 }
Chris Lattner934edb22007-12-28 05:31:15 +00004611 }
Mike Stump11289f42009-09-09 15:08:12 +00004612
Douglas Gregorfe314812011-06-21 17:03:29 +00004613 case Stmt::MaterializeTemporaryExprClass:
4614 if (Expr *Result = EvalAddr(
4615 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004616 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004617 return Result;
4618
4619 return E;
4620
Chris Lattner934edb22007-12-28 05:31:15 +00004621 // Everything else: we simply don't reason about them.
4622 default:
4623 return NULL;
4624 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004625}
Mike Stump11289f42009-09-09 15:08:12 +00004626
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004627
4628/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4629/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004630static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4631 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004632do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004633 // We should only be called for evaluating non-pointer expressions, or
4634 // expressions with a pointer type that are not used as references but instead
4635 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004636
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004637 // Our "symbolic interpreter" is just a dispatch off the currently
4638 // viewed AST node. We then recursively traverse the AST by calling
4639 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004640
4641 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004642 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004643 case Stmt::ImplicitCastExprClass: {
4644 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004645 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004646 E = IE->getSubExpr();
4647 continue;
4648 }
4649 return NULL;
4650 }
4651
John McCall28fc7092011-11-10 05:35:25 +00004652 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004653 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004654
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004655 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004656 // When we hit a DeclRefExpr we are looking at code that refers to a
4657 // variable's name. If it's not a reference variable we check if it has
4658 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004659 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004660
Richard Smith40f08eb2014-01-30 22:05:38 +00004661 // If we leave the immediate function, the lifetime isn't about to end.
4662 if (DR->refersToEnclosingLocal())
4663 return 0;
4664
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004665 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4666 // Check if it refers to itself, e.g. "int& i = i;".
4667 if (V == ParentDecl)
4668 return DR;
4669
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004670 if (V->hasLocalStorage()) {
4671 if (!V->getType()->isReferenceType())
4672 return DR;
4673
4674 // Reference variable, follow through to the expression that
4675 // it points to.
4676 if (V->hasInit()) {
4677 // Add the reference variable to the "trail".
4678 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004679 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004680 }
4681 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004682 }
Mike Stump11289f42009-09-09 15:08:12 +00004683
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004684 return NULL;
4685 }
Mike Stump11289f42009-09-09 15:08:12 +00004686
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004687 case Stmt::UnaryOperatorClass: {
4688 // The only unary operator that make sense to handle here
4689 // is Deref. All others don't resolve to a "name." This includes
4690 // handling all sorts of rvalues passed to a unary operator.
4691 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004692
John McCalle3027922010-08-25 11:45:40 +00004693 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004694 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004695
4696 return NULL;
4697 }
Mike Stump11289f42009-09-09 15:08:12 +00004698
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004699 case Stmt::ArraySubscriptExprClass: {
4700 // Array subscripts are potential references to data on the stack. We
4701 // retrieve the DeclRefExpr* for the array variable if it indeed
4702 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004703 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004704 }
Mike Stump11289f42009-09-09 15:08:12 +00004705
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004706 case Stmt::ConditionalOperatorClass: {
4707 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004708 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004709 ConditionalOperator *C = cast<ConditionalOperator>(E);
4710
Anders Carlsson801c5c72007-11-30 19:04:31 +00004711 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004712 if (Expr *LHSExpr = C->getLHS()) {
4713 // In C++, we can have a throw-expression, which has 'void' type.
4714 if (!LHSExpr->getType()->isVoidType())
4715 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4716 return LHS;
4717 }
4718
4719 // In C++, we can have a throw-expression, which has 'void' type.
4720 if (C->getRHS()->getType()->isVoidType())
4721 return 0;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004722
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004723 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004724 }
Mike Stump11289f42009-09-09 15:08:12 +00004725
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004726 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004727 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004728 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004729
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004730 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004731 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004732 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004733
4734 // Check whether the member type is itself a reference, in which case
4735 // we're not going to refer to the member, but to what the member refers to.
4736 if (M->getMemberDecl()->getType()->isReferenceType())
4737 return NULL;
4738
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004739 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004740 }
Mike Stump11289f42009-09-09 15:08:12 +00004741
Douglas Gregorfe314812011-06-21 17:03:29 +00004742 case Stmt::MaterializeTemporaryExprClass:
4743 if (Expr *Result = EvalVal(
4744 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004745 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004746 return Result;
4747
4748 return E;
4749
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004750 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004751 // Check that we don't return or take the address of a reference to a
4752 // temporary. This is only useful in C++.
4753 if (!E->isTypeDependent() && E->isRValue())
4754 return E;
4755
4756 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004757 return NULL;
4758 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004759} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004760}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004761
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004762void
4763Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4764 SourceLocation ReturnLoc,
4765 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004766 const AttrVec *Attrs,
4767 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004768 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4769
4770 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004771 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4772 CheckNonNullExpr(*this, RetValExp))
4773 Diag(ReturnLoc, diag::warn_null_ret)
4774 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004775
4776 // C++11 [basic.stc.dynamic.allocation]p4:
4777 // If an allocation function declared with a non-throwing
4778 // exception-specification fails to allocate storage, it shall return
4779 // a null pointer. Any other allocation function that fails to allocate
4780 // storage shall indicate failure only by throwing an exception [...]
4781 if (FD) {
4782 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4783 if (Op == OO_New || Op == OO_Array_New) {
4784 const FunctionProtoType *Proto
4785 = FD->getType()->castAs<FunctionProtoType>();
4786 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4787 CheckNonNullExpr(*this, RetValExp))
4788 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4789 << FD << getLangOpts().CPlusPlus11;
4790 }
4791 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004792}
4793
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004794//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4795
4796/// Check for comparisons of floating point operands using != and ==.
4797/// Issue a warning if these are no self-comparisons, as they are not likely
4798/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004799void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004800 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4801 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004802
4803 // Special case: check for x == x (which is OK).
4804 // Do not emit warnings for such cases.
4805 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4806 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4807 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004808 return;
Mike Stump11289f42009-09-09 15:08:12 +00004809
4810
Ted Kremenekeda40e22007-11-29 00:59:04 +00004811 // Special case: check for comparisons against literals that can be exactly
4812 // represented by APFloat. In such cases, do not emit a warning. This
4813 // is a heuristic: often comparison against such literals are used to
4814 // detect if a value in a variable has not changed. This clearly can
4815 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004816 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4817 if (FLL->isExact())
4818 return;
4819 } else
4820 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4821 if (FLR->isExact())
4822 return;
Mike Stump11289f42009-09-09 15:08:12 +00004823
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004824 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004825 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004826 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004827 return;
Mike Stump11289f42009-09-09 15:08:12 +00004828
David Blaikie1f4ff152012-07-16 20:47:22 +00004829 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004830 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004831 return;
Mike Stump11289f42009-09-09 15:08:12 +00004832
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004833 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004834 Diag(Loc, diag::warn_floatingpoint_eq)
4835 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004836}
John McCallca01b222010-01-04 23:21:16 +00004837
John McCall70aa5392010-01-06 05:24:50 +00004838//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4839//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004840
John McCall70aa5392010-01-06 05:24:50 +00004841namespace {
John McCallca01b222010-01-04 23:21:16 +00004842
John McCall70aa5392010-01-06 05:24:50 +00004843/// Structure recording the 'active' range of an integer-valued
4844/// expression.
4845struct IntRange {
4846 /// The number of bits active in the int.
4847 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004848
John McCall70aa5392010-01-06 05:24:50 +00004849 /// True if the int is known not to have negative values.
4850 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004851
John McCall70aa5392010-01-06 05:24:50 +00004852 IntRange(unsigned Width, bool NonNegative)
4853 : Width(Width), NonNegative(NonNegative)
4854 {}
John McCallca01b222010-01-04 23:21:16 +00004855
John McCall817d4af2010-11-10 23:38:19 +00004856 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004857 static IntRange forBoolType() {
4858 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004859 }
4860
John McCall817d4af2010-11-10 23:38:19 +00004861 /// Returns the range of an opaque value of the given integral type.
4862 static IntRange forValueOfType(ASTContext &C, QualType T) {
4863 return forValueOfCanonicalType(C,
4864 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004865 }
4866
John McCall817d4af2010-11-10 23:38:19 +00004867 /// Returns the range of an opaque value of a canonical integral type.
4868 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004869 assert(T->isCanonicalUnqualified());
4870
4871 if (const VectorType *VT = dyn_cast<VectorType>(T))
4872 T = VT->getElementType().getTypePtr();
4873 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4874 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004875
David Majnemer6a426652013-06-07 22:07:20 +00004876 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004877 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004878 EnumDecl *Enum = ET->getDecl();
4879 if (!Enum->isCompleteDefinition())
4880 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004881
David Majnemer6a426652013-06-07 22:07:20 +00004882 unsigned NumPositive = Enum->getNumPositiveBits();
4883 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004884
David Majnemer6a426652013-06-07 22:07:20 +00004885 if (NumNegative == 0)
4886 return IntRange(NumPositive, true/*NonNegative*/);
4887 else
4888 return IntRange(std::max(NumPositive + 1, NumNegative),
4889 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004890 }
John McCall70aa5392010-01-06 05:24:50 +00004891
4892 const BuiltinType *BT = cast<BuiltinType>(T);
4893 assert(BT->isInteger());
4894
4895 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4896 }
4897
John McCall817d4af2010-11-10 23:38:19 +00004898 /// Returns the "target" range of a canonical integral type, i.e.
4899 /// the range of values expressible in the type.
4900 ///
4901 /// This matches forValueOfCanonicalType except that enums have the
4902 /// full range of their type, not the range of their enumerators.
4903 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4904 assert(T->isCanonicalUnqualified());
4905
4906 if (const VectorType *VT = dyn_cast<VectorType>(T))
4907 T = VT->getElementType().getTypePtr();
4908 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4909 T = CT->getElementType().getTypePtr();
4910 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004911 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004912
4913 const BuiltinType *BT = cast<BuiltinType>(T);
4914 assert(BT->isInteger());
4915
4916 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4917 }
4918
4919 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004920 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004921 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004922 L.NonNegative && R.NonNegative);
4923 }
4924
John McCall817d4af2010-11-10 23:38:19 +00004925 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004926 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004927 return IntRange(std::min(L.Width, R.Width),
4928 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004929 }
4930};
4931
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004932static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4933 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004934 if (value.isSigned() && value.isNegative())
4935 return IntRange(value.getMinSignedBits(), false);
4936
4937 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004938 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004939
4940 // isNonNegative() just checks the sign bit without considering
4941 // signedness.
4942 return IntRange(value.getActiveBits(), true);
4943}
4944
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004945static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4946 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004947 if (result.isInt())
4948 return GetValueRange(C, result.getInt(), MaxWidth);
4949
4950 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004951 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4952 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4953 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4954 R = IntRange::join(R, El);
4955 }
John McCall70aa5392010-01-06 05:24:50 +00004956 return R;
4957 }
4958
4959 if (result.isComplexInt()) {
4960 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4961 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4962 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004963 }
4964
4965 // This can happen with lossless casts to intptr_t of "based" lvalues.
4966 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004967 // FIXME: The only reason we need to pass the type in here is to get
4968 // the sign right on this one case. It would be nice if APValue
4969 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004970 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004971 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004972}
John McCall70aa5392010-01-06 05:24:50 +00004973
Eli Friedmane6d33952013-07-08 20:20:06 +00004974static QualType GetExprType(Expr *E) {
4975 QualType Ty = E->getType();
4976 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4977 Ty = AtomicRHS->getValueType();
4978 return Ty;
4979}
4980
John McCall70aa5392010-01-06 05:24:50 +00004981/// Pseudo-evaluate the given integer expression, estimating the
4982/// range of values it might take.
4983///
4984/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004985static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004986 E = E->IgnoreParens();
4987
4988 // Try a full evaluation first.
4989 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004990 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004991 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004992
4993 // I think we only want to look through implicit casts here; if the
4994 // user has an explicit widening cast, we should treat the value as
4995 // being of the new, wider type.
4996 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004997 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004998 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4999
Eli Friedmane6d33952013-07-08 20:20:06 +00005000 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005001
John McCalle3027922010-08-25 11:45:40 +00005002 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005003
John McCall70aa5392010-01-06 05:24:50 +00005004 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005005 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005006 return OutputTypeRange;
5007
5008 IntRange SubRange
5009 = GetExprRange(C, CE->getSubExpr(),
5010 std::min(MaxWidth, OutputTypeRange.Width));
5011
5012 // Bail out if the subexpr's range is as wide as the cast type.
5013 if (SubRange.Width >= OutputTypeRange.Width)
5014 return OutputTypeRange;
5015
5016 // Otherwise, we take the smaller width, and we're non-negative if
5017 // either the output type or the subexpr is.
5018 return IntRange(SubRange.Width,
5019 SubRange.NonNegative || OutputTypeRange.NonNegative);
5020 }
5021
5022 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5023 // If we can fold the condition, just take that operand.
5024 bool CondResult;
5025 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5026 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5027 : CO->getFalseExpr(),
5028 MaxWidth);
5029
5030 // Otherwise, conservatively merge.
5031 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5032 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5033 return IntRange::join(L, R);
5034 }
5035
5036 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5037 switch (BO->getOpcode()) {
5038
5039 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005040 case BO_LAnd:
5041 case BO_LOr:
5042 case BO_LT:
5043 case BO_GT:
5044 case BO_LE:
5045 case BO_GE:
5046 case BO_EQ:
5047 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005048 return IntRange::forBoolType();
5049
John McCallc3688382011-07-13 06:35:24 +00005050 // The type of the assignments is the type of the LHS, so the RHS
5051 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005052 case BO_MulAssign:
5053 case BO_DivAssign:
5054 case BO_RemAssign:
5055 case BO_AddAssign:
5056 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005057 case BO_XorAssign:
5058 case BO_OrAssign:
5059 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005060 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005061
John McCallc3688382011-07-13 06:35:24 +00005062 // Simple assignments just pass through the RHS, which will have
5063 // been coerced to the LHS type.
5064 case BO_Assign:
5065 // TODO: bitfields?
5066 return GetExprRange(C, BO->getRHS(), MaxWidth);
5067
John McCall70aa5392010-01-06 05:24:50 +00005068 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005069 case BO_PtrMemD:
5070 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005071 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005072
John McCall2ce81ad2010-01-06 22:07:33 +00005073 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005074 case BO_And:
5075 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005076 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5077 GetExprRange(C, BO->getRHS(), MaxWidth));
5078
John McCall70aa5392010-01-06 05:24:50 +00005079 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005080 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005081 // ...except that we want to treat '1 << (blah)' as logically
5082 // positive. It's an important idiom.
5083 if (IntegerLiteral *I
5084 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5085 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005086 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005087 return IntRange(R.Width, /*NonNegative*/ true);
5088 }
5089 }
5090 // fallthrough
5091
John McCalle3027922010-08-25 11:45:40 +00005092 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005093 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005094
John McCall2ce81ad2010-01-06 22:07:33 +00005095 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005096 case BO_Shr:
5097 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005098 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5099
5100 // If the shift amount is a positive constant, drop the width by
5101 // that much.
5102 llvm::APSInt shift;
5103 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5104 shift.isNonNegative()) {
5105 unsigned zext = shift.getZExtValue();
5106 if (zext >= L.Width)
5107 L.Width = (L.NonNegative ? 0 : 1);
5108 else
5109 L.Width -= zext;
5110 }
5111
5112 return L;
5113 }
5114
5115 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005116 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005117 return GetExprRange(C, BO->getRHS(), MaxWidth);
5118
John McCall2ce81ad2010-01-06 22:07:33 +00005119 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005120 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005121 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005122 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005123 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005124
John McCall51431812011-07-14 22:39:48 +00005125 // The width of a division result is mostly determined by the size
5126 // of the LHS.
5127 case BO_Div: {
5128 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005129 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005130 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5131
5132 // If the divisor is constant, use that.
5133 llvm::APSInt divisor;
5134 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5135 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5136 if (log2 >= L.Width)
5137 L.Width = (L.NonNegative ? 0 : 1);
5138 else
5139 L.Width = std::min(L.Width - log2, MaxWidth);
5140 return L;
5141 }
5142
5143 // Otherwise, just use the LHS's width.
5144 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5145 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5146 }
5147
5148 // The result of a remainder can't be larger than the result of
5149 // either side.
5150 case BO_Rem: {
5151 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005152 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005153 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5154 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5155
5156 IntRange meet = IntRange::meet(L, R);
5157 meet.Width = std::min(meet.Width, MaxWidth);
5158 return meet;
5159 }
5160
5161 // The default behavior is okay for these.
5162 case BO_Mul:
5163 case BO_Add:
5164 case BO_Xor:
5165 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005166 break;
5167 }
5168
John McCall51431812011-07-14 22:39:48 +00005169 // The default case is to treat the operation as if it were closed
5170 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005171 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5172 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5173 return IntRange::join(L, R);
5174 }
5175
5176 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5177 switch (UO->getOpcode()) {
5178 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005179 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005180 return IntRange::forBoolType();
5181
5182 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005183 case UO_Deref:
5184 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005185 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005186
5187 default:
5188 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5189 }
5190 }
5191
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005192 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5193 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5194
John McCalld25db7e2013-05-06 21:39:12 +00005195 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005196 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005197 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005198
Eli Friedmane6d33952013-07-08 20:20:06 +00005199 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005200}
John McCall263a48b2010-01-04 23:31:57 +00005201
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005202static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005203 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005204}
5205
John McCall263a48b2010-01-04 23:31:57 +00005206/// Checks whether the given value, which currently has the given
5207/// source semantics, has the same value when coerced through the
5208/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005209static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5210 const llvm::fltSemantics &Src,
5211 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005212 llvm::APFloat truncated = value;
5213
5214 bool ignored;
5215 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5216 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5217
5218 return truncated.bitwiseIsEqual(value);
5219}
5220
5221/// Checks whether the given value, which currently has the given
5222/// source semantics, has the same value when coerced through the
5223/// target semantics.
5224///
5225/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005226static bool IsSameFloatAfterCast(const APValue &value,
5227 const llvm::fltSemantics &Src,
5228 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005229 if (value.isFloat())
5230 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5231
5232 if (value.isVector()) {
5233 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5234 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5235 return false;
5236 return true;
5237 }
5238
5239 assert(value.isComplexFloat());
5240 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5241 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5242}
5243
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005244static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005245
Ted Kremenek6274be42010-09-23 21:43:44 +00005246static bool IsZero(Sema &S, Expr *E) {
5247 // Suppress cases where we are comparing against an enum constant.
5248 if (const DeclRefExpr *DR =
5249 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5250 if (isa<EnumConstantDecl>(DR->getDecl()))
5251 return false;
5252
5253 // Suppress cases where the '0' value is expanded from a macro.
5254 if (E->getLocStart().isMacroID())
5255 return false;
5256
John McCallcc7e5bf2010-05-06 08:58:33 +00005257 llvm::APSInt Value;
5258 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5259}
5260
John McCall2551c1b2010-10-06 00:25:24 +00005261static bool HasEnumType(Expr *E) {
5262 // Strip off implicit integral promotions.
5263 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005264 if (ICE->getCastKind() != CK_IntegralCast &&
5265 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005266 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005267 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005268 }
5269
5270 return E->getType()->isEnumeralType();
5271}
5272
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005273static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005274 // Disable warning in template instantiations.
5275 if (!S.ActiveTemplateInstantiations.empty())
5276 return;
5277
John McCalle3027922010-08-25 11:45:40 +00005278 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005279 if (E->isValueDependent())
5280 return;
5281
John McCalle3027922010-08-25 11:45:40 +00005282 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005283 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005284 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005285 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005286 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005287 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005288 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005289 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005290 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005291 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005292 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005293 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005294 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005295 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005296 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005297 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5298 }
5299}
5300
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005301static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005302 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005303 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005304 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005305 // Disable warning in template instantiations.
5306 if (!S.ActiveTemplateInstantiations.empty())
5307 return;
5308
Richard Trieu560910c2012-11-14 22:50:24 +00005309 // 0 values are handled later by CheckTrivialUnsignedComparison().
5310 if (Value == 0)
5311 return;
5312
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005313 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005314 QualType OtherT = Other->getType();
5315 QualType ConstantT = Constant->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005316 QualType CommonT = E->getLHS()->getType();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005317 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005318 return;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005319 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005320 && "comparison with non-integer type");
Richard Trieu560910c2012-11-14 22:50:24 +00005321
5322 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu560910c2012-11-14 22:50:24 +00005323 bool CommonSigned = CommonT->isSignedIntegerType();
5324
5325 bool EqualityOnly = false;
5326
5327 // TODO: Investigate using GetExprRange() to get tighter bounds on
5328 // on the bit ranges.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005329 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu560910c2012-11-14 22:50:24 +00005330 unsigned OtherWidth = OtherRange.Width;
5331
5332 if (CommonSigned) {
5333 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedman5ac98752012-11-30 23:09:29 +00005334 if (!OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005335 // Check that the constant is representable in type OtherT.
5336 if (ConstantSigned) {
5337 if (OtherWidth >= Value.getMinSignedBits())
5338 return;
5339 } else { // !ConstantSigned
5340 if (OtherWidth >= Value.getActiveBits() + 1)
5341 return;
5342 }
5343 } else { // !OtherSigned
5344 // Check that the constant is representable in type OtherT.
5345 // Negative values are out of range.
5346 if (ConstantSigned) {
5347 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5348 return;
5349 } else { // !ConstantSigned
5350 if (OtherWidth >= Value.getActiveBits())
5351 return;
5352 }
5353 }
5354 } else { // !CommonSigned
Eli Friedman5ac98752012-11-30 23:09:29 +00005355 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005356 if (OtherWidth >= Value.getActiveBits())
5357 return;
Eli Friedman5ac98752012-11-30 23:09:29 +00005358 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu560910c2012-11-14 22:50:24 +00005359 // Check to see if the constant is representable in OtherT.
5360 if (OtherWidth > Value.getActiveBits())
5361 return;
5362 // Check to see if the constant is equivalent to a negative value
5363 // cast to CommonT.
5364 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu03c3a2f2012-11-15 03:43:50 +00005365 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu560910c2012-11-14 22:50:24 +00005366 return;
5367 // The constant value rests between values that OtherT can represent after
5368 // conversion. Relational comparison still works, but equality
5369 // comparisons will be tautological.
5370 EqualityOnly = true;
5371 } else { // OtherSigned && ConstantSigned
5372 assert(0 && "Two signed types converted to unsigned types.");
5373 }
5374 }
5375
5376 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5377
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005378 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005379 if (op == BO_EQ || op == BO_NE) {
5380 IsTrue = op == BO_NE;
5381 } else if (EqualityOnly) {
5382 return;
5383 } else if (RhsConstant) {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005384 if (op == BO_GT || op == BO_GE)
Richard Trieu560910c2012-11-14 22:50:24 +00005385 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005386 else // op == BO_LT || op == BO_LE
Richard Trieu560910c2012-11-14 22:50:24 +00005387 IsTrue = PositiveConstant;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005388 } else {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005389 if (op == BO_LT || op == BO_LE)
Richard Trieu560910c2012-11-14 22:50:24 +00005390 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005391 else // op == BO_GT || op == BO_GE
Richard Trieu560910c2012-11-14 22:50:24 +00005392 IsTrue = PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005393 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005394
5395 // If this is a comparison to an enum constant, include that
5396 // constant in the diagnostic.
5397 const EnumConstantDecl *ED = 0;
5398 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5399 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5400
5401 SmallString<64> PrettySourceValue;
5402 llvm::raw_svector_ostream OS(PrettySourceValue);
5403 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005404 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005405 else
5406 OS << Value;
5407
Richard Trieuc38786b2014-01-10 04:38:09 +00005408 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5409 S.PDiag(diag::warn_out_of_range_compare)
5410 << OS.str() << OtherT << IsTrue
5411 << E->getLHS()->getSourceRange()
5412 << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005413}
5414
John McCallcc7e5bf2010-05-06 08:58:33 +00005415/// Analyze the operands of the given comparison. Implements the
5416/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005417static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005418 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5419 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005420}
John McCall263a48b2010-01-04 23:31:57 +00005421
John McCallca01b222010-01-04 23:21:16 +00005422/// \brief Implements -Wsign-compare.
5423///
Richard Trieu82402a02011-09-15 21:56:47 +00005424/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005425static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005426 // The type the comparison is being performed in.
5427 QualType T = E->getLHS()->getType();
5428 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5429 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005430 if (E->isValueDependent())
5431 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005432
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005433 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5434 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005435
5436 bool IsComparisonConstant = false;
5437
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005438 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005439 // of 'true' or 'false'.
5440 if (T->isIntegralType(S.Context)) {
5441 llvm::APSInt RHSValue;
5442 bool IsRHSIntegralLiteral =
5443 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5444 llvm::APSInt LHSValue;
5445 bool IsLHSIntegralLiteral =
5446 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5447 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5448 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5449 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5450 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5451 else
5452 IsComparisonConstant =
5453 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005454 } else if (!T->hasUnsignedIntegerRepresentation())
5455 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005456
John McCallcc7e5bf2010-05-06 08:58:33 +00005457 // We don't do anything special if this isn't an unsigned integral
5458 // comparison: we're only interested in integral comparisons, and
5459 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005460 //
5461 // We also don't care about value-dependent expressions or expressions
5462 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005463 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005464 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005465
John McCallcc7e5bf2010-05-06 08:58:33 +00005466 // Check to see if one of the (unmodified) operands is of different
5467 // signedness.
5468 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005469 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5470 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005471 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005472 signedOperand = LHS;
5473 unsignedOperand = RHS;
5474 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5475 signedOperand = RHS;
5476 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005477 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005478 CheckTrivialUnsignedComparison(S, E);
5479 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005480 }
5481
John McCallcc7e5bf2010-05-06 08:58:33 +00005482 // Otherwise, calculate the effective range of the signed operand.
5483 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005484
John McCallcc7e5bf2010-05-06 08:58:33 +00005485 // Go ahead and analyze implicit conversions in the operands. Note
5486 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005487 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5488 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005489
John McCallcc7e5bf2010-05-06 08:58:33 +00005490 // If the signed range is non-negative, -Wsign-compare won't fire,
5491 // but we should still check for comparisons which are always true
5492 // or false.
5493 if (signedRange.NonNegative)
5494 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005495
5496 // For (in)equality comparisons, if the unsigned operand is a
5497 // constant which cannot collide with a overflowed signed operand,
5498 // then reinterpreting the signed operand as unsigned will not
5499 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005500 if (E->isEqualityOp()) {
5501 unsigned comparisonWidth = S.Context.getIntWidth(T);
5502 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005503
John McCallcc7e5bf2010-05-06 08:58:33 +00005504 // We should never be unable to prove that the unsigned operand is
5505 // non-negative.
5506 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5507
5508 if (unsignedRange.Width < comparisonWidth)
5509 return;
5510 }
5511
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005512 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5513 S.PDiag(diag::warn_mixed_sign_comparison)
5514 << LHS->getType() << RHS->getType()
5515 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005516}
5517
John McCall1f425642010-11-11 03:21:53 +00005518/// Analyzes an attempt to assign the given value to a bitfield.
5519///
5520/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005521static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5522 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005523 assert(Bitfield->isBitField());
5524 if (Bitfield->isInvalidDecl())
5525 return false;
5526
John McCalldeebbcf2010-11-11 05:33:51 +00005527 // White-list bool bitfields.
5528 if (Bitfield->getType()->isBooleanType())
5529 return false;
5530
Douglas Gregor789adec2011-02-04 13:09:01 +00005531 // Ignore value- or type-dependent expressions.
5532 if (Bitfield->getBitWidth()->isValueDependent() ||
5533 Bitfield->getBitWidth()->isTypeDependent() ||
5534 Init->isValueDependent() ||
5535 Init->isTypeDependent())
5536 return false;
5537
John McCall1f425642010-11-11 03:21:53 +00005538 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5539
Richard Smith5fab0c92011-12-28 19:48:30 +00005540 llvm::APSInt Value;
5541 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005542 return false;
5543
John McCall1f425642010-11-11 03:21:53 +00005544 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005545 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005546
5547 if (OriginalWidth <= FieldWidth)
5548 return false;
5549
Eli Friedmanc267a322012-01-26 23:11:39 +00005550 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005551 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005552 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005553
Eli Friedmanc267a322012-01-26 23:11:39 +00005554 // Check whether the stored value is equal to the original value.
5555 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005556 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005557 return false;
5558
Eli Friedmanc267a322012-01-26 23:11:39 +00005559 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005560 // therefore don't strictly fit into a signed bitfield of width 1.
5561 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005562 return false;
5563
John McCall1f425642010-11-11 03:21:53 +00005564 std::string PrettyValue = Value.toString(10);
5565 std::string PrettyTrunc = TruncatedValue.toString(10);
5566
5567 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5568 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5569 << Init->getSourceRange();
5570
5571 return true;
5572}
5573
John McCalld2a53122010-11-09 23:24:47 +00005574/// Analyze the given simple or compound assignment for warning-worthy
5575/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005576static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005577 // Just recurse on the LHS.
5578 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5579
5580 // We want to recurse on the RHS as normal unless we're assigning to
5581 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005582 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005583 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005584 E->getOperatorLoc())) {
5585 // Recurse, ignoring any implicit conversions on the RHS.
5586 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5587 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005588 }
5589 }
5590
5591 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5592}
5593
John McCall263a48b2010-01-04 23:31:57 +00005594/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005595static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005596 SourceLocation CContext, unsigned diag,
5597 bool pruneControlFlow = false) {
5598 if (pruneControlFlow) {
5599 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5600 S.PDiag(diag)
5601 << SourceType << T << E->getSourceRange()
5602 << SourceRange(CContext));
5603 return;
5604 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005605 S.Diag(E->getExprLoc(), diag)
5606 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5607}
5608
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005609/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005610static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005611 SourceLocation CContext, unsigned diag,
5612 bool pruneControlFlow = false) {
5613 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005614}
5615
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005616/// Diagnose an implicit cast from a literal expression. Does not warn when the
5617/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005618void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5619 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005620 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005621 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005622 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005623 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5624 T->hasUnsignedIntegerRepresentation());
5625 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005626 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005627 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005628 return;
5629
Eli Friedman07185912013-08-29 23:44:43 +00005630 // FIXME: Force the precision of the source value down so we don't print
5631 // digits which are usually useless (we don't really care here if we
5632 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5633 // would automatically print the shortest representation, but it's a bit
5634 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005635 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005636 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5637 precision = (precision * 59 + 195) / 196;
5638 Value.toString(PrettySourceValue, precision);
5639
David Blaikie9b88cc02012-05-15 17:18:27 +00005640 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005641 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5642 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5643 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005644 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005645
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005646 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005647 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5648 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005649}
5650
John McCall18a2c2c2010-11-09 22:22:12 +00005651std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5652 if (!Range.Width) return "0";
5653
5654 llvm::APSInt ValueInRange = Value;
5655 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005656 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005657 return ValueInRange.toString(10);
5658}
5659
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005660static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5661 if (!isa<ImplicitCastExpr>(Ex))
5662 return false;
5663
5664 Expr *InnerE = Ex->IgnoreParenImpCasts();
5665 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5666 const Type *Source =
5667 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5668 if (Target->isDependentType())
5669 return false;
5670
5671 const BuiltinType *FloatCandidateBT =
5672 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5673 const Type *BoolCandidateType = ToBool ? Target : Source;
5674
5675 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5676 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5677}
5678
5679void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5680 SourceLocation CC) {
5681 unsigned NumArgs = TheCall->getNumArgs();
5682 for (unsigned i = 0; i < NumArgs; ++i) {
5683 Expr *CurrA = TheCall->getArg(i);
5684 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5685 continue;
5686
5687 bool IsSwapped = ((i > 0) &&
5688 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5689 IsSwapped |= ((i < (NumArgs - 1)) &&
5690 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5691 if (IsSwapped) {
5692 // Warn on this floating-point to bool conversion.
5693 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5694 CurrA->getType(), CC,
5695 diag::warn_impcast_floating_point_to_bool);
5696 }
5697 }
5698}
5699
John McCallcc7e5bf2010-05-06 08:58:33 +00005700void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005701 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005702 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005703
John McCallcc7e5bf2010-05-06 08:58:33 +00005704 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5705 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5706 if (Source == Target) return;
5707 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005708
Chandler Carruthc22845a2011-07-26 05:40:03 +00005709 // If the conversion context location is invalid don't complain. We also
5710 // don't want to emit a warning if the issue occurs from the expansion of
5711 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5712 // delay this check as long as possible. Once we detect we are in that
5713 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005714 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005715 return;
5716
Richard Trieu021baa32011-09-23 20:10:00 +00005717 // Diagnose implicit casts to bool.
5718 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5719 if (isa<StringLiteral>(E))
5720 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005721 // and expressions, for instance, assert(0 && "error here"), are
5722 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005723 return DiagnoseImpCast(S, E, T, CC,
5724 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005725 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5726 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5727 // This covers the literal expressions that evaluate to Objective-C
5728 // objects.
5729 return DiagnoseImpCast(S, E, T, CC,
5730 diag::warn_impcast_objective_c_literal_to_bool);
5731 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005732 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5733 // Warn on pointer to bool conversion that is always true.
5734 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5735 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005736 }
Richard Trieu021baa32011-09-23 20:10:00 +00005737 }
John McCall263a48b2010-01-04 23:31:57 +00005738
5739 // Strip vector types.
5740 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005741 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005742 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005743 return;
John McCallacf0ee52010-10-08 02:01:28 +00005744 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005745 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005746
5747 // If the vector cast is cast between two vectors of the same size, it is
5748 // a bitcast, not a conversion.
5749 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5750 return;
John McCall263a48b2010-01-04 23:31:57 +00005751
5752 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5753 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5754 }
5755
5756 // Strip complex types.
5757 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005758 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005759 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005760 return;
5761
John McCallacf0ee52010-10-08 02:01:28 +00005762 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005763 }
John McCall263a48b2010-01-04 23:31:57 +00005764
5765 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5766 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5767 }
5768
5769 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5770 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5771
5772 // If the source is floating point...
5773 if (SourceBT && SourceBT->isFloatingPoint()) {
5774 // ...and the target is floating point...
5775 if (TargetBT && TargetBT->isFloatingPoint()) {
5776 // ...then warn if we're dropping FP rank.
5777
5778 // Builtin FP kinds are ordered by increasing FP rank.
5779 if (SourceBT->getKind() > TargetBT->getKind()) {
5780 // Don't warn about float constants that are precisely
5781 // representable in the target type.
5782 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005783 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005784 // Value might be a float, a float vector, or a float complex.
5785 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005786 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5787 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005788 return;
5789 }
5790
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005791 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005792 return;
5793
John McCallacf0ee52010-10-08 02:01:28 +00005794 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005795 }
5796 return;
5797 }
5798
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005799 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005800 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005801 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005802 return;
5803
Chandler Carruth22c7a792011-02-17 11:05:49 +00005804 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005805 // We also want to warn on, e.g., "int i = -1.234"
5806 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5807 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5808 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5809
Chandler Carruth016ef402011-04-10 08:36:24 +00005810 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5811 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005812 } else {
5813 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5814 }
5815 }
John McCall263a48b2010-01-04 23:31:57 +00005816
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005817 // If the target is bool, warn if expr is a function or method call.
5818 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5819 isa<CallExpr>(E)) {
5820 // Check last argument of function call to see if it is an
5821 // implicit cast from a type matching the type the result
5822 // is being cast to.
5823 CallExpr *CEx = cast<CallExpr>(E);
5824 unsigned NumArgs = CEx->getNumArgs();
5825 if (NumArgs > 0) {
5826 Expr *LastA = CEx->getArg(NumArgs - 1);
5827 Expr *InnerE = LastA->IgnoreParenImpCasts();
5828 const Type *InnerType =
5829 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5830 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5831 // Warn on this floating-point to bool conversion
5832 DiagnoseImpCast(S, E, T, CC,
5833 diag::warn_impcast_floating_point_to_bool);
5834 }
5835 }
5836 }
John McCall263a48b2010-01-04 23:31:57 +00005837 return;
5838 }
5839
Richard Trieubeaf3452011-05-29 19:59:02 +00005840 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005841 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005842 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005843 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005844 SourceLocation Loc = E->getSourceRange().getBegin();
5845 if (Loc.isMacroID())
5846 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005847 if (!Loc.isMacroID() || CC.isMacroID())
5848 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5849 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005850 << FixItHint::CreateReplacement(Loc,
5851 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005852 }
5853
David Blaikie9366d2b2012-06-19 21:19:06 +00005854 if (!Source->isIntegerType() || !Target->isIntegerType())
5855 return;
5856
David Blaikie7555b6a2012-05-15 16:56:36 +00005857 // TODO: remove this early return once the false positives for constant->bool
5858 // in templates, macros, etc, are reduced or removed.
5859 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5860 return;
5861
John McCallcc7e5bf2010-05-06 08:58:33 +00005862 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005863 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005864
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005865 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005866 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005867 // TODO: this should happen for bitfield stores, too.
5868 llvm::APSInt Value(32);
5869 if (E->isIntegerConstantExpr(Value, S.Context)) {
5870 if (S.SourceMgr.isInSystemMacro(CC))
5871 return;
5872
John McCall18a2c2c2010-11-09 22:22:12 +00005873 std::string PrettySourceValue = Value.toString(10);
5874 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005875
Ted Kremenek33ba9952011-10-22 02:37:33 +00005876 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5877 S.PDiag(diag::warn_impcast_integer_precision_constant)
5878 << PrettySourceValue << PrettyTargetValue
5879 << E->getType() << T << E->getSourceRange()
5880 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005881 return;
5882 }
5883
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005884 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5885 if (S.SourceMgr.isInSystemMacro(CC))
5886 return;
5887
David Blaikie9455da02012-04-12 22:40:54 +00005888 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005889 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5890 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005891 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005892 }
5893
5894 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5895 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5896 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005897
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005898 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005899 return;
5900
John McCallcc7e5bf2010-05-06 08:58:33 +00005901 unsigned DiagID = diag::warn_impcast_integer_sign;
5902
5903 // Traditionally, gcc has warned about this under -Wsign-compare.
5904 // We also want to warn about it in -Wconversion.
5905 // So if -Wconversion is off, use a completely identical diagnostic
5906 // in the sign-compare group.
5907 // The conditional-checking code will
5908 if (ICContext) {
5909 DiagID = diag::warn_impcast_integer_sign_conditional;
5910 *ICContext = true;
5911 }
5912
John McCallacf0ee52010-10-08 02:01:28 +00005913 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005914 }
5915
Douglas Gregora78f1932011-02-22 02:45:07 +00005916 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005917 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5918 // type, to give us better diagnostics.
5919 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005920 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005921 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5922 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5923 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5924 SourceType = S.Context.getTypeDeclType(Enum);
5925 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5926 }
5927 }
5928
Douglas Gregora78f1932011-02-22 02:45:07 +00005929 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5930 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00005931 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5932 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005933 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005934 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005935 return;
5936
Douglas Gregor364f7db2011-03-12 00:14:31 +00005937 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00005938 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005939 }
Douglas Gregora78f1932011-02-22 02:45:07 +00005940
John McCall263a48b2010-01-04 23:31:57 +00005941 return;
5942}
5943
David Blaikie18e9ac72012-05-15 21:57:38 +00005944void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5945 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005946
5947void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00005948 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005949 E = E->IgnoreParenImpCasts();
5950
5951 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00005952 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005953
John McCallacf0ee52010-10-08 02:01:28 +00005954 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005955 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005956 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00005957 return;
5958}
5959
David Blaikie18e9ac72012-05-15 21:57:38 +00005960void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5961 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00005962 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005963
5964 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00005965 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5966 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005967
5968 // If -Wconversion would have warned about either of the candidates
5969 // for a signedness conversion to the context type...
5970 if (!Suspicious) return;
5971
5972 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005973 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5974 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00005975 return;
5976
John McCallcc7e5bf2010-05-06 08:58:33 +00005977 // ...then check whether it would have warned about either of the
5978 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00005979 if (E->getType() == T) return;
5980
5981 Suspicious = false;
5982 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5983 E->getType(), CC, &Suspicious);
5984 if (!Suspicious)
5985 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00005986 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005987}
5988
5989/// AnalyzeImplicitConversions - Find and report any interesting
5990/// implicit conversions in the given expression. There are a couple
5991/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005992void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005993 QualType T = OrigE->getType();
5994 Expr *E = OrigE->IgnoreParenImpCasts();
5995
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00005996 if (E->isTypeDependent() || E->isValueDependent())
5997 return;
5998
John McCallcc7e5bf2010-05-06 08:58:33 +00005999 // For conditional operators, we analyze the arguments as if they
6000 // were being fed directly into the output.
6001 if (isa<ConditionalOperator>(E)) {
6002 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006003 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006004 return;
6005 }
6006
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006007 // Check implicit argument conversions for function calls.
6008 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6009 CheckImplicitArgumentConversions(S, Call, CC);
6010
John McCallcc7e5bf2010-05-06 08:58:33 +00006011 // Go ahead and check any implicit conversions we might have skipped.
6012 // The non-canonical typecheck is just an optimization;
6013 // CheckImplicitConversion will filter out dead implicit conversions.
6014 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006015 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006016
6017 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006018
6019 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006020 if (POE->getResultExpr())
6021 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006022 }
6023
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006024 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6025 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6026
John McCallcc7e5bf2010-05-06 08:58:33 +00006027 // Skip past explicit casts.
6028 if (isa<ExplicitCastExpr>(E)) {
6029 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006030 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006031 }
6032
John McCalld2a53122010-11-09 23:24:47 +00006033 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6034 // Do a somewhat different check with comparison operators.
6035 if (BO->isComparisonOp())
6036 return AnalyzeComparison(S, BO);
6037
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006038 // And with simple assignments.
6039 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006040 return AnalyzeAssignment(S, BO);
6041 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006042
6043 // These break the otherwise-useful invariant below. Fortunately,
6044 // we don't really need to recurse into them, because any internal
6045 // expressions should have been analyzed already when they were
6046 // built into statements.
6047 if (isa<StmtExpr>(E)) return;
6048
6049 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006050 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006051
6052 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006053 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006054 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006055 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006056 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006057 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006058 if (!ChildExpr)
6059 continue;
6060
Richard Trieu955231d2014-01-25 01:10:35 +00006061 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006062 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006063 // Ignore checking string literals that are in logical and operators.
6064 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006065 continue;
6066 AnalyzeImplicitConversions(S, ChildExpr, CC);
6067 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006068}
6069
6070} // end anonymous namespace
6071
Richard Trieu3bb8b562014-02-26 02:36:06 +00006072enum {
6073 AddressOf,
6074 FunctionPointer,
6075 ArrayPointer
6076};
6077
6078/// \brief Diagnose pointers that are always non-null.
6079/// \param E the expression containing the pointer
6080/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6081/// compared to a null pointer
6082/// \param IsEqual True when the comparison is equal to a null pointer
6083/// \param Range Extra SourceRange to highlight in the diagnostic
6084void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6085 Expr::NullPointerConstantKind NullKind,
6086 bool IsEqual, SourceRange Range) {
6087
6088 // Don't warn inside macros.
6089 if (E->getExprLoc().isMacroID())
6090 return;
6091 E = E->IgnoreImpCasts();
6092
6093 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6094
6095 bool IsAddressOf = false;
6096
6097 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6098 if (UO->getOpcode() != UO_AddrOf)
6099 return;
6100 IsAddressOf = true;
6101 E = UO->getSubExpr();
6102 }
6103
6104 // Expect to find a single Decl. Skip anything more complicated.
6105 ValueDecl *D = 0;
6106 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6107 D = R->getDecl();
6108 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6109 D = M->getMemberDecl();
6110 }
6111
6112 // Weak Decls can be null.
6113 if (!D || D->isWeak())
6114 return;
6115
6116 QualType T = D->getType();
6117 const bool IsArray = T->isArrayType();
6118 const bool IsFunction = T->isFunctionType();
6119
6120 if (IsAddressOf) {
6121 // Address of function is used to silence the function warning.
6122 if (IsFunction)
6123 return;
6124 // Address of reference can be null.
6125 if (T->isReferenceType())
6126 return;
6127 }
6128
6129 // Found nothing.
6130 if (!IsAddressOf && !IsFunction && !IsArray)
6131 return;
6132
6133 // Pretty print the expression for the diagnostic.
6134 std::string Str;
6135 llvm::raw_string_ostream S(Str);
6136 E->printPretty(S, 0, getPrintingPolicy());
6137
6138 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6139 : diag::warn_impcast_pointer_to_bool;
6140 unsigned DiagType;
6141 if (IsAddressOf)
6142 DiagType = AddressOf;
6143 else if (IsFunction)
6144 DiagType = FunctionPointer;
6145 else if (IsArray)
6146 DiagType = ArrayPointer;
6147 else
6148 llvm_unreachable("Could not determine diagnostic.");
6149 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6150 << Range << IsEqual;
6151
6152 if (!IsFunction)
6153 return;
6154
6155 // Suggest '&' to silence the function warning.
6156 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6157 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6158
6159 // Check to see if '()' fixit should be emitted.
6160 QualType ReturnType;
6161 UnresolvedSet<4> NonTemplateOverloads;
6162 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6163 if (ReturnType.isNull())
6164 return;
6165
6166 if (IsCompare) {
6167 // There are two cases here. If there is null constant, the only suggest
6168 // for a pointer return type. If the null is 0, then suggest if the return
6169 // type is a pointer or an integer type.
6170 if (!ReturnType->isPointerType()) {
6171 if (NullKind == Expr::NPCK_ZeroExpression ||
6172 NullKind == Expr::NPCK_ZeroLiteral) {
6173 if (!ReturnType->isIntegerType())
6174 return;
6175 } else {
6176 return;
6177 }
6178 }
6179 } else { // !IsCompare
6180 // For function to bool, only suggest if the function pointer has bool
6181 // return type.
6182 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6183 return;
6184 }
6185 Diag(E->getExprLoc(), diag::note_function_to_function_call)
6186 << FixItHint::CreateInsertion(
6187 getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
6188}
6189
6190
John McCallcc7e5bf2010-05-06 08:58:33 +00006191/// Diagnoses "dangerous" implicit conversions within the given
6192/// expression (which is a full expression). Implements -Wconversion
6193/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006194///
6195/// \param CC the "context" location of the implicit conversion, i.e.
6196/// the most location of the syntactic entity requiring the implicit
6197/// conversion
6198void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006199 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006200 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006201 return;
6202
6203 // Don't diagnose for value- or type-dependent expressions.
6204 if (E->isTypeDependent() || E->isValueDependent())
6205 return;
6206
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006207 // Check for array bounds violations in cases where the check isn't triggered
6208 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6209 // ArraySubscriptExpr is on the RHS of a variable initialization.
6210 CheckArrayAccess(E);
6211
John McCallacf0ee52010-10-08 02:01:28 +00006212 // This is not the right CC for (e.g.) a variable initialization.
6213 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006214}
6215
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006216/// Diagnose when expression is an integer constant expression and its evaluation
6217/// results in integer overflow
6218void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006219 if (isa<BinaryOperator>(E->IgnoreParens()))
6220 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006221}
6222
Richard Smithc406cb72013-01-17 01:17:56 +00006223namespace {
6224/// \brief Visitor for expressions which looks for unsequenced operations on the
6225/// same object.
6226class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006227 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6228
Richard Smithc406cb72013-01-17 01:17:56 +00006229 /// \brief A tree of sequenced regions within an expression. Two regions are
6230 /// unsequenced if one is an ancestor or a descendent of the other. When we
6231 /// finish processing an expression with sequencing, such as a comma
6232 /// expression, we fold its tree nodes into its parent, since they are
6233 /// unsequenced with respect to nodes we will visit later.
6234 class SequenceTree {
6235 struct Value {
6236 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6237 unsigned Parent : 31;
6238 bool Merged : 1;
6239 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006240 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006241
6242 public:
6243 /// \brief A region within an expression which may be sequenced with respect
6244 /// to some other region.
6245 class Seq {
6246 explicit Seq(unsigned N) : Index(N) {}
6247 unsigned Index;
6248 friend class SequenceTree;
6249 public:
6250 Seq() : Index(0) {}
6251 };
6252
6253 SequenceTree() { Values.push_back(Value(0)); }
6254 Seq root() const { return Seq(0); }
6255
6256 /// \brief Create a new sequence of operations, which is an unsequenced
6257 /// subset of \p Parent. This sequence of operations is sequenced with
6258 /// respect to other children of \p Parent.
6259 Seq allocate(Seq Parent) {
6260 Values.push_back(Value(Parent.Index));
6261 return Seq(Values.size() - 1);
6262 }
6263
6264 /// \brief Merge a sequence of operations into its parent.
6265 void merge(Seq S) {
6266 Values[S.Index].Merged = true;
6267 }
6268
6269 /// \brief Determine whether two operations are unsequenced. This operation
6270 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6271 /// should have been merged into its parent as appropriate.
6272 bool isUnsequenced(Seq Cur, Seq Old) {
6273 unsigned C = representative(Cur.Index);
6274 unsigned Target = representative(Old.Index);
6275 while (C >= Target) {
6276 if (C == Target)
6277 return true;
6278 C = Values[C].Parent;
6279 }
6280 return false;
6281 }
6282
6283 private:
6284 /// \brief Pick a representative for a sequence.
6285 unsigned representative(unsigned K) {
6286 if (Values[K].Merged)
6287 // Perform path compression as we go.
6288 return Values[K].Parent = representative(Values[K].Parent);
6289 return K;
6290 }
6291 };
6292
6293 /// An object for which we can track unsequenced uses.
6294 typedef NamedDecl *Object;
6295
6296 /// Different flavors of object usage which we track. We only track the
6297 /// least-sequenced usage of each kind.
6298 enum UsageKind {
6299 /// A read of an object. Multiple unsequenced reads are OK.
6300 UK_Use,
6301 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006302 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006303 UK_ModAsValue,
6304 /// A modification of an object which is not sequenced before the value
6305 /// computation of the expression, such as n++.
6306 UK_ModAsSideEffect,
6307
6308 UK_Count = UK_ModAsSideEffect + 1
6309 };
6310
6311 struct Usage {
6312 Usage() : Use(0), Seq() {}
6313 Expr *Use;
6314 SequenceTree::Seq Seq;
6315 };
6316
6317 struct UsageInfo {
6318 UsageInfo() : Diagnosed(false) {}
6319 Usage Uses[UK_Count];
6320 /// Have we issued a diagnostic for this variable already?
6321 bool Diagnosed;
6322 };
6323 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6324
6325 Sema &SemaRef;
6326 /// Sequenced regions within the expression.
6327 SequenceTree Tree;
6328 /// Declaration modifications and references which we have seen.
6329 UsageInfoMap UsageMap;
6330 /// The region we are currently within.
6331 SequenceTree::Seq Region;
6332 /// Filled in with declarations which were modified as a side-effect
6333 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006334 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006335 /// Expressions to check later. We defer checking these to reduce
6336 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006337 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006338
6339 /// RAII object wrapping the visitation of a sequenced subexpression of an
6340 /// expression. At the end of this process, the side-effects of the evaluation
6341 /// become sequenced with respect to the value computation of the result, so
6342 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6343 /// UK_ModAsValue.
6344 struct SequencedSubexpression {
6345 SequencedSubexpression(SequenceChecker &Self)
6346 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6347 Self.ModAsSideEffect = &ModAsSideEffect;
6348 }
6349 ~SequencedSubexpression() {
6350 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6351 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6352 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6353 Self.addUsage(U, ModAsSideEffect[I].first,
6354 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6355 }
6356 Self.ModAsSideEffect = OldModAsSideEffect;
6357 }
6358
6359 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006360 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6361 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006362 };
6363
Richard Smith40238f02013-06-20 22:21:56 +00006364 /// RAII object wrapping the visitation of a subexpression which we might
6365 /// choose to evaluate as a constant. If any subexpression is evaluated and
6366 /// found to be non-constant, this allows us to suppress the evaluation of
6367 /// the outer expression.
6368 class EvaluationTracker {
6369 public:
6370 EvaluationTracker(SequenceChecker &Self)
6371 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6372 Self.EvalTracker = this;
6373 }
6374 ~EvaluationTracker() {
6375 Self.EvalTracker = Prev;
6376 if (Prev)
6377 Prev->EvalOK &= EvalOK;
6378 }
6379
6380 bool evaluate(const Expr *E, bool &Result) {
6381 if (!EvalOK || E->isValueDependent())
6382 return false;
6383 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6384 return EvalOK;
6385 }
6386
6387 private:
6388 SequenceChecker &Self;
6389 EvaluationTracker *Prev;
6390 bool EvalOK;
6391 } *EvalTracker;
6392
Richard Smithc406cb72013-01-17 01:17:56 +00006393 /// \brief Find the object which is produced by the specified expression,
6394 /// if any.
6395 Object getObject(Expr *E, bool Mod) const {
6396 E = E->IgnoreParenCasts();
6397 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6398 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6399 return getObject(UO->getSubExpr(), Mod);
6400 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6401 if (BO->getOpcode() == BO_Comma)
6402 return getObject(BO->getRHS(), Mod);
6403 if (Mod && BO->isAssignmentOp())
6404 return getObject(BO->getLHS(), Mod);
6405 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6406 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6407 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6408 return ME->getMemberDecl();
6409 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6410 // FIXME: If this is a reference, map through to its value.
6411 return DRE->getDecl();
6412 return 0;
6413 }
6414
6415 /// \brief Note that an object was modified or used by an expression.
6416 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6417 Usage &U = UI.Uses[UK];
6418 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6419 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6420 ModAsSideEffect->push_back(std::make_pair(O, U));
6421 U.Use = Ref;
6422 U.Seq = Region;
6423 }
6424 }
6425 /// \brief Check whether a modification or use conflicts with a prior usage.
6426 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6427 bool IsModMod) {
6428 if (UI.Diagnosed)
6429 return;
6430
6431 const Usage &U = UI.Uses[OtherKind];
6432 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6433 return;
6434
6435 Expr *Mod = U.Use;
6436 Expr *ModOrUse = Ref;
6437 if (OtherKind == UK_Use)
6438 std::swap(Mod, ModOrUse);
6439
6440 SemaRef.Diag(Mod->getExprLoc(),
6441 IsModMod ? diag::warn_unsequenced_mod_mod
6442 : diag::warn_unsequenced_mod_use)
6443 << O << SourceRange(ModOrUse->getExprLoc());
6444 UI.Diagnosed = true;
6445 }
6446
6447 void notePreUse(Object O, Expr *Use) {
6448 UsageInfo &U = UsageMap[O];
6449 // Uses conflict with other modifications.
6450 checkUsage(O, U, Use, UK_ModAsValue, false);
6451 }
6452 void notePostUse(Object O, Expr *Use) {
6453 UsageInfo &U = UsageMap[O];
6454 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6455 addUsage(U, O, Use, UK_Use);
6456 }
6457
6458 void notePreMod(Object O, Expr *Mod) {
6459 UsageInfo &U = UsageMap[O];
6460 // Modifications conflict with other modifications and with uses.
6461 checkUsage(O, U, Mod, UK_ModAsValue, true);
6462 checkUsage(O, U, Mod, UK_Use, false);
6463 }
6464 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6465 UsageInfo &U = UsageMap[O];
6466 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6467 addUsage(U, O, Use, UK);
6468 }
6469
6470public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006471 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6472 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6473 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00006474 Visit(E);
6475 }
6476
6477 void VisitStmt(Stmt *S) {
6478 // Skip all statements which aren't expressions for now.
6479 }
6480
6481 void VisitExpr(Expr *E) {
6482 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006483 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006484 }
6485
6486 void VisitCastExpr(CastExpr *E) {
6487 Object O = Object();
6488 if (E->getCastKind() == CK_LValueToRValue)
6489 O = getObject(E->getSubExpr(), false);
6490
6491 if (O)
6492 notePreUse(O, E);
6493 VisitExpr(E);
6494 if (O)
6495 notePostUse(O, E);
6496 }
6497
6498 void VisitBinComma(BinaryOperator *BO) {
6499 // C++11 [expr.comma]p1:
6500 // Every value computation and side effect associated with the left
6501 // expression is sequenced before every value computation and side
6502 // effect associated with the right expression.
6503 SequenceTree::Seq LHS = Tree.allocate(Region);
6504 SequenceTree::Seq RHS = Tree.allocate(Region);
6505 SequenceTree::Seq OldRegion = Region;
6506
6507 {
6508 SequencedSubexpression SeqLHS(*this);
6509 Region = LHS;
6510 Visit(BO->getLHS());
6511 }
6512
6513 Region = RHS;
6514 Visit(BO->getRHS());
6515
6516 Region = OldRegion;
6517
6518 // Forget that LHS and RHS are sequenced. They are both unsequenced
6519 // with respect to other stuff.
6520 Tree.merge(LHS);
6521 Tree.merge(RHS);
6522 }
6523
6524 void VisitBinAssign(BinaryOperator *BO) {
6525 // The modification is sequenced after the value computation of the LHS
6526 // and RHS, so check it before inspecting the operands and update the
6527 // map afterwards.
6528 Object O = getObject(BO->getLHS(), true);
6529 if (!O)
6530 return VisitExpr(BO);
6531
6532 notePreMod(O, BO);
6533
6534 // C++11 [expr.ass]p7:
6535 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6536 // only once.
6537 //
6538 // Therefore, for a compound assignment operator, O is considered used
6539 // everywhere except within the evaluation of E1 itself.
6540 if (isa<CompoundAssignOperator>(BO))
6541 notePreUse(O, BO);
6542
6543 Visit(BO->getLHS());
6544
6545 if (isa<CompoundAssignOperator>(BO))
6546 notePostUse(O, BO);
6547
6548 Visit(BO->getRHS());
6549
Richard Smith83e37bee2013-06-26 23:16:51 +00006550 // C++11 [expr.ass]p1:
6551 // the assignment is sequenced [...] before the value computation of the
6552 // assignment expression.
6553 // C11 6.5.16/3 has no such rule.
6554 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6555 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006556 }
6557 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6558 VisitBinAssign(CAO);
6559 }
6560
6561 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6562 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6563 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6564 Object O = getObject(UO->getSubExpr(), true);
6565 if (!O)
6566 return VisitExpr(UO);
6567
6568 notePreMod(O, UO);
6569 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006570 // C++11 [expr.pre.incr]p1:
6571 // the expression ++x is equivalent to x+=1
6572 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6573 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006574 }
6575
6576 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6577 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6578 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6579 Object O = getObject(UO->getSubExpr(), true);
6580 if (!O)
6581 return VisitExpr(UO);
6582
6583 notePreMod(O, UO);
6584 Visit(UO->getSubExpr());
6585 notePostMod(O, UO, UK_ModAsSideEffect);
6586 }
6587
6588 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6589 void VisitBinLOr(BinaryOperator *BO) {
6590 // The side-effects of the LHS of an '&&' are sequenced before the
6591 // value computation of the RHS, and hence before the value computation
6592 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6593 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006594 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006595 {
6596 SequencedSubexpression Sequenced(*this);
6597 Visit(BO->getLHS());
6598 }
6599
6600 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006601 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006602 if (!Result)
6603 Visit(BO->getRHS());
6604 } else {
6605 // Check for unsequenced operations in the RHS, treating it as an
6606 // entirely separate evaluation.
6607 //
6608 // FIXME: If there are operations in the RHS which are unsequenced
6609 // with respect to operations outside the RHS, and those operations
6610 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006611 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006612 }
Richard Smithc406cb72013-01-17 01:17:56 +00006613 }
6614 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006615 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006616 {
6617 SequencedSubexpression Sequenced(*this);
6618 Visit(BO->getLHS());
6619 }
6620
6621 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006622 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006623 if (Result)
6624 Visit(BO->getRHS());
6625 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006626 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006627 }
Richard Smithc406cb72013-01-17 01:17:56 +00006628 }
6629
6630 // Only visit the condition, unless we can be sure which subexpression will
6631 // be chosen.
6632 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006633 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006634 {
6635 SequencedSubexpression Sequenced(*this);
6636 Visit(CO->getCond());
6637 }
Richard Smithc406cb72013-01-17 01:17:56 +00006638
6639 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006640 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006641 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006642 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006643 WorkList.push_back(CO->getTrueExpr());
6644 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006645 }
Richard Smithc406cb72013-01-17 01:17:56 +00006646 }
6647
Richard Smithe3dbfe02013-06-30 10:40:20 +00006648 void VisitCallExpr(CallExpr *CE) {
6649 // C++11 [intro.execution]p15:
6650 // When calling a function [...], every value computation and side effect
6651 // associated with any argument expression, or with the postfix expression
6652 // designating the called function, is sequenced before execution of every
6653 // expression or statement in the body of the function [and thus before
6654 // the value computation of its result].
6655 SequencedSubexpression Sequenced(*this);
6656 Base::VisitCallExpr(CE);
6657
6658 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6659 }
6660
Richard Smithc406cb72013-01-17 01:17:56 +00006661 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006662 // This is a call, so all subexpressions are sequenced before the result.
6663 SequencedSubexpression Sequenced(*this);
6664
Richard Smithc406cb72013-01-17 01:17:56 +00006665 if (!CCE->isListInitialization())
6666 return VisitExpr(CCE);
6667
6668 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006669 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006670 SequenceTree::Seq Parent = Region;
6671 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6672 E = CCE->arg_end();
6673 I != E; ++I) {
6674 Region = Tree.allocate(Parent);
6675 Elts.push_back(Region);
6676 Visit(*I);
6677 }
6678
6679 // Forget that the initializers are sequenced.
6680 Region = Parent;
6681 for (unsigned I = 0; I < Elts.size(); ++I)
6682 Tree.merge(Elts[I]);
6683 }
6684
6685 void VisitInitListExpr(InitListExpr *ILE) {
6686 if (!SemaRef.getLangOpts().CPlusPlus11)
6687 return VisitExpr(ILE);
6688
6689 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006690 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006691 SequenceTree::Seq Parent = Region;
6692 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6693 Expr *E = ILE->getInit(I);
6694 if (!E) continue;
6695 Region = Tree.allocate(Parent);
6696 Elts.push_back(Region);
6697 Visit(E);
6698 }
6699
6700 // Forget that the initializers are sequenced.
6701 Region = Parent;
6702 for (unsigned I = 0; I < Elts.size(); ++I)
6703 Tree.merge(Elts[I]);
6704 }
6705};
6706}
6707
6708void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006709 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006710 WorkList.push_back(E);
6711 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006712 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006713 SequenceChecker(*this, Item, WorkList);
6714 }
Richard Smithc406cb72013-01-17 01:17:56 +00006715}
6716
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006717void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6718 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006719 CheckImplicitConversions(E, CheckLoc);
6720 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006721 if (!IsConstexpr && !E->isValueDependent())
6722 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006723}
6724
John McCall1f425642010-11-11 03:21:53 +00006725void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6726 FieldDecl *BitField,
6727 Expr *Init) {
6728 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6729}
6730
Mike Stump0c2ec772010-01-21 03:59:47 +00006731/// CheckParmsForFunctionDef - Check that the parameters of the given
6732/// function are appropriate for the definition of a function. This
6733/// takes care of any checks that cannot be performed on the
6734/// declaration itself, e.g., that the types of each of the function
6735/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006736bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6737 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006738 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006739 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006740 for (; P != PEnd; ++P) {
6741 ParmVarDecl *Param = *P;
6742
Mike Stump0c2ec772010-01-21 03:59:47 +00006743 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6744 // function declarator that is part of a function definition of
6745 // that function shall not have incomplete type.
6746 //
6747 // This is also C++ [dcl.fct]p6.
6748 if (!Param->isInvalidDecl() &&
6749 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006750 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006751 Param->setInvalidDecl();
6752 HasInvalidParm = true;
6753 }
6754
6755 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6756 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006757 if (CheckParameterNames &&
6758 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006759 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006760 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006761 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006762
6763 // C99 6.7.5.3p12:
6764 // If the function declarator is not part of a definition of that
6765 // function, parameters may have incomplete type and may use the [*]
6766 // notation in their sequences of declarator specifiers to specify
6767 // variable length array types.
6768 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006769 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006770 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006771 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006772 // information is added for it.
6773 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006774 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006775 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006776 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006777 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006778
6779 // MSVC destroys objects passed by value in the callee. Therefore a
6780 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006781 // object's destructor. However, we don't perform any direct access check
6782 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006783 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6784 .getCXXABI()
6785 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006786 if (!Param->isInvalidDecl()) {
6787 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6788 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6789 if (!ClassDecl->isInvalidDecl() &&
6790 !ClassDecl->hasIrrelevantDestructor() &&
6791 !ClassDecl->isDependentContext()) {
6792 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6793 MarkFunctionReferenced(Param->getLocation(), Destructor);
6794 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6795 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006796 }
6797 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006798 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006799 }
6800
6801 return HasInvalidParm;
6802}
John McCall2b5c1b22010-08-12 21:44:57 +00006803
6804/// CheckCastAlign - Implements -Wcast-align, which warns when a
6805/// pointer cast increases the alignment requirements.
6806void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6807 // This is actually a lot of work to potentially be doing on every
6808 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006809 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6810 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006811 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006812 return;
6813
6814 // Ignore dependent types.
6815 if (T->isDependentType() || Op->getType()->isDependentType())
6816 return;
6817
6818 // Require that the destination be a pointer type.
6819 const PointerType *DestPtr = T->getAs<PointerType>();
6820 if (!DestPtr) return;
6821
6822 // If the destination has alignment 1, we're done.
6823 QualType DestPointee = DestPtr->getPointeeType();
6824 if (DestPointee->isIncompleteType()) return;
6825 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6826 if (DestAlign.isOne()) return;
6827
6828 // Require that the source be a pointer type.
6829 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6830 if (!SrcPtr) return;
6831 QualType SrcPointee = SrcPtr->getPointeeType();
6832
6833 // Whitelist casts from cv void*. We already implicitly
6834 // whitelisted casts to cv void*, since they have alignment 1.
6835 // Also whitelist casts involving incomplete types, which implicitly
6836 // includes 'void'.
6837 if (SrcPointee->isIncompleteType()) return;
6838
6839 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6840 if (SrcAlign >= DestAlign) return;
6841
6842 Diag(TRange.getBegin(), diag::warn_cast_align)
6843 << Op->getType() << T
6844 << static_cast<unsigned>(SrcAlign.getQuantity())
6845 << static_cast<unsigned>(DestAlign.getQuantity())
6846 << TRange << Op->getSourceRange();
6847}
6848
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006849static const Type* getElementType(const Expr *BaseExpr) {
6850 const Type* EltType = BaseExpr->getType().getTypePtr();
6851 if (EltType->isAnyPointerType())
6852 return EltType->getPointeeType().getTypePtr();
6853 else if (EltType->isArrayType())
6854 return EltType->getBaseElementTypeUnsafe();
6855 return EltType;
6856}
6857
Chandler Carruth28389f02011-08-05 09:10:50 +00006858/// \brief Check whether this array fits the idiom of a size-one tail padded
6859/// array member of a struct.
6860///
6861/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6862/// commonly used to emulate flexible arrays in C89 code.
6863static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6864 const NamedDecl *ND) {
6865 if (Size != 1 || !ND) return false;
6866
6867 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6868 if (!FD) return false;
6869
6870 // Don't consider sizes resulting from macro expansions or template argument
6871 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006872
6873 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006874 while (TInfo) {
6875 TypeLoc TL = TInfo->getTypeLoc();
6876 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006877 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6878 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006879 TInfo = TDL->getTypeSourceInfo();
6880 continue;
6881 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006882 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6883 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006884 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6885 return false;
6886 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006887 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006888 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006889
6890 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006891 if (!RD) return false;
6892 if (RD->isUnion()) return false;
6893 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6894 if (!CRD->isStandardLayout()) return false;
6895 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006896
Benjamin Kramer8c543672011-08-06 03:04:42 +00006897 // See if this is the last field decl in the record.
6898 const Decl *D = FD;
6899 while ((D = D->getNextDeclInContext()))
6900 if (isa<FieldDecl>(D))
6901 return false;
6902 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006903}
6904
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006905void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006906 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006907 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006908 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006909 if (IndexExpr->isValueDependent())
6910 return;
6911
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006912 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006913 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006914 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006915 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006916 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006917 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006918
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006919 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006920 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006921 return;
Richard Smith13f67182011-12-16 19:31:14 +00006922 if (IndexNegated)
6923 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006924
Chandler Carruth126b1552011-08-05 08:07:29 +00006925 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00006926 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6927 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00006928 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00006929 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00006930
Ted Kremeneke4b316c2011-02-23 23:06:04 +00006931 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006932 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00006933 if (!size.isStrictlyPositive())
6934 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006935
6936 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00006937 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006938 // Make sure we're comparing apples to apples when comparing index to size
6939 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6940 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00006941 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00006942 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006943 if (ptrarith_typesize != array_typesize) {
6944 // There's a cast to a different size type involved
6945 uint64_t ratio = array_typesize / ptrarith_typesize;
6946 // TODO: Be smarter about handling cases where array_typesize is not a
6947 // multiple of ptrarith_typesize
6948 if (ptrarith_typesize * ratio == array_typesize)
6949 size *= llvm::APInt(size.getBitWidth(), ratio);
6950 }
6951 }
6952
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006953 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006954 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006955 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006956 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006957
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006958 // For array subscripting the index must be less than size, but for pointer
6959 // arithmetic also allow the index (offset) to be equal to size since
6960 // computing the next address after the end of the array is legal and
6961 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006962 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00006963 return;
6964
6965 // Also don't warn for arrays of size 1 which are members of some
6966 // structure. These are often used to approximate flexible arrays in C89
6967 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006968 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00006969 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006970
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006971 // Suppress the warning if the subscript expression (as identified by the
6972 // ']' location) and the index expression are both from macro expansions
6973 // within a system header.
6974 if (ASE) {
6975 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6976 ASE->getRBracketLoc());
6977 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6978 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6979 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00006980 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006981 return;
6982 }
6983 }
6984
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006985 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006986 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006987 DiagID = diag::warn_array_index_exceeds_bounds;
6988
6989 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6990 PDiag(DiagID) << index.toString(10, true)
6991 << size.toString(10, true)
6992 << (unsigned)size.getLimitedValue(~0U)
6993 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006994 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006995 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006996 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006997 DiagID = diag::warn_ptr_arith_precedes_bounds;
6998 if (index.isNegative()) index = -index;
6999 }
7000
7001 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7002 PDiag(DiagID) << index.toString(10, true)
7003 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007004 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007005
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007006 if (!ND) {
7007 // Try harder to find a NamedDecl to point at in the note.
7008 while (const ArraySubscriptExpr *ASE =
7009 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7010 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7011 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7012 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7013 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7014 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7015 }
7016
Chandler Carruth1af88f12011-02-17 21:10:52 +00007017 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007018 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7019 PDiag(diag::note_array_index_out_of_bounds)
7020 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007021}
7022
Ted Kremenekdf26df72011-03-01 18:41:00 +00007023void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007024 int AllowOnePastEnd = 0;
7025 while (expr) {
7026 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007027 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007028 case Stmt::ArraySubscriptExprClass: {
7029 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007030 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007031 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007032 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007033 }
7034 case Stmt::UnaryOperatorClass: {
7035 // Only unwrap the * and & unary operators
7036 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7037 expr = UO->getSubExpr();
7038 switch (UO->getOpcode()) {
7039 case UO_AddrOf:
7040 AllowOnePastEnd++;
7041 break;
7042 case UO_Deref:
7043 AllowOnePastEnd--;
7044 break;
7045 default:
7046 return;
7047 }
7048 break;
7049 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007050 case Stmt::ConditionalOperatorClass: {
7051 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7052 if (const Expr *lhs = cond->getLHS())
7053 CheckArrayAccess(lhs);
7054 if (const Expr *rhs = cond->getRHS())
7055 CheckArrayAccess(rhs);
7056 return;
7057 }
7058 default:
7059 return;
7060 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007061 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007062}
John McCall31168b02011-06-15 23:02:42 +00007063
7064//===--- CHECK: Objective-C retain cycles ----------------------------------//
7065
7066namespace {
7067 struct RetainCycleOwner {
7068 RetainCycleOwner() : Variable(0), Indirect(false) {}
7069 VarDecl *Variable;
7070 SourceRange Range;
7071 SourceLocation Loc;
7072 bool Indirect;
7073
7074 void setLocsFrom(Expr *e) {
7075 Loc = e->getExprLoc();
7076 Range = e->getSourceRange();
7077 }
7078 };
7079}
7080
7081/// Consider whether capturing the given variable can possibly lead to
7082/// a retain cycle.
7083static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007084 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007085 // lifetime. In MRR, it's captured strongly if the variable is
7086 // __block and has an appropriate type.
7087 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7088 return false;
7089
7090 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007091 if (ref)
7092 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007093 return true;
7094}
7095
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007096static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007097 while (true) {
7098 e = e->IgnoreParens();
7099 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7100 switch (cast->getCastKind()) {
7101 case CK_BitCast:
7102 case CK_LValueBitCast:
7103 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007104 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007105 e = cast->getSubExpr();
7106 continue;
7107
John McCall31168b02011-06-15 23:02:42 +00007108 default:
7109 return false;
7110 }
7111 }
7112
7113 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7114 ObjCIvarDecl *ivar = ref->getDecl();
7115 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7116 return false;
7117
7118 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007119 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007120 return false;
7121
7122 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7123 owner.Indirect = true;
7124 return true;
7125 }
7126
7127 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7128 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7129 if (!var) return false;
7130 return considerVariable(var, ref, owner);
7131 }
7132
John McCall31168b02011-06-15 23:02:42 +00007133 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7134 if (member->isArrow()) return false;
7135
7136 // Don't count this as an indirect ownership.
7137 e = member->getBase();
7138 continue;
7139 }
7140
John McCallfe96e0b2011-11-06 09:01:30 +00007141 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7142 // Only pay attention to pseudo-objects on property references.
7143 ObjCPropertyRefExpr *pre
7144 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7145 ->IgnoreParens());
7146 if (!pre) return false;
7147 if (pre->isImplicitProperty()) return false;
7148 ObjCPropertyDecl *property = pre->getExplicitProperty();
7149 if (!property->isRetaining() &&
7150 !(property->getPropertyIvarDecl() &&
7151 property->getPropertyIvarDecl()->getType()
7152 .getObjCLifetime() == Qualifiers::OCL_Strong))
7153 return false;
7154
7155 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007156 if (pre->isSuperReceiver()) {
7157 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7158 if (!owner.Variable)
7159 return false;
7160 owner.Loc = pre->getLocation();
7161 owner.Range = pre->getSourceRange();
7162 return true;
7163 }
John McCallfe96e0b2011-11-06 09:01:30 +00007164 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7165 ->getSourceExpr());
7166 continue;
7167 }
7168
John McCall31168b02011-06-15 23:02:42 +00007169 // Array ivars?
7170
7171 return false;
7172 }
7173}
7174
7175namespace {
7176 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7177 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7178 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7179 Variable(variable), Capturer(0) {}
7180
7181 VarDecl *Variable;
7182 Expr *Capturer;
7183
7184 void VisitDeclRefExpr(DeclRefExpr *ref) {
7185 if (ref->getDecl() == Variable && !Capturer)
7186 Capturer = ref;
7187 }
7188
John McCall31168b02011-06-15 23:02:42 +00007189 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7190 if (Capturer) return;
7191 Visit(ref->getBase());
7192 if (Capturer && ref->isFreeIvar())
7193 Capturer = ref;
7194 }
7195
7196 void VisitBlockExpr(BlockExpr *block) {
7197 // Look inside nested blocks
7198 if (block->getBlockDecl()->capturesVariable(Variable))
7199 Visit(block->getBlockDecl()->getBody());
7200 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007201
7202 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7203 if (Capturer) return;
7204 if (OVE->getSourceExpr())
7205 Visit(OVE->getSourceExpr());
7206 }
John McCall31168b02011-06-15 23:02:42 +00007207 };
7208}
7209
7210/// Check whether the given argument is a block which captures a
7211/// variable.
7212static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7213 assert(owner.Variable && owner.Loc.isValid());
7214
7215 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007216
7217 // Look through [^{...} copy] and Block_copy(^{...}).
7218 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7219 Selector Cmd = ME->getSelector();
7220 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7221 e = ME->getInstanceReceiver();
7222 if (!e)
7223 return 0;
7224 e = e->IgnoreParenCasts();
7225 }
7226 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7227 if (CE->getNumArgs() == 1) {
7228 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007229 if (Fn) {
7230 const IdentifierInfo *FnI = Fn->getIdentifier();
7231 if (FnI && FnI->isStr("_Block_copy")) {
7232 e = CE->getArg(0)->IgnoreParenCasts();
7233 }
7234 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007235 }
7236 }
7237
John McCall31168b02011-06-15 23:02:42 +00007238 BlockExpr *block = dyn_cast<BlockExpr>(e);
7239 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7240 return 0;
7241
7242 FindCaptureVisitor visitor(S.Context, owner.Variable);
7243 visitor.Visit(block->getBlockDecl()->getBody());
7244 return visitor.Capturer;
7245}
7246
7247static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7248 RetainCycleOwner &owner) {
7249 assert(capturer);
7250 assert(owner.Variable && owner.Loc.isValid());
7251
7252 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7253 << owner.Variable << capturer->getSourceRange();
7254 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7255 << owner.Indirect << owner.Range;
7256}
7257
7258/// Check for a keyword selector that starts with the word 'add' or
7259/// 'set'.
7260static bool isSetterLikeSelector(Selector sel) {
7261 if (sel.isUnarySelector()) return false;
7262
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007263 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007264 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007265 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007266 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007267 else if (str.startswith("add")) {
7268 // Specially whitelist 'addOperationWithBlock:'.
7269 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7270 return false;
7271 str = str.substr(3);
7272 }
John McCall31168b02011-06-15 23:02:42 +00007273 else
7274 return false;
7275
7276 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007277 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007278}
7279
7280/// Check a message send to see if it's likely to cause a retain cycle.
7281void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7282 // Only check instance methods whose selector looks like a setter.
7283 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7284 return;
7285
7286 // Try to find a variable that the receiver is strongly owned by.
7287 RetainCycleOwner owner;
7288 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007289 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007290 return;
7291 } else {
7292 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7293 owner.Variable = getCurMethodDecl()->getSelfDecl();
7294 owner.Loc = msg->getSuperLoc();
7295 owner.Range = msg->getSuperLoc();
7296 }
7297
7298 // Check whether the receiver is captured by any of the arguments.
7299 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7300 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7301 return diagnoseRetainCycle(*this, capturer, owner);
7302}
7303
7304/// Check a property assign to see if it's likely to cause a retain cycle.
7305void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7306 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007307 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007308 return;
7309
7310 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7311 diagnoseRetainCycle(*this, capturer, owner);
7312}
7313
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007314void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7315 RetainCycleOwner Owner;
7316 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
7317 return;
7318
7319 // Because we don't have an expression for the variable, we have to set the
7320 // location explicitly here.
7321 Owner.Loc = Var->getLocation();
7322 Owner.Range = Var->getSourceRange();
7323
7324 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7325 diagnoseRetainCycle(*this, Capturer, Owner);
7326}
7327
Ted Kremenek9304da92012-12-21 08:04:28 +00007328static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7329 Expr *RHS, bool isProperty) {
7330 // Check if RHS is an Objective-C object literal, which also can get
7331 // immediately zapped in a weak reference. Note that we explicitly
7332 // allow ObjCStringLiterals, since those are designed to never really die.
7333 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007334
Ted Kremenek64873352012-12-21 22:46:35 +00007335 // This enum needs to match with the 'select' in
7336 // warn_objc_arc_literal_assign (off-by-1).
7337 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7338 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7339 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007340
7341 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007342 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007343 << (isProperty ? 0 : 1)
7344 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007345
7346 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007347}
7348
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007349static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7350 Qualifiers::ObjCLifetime LT,
7351 Expr *RHS, bool isProperty) {
7352 // Strip off any implicit cast added to get to the one ARC-specific.
7353 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7354 if (cast->getCastKind() == CK_ARCConsumeObject) {
7355 S.Diag(Loc, diag::warn_arc_retained_assign)
7356 << (LT == Qualifiers::OCL_ExplicitNone)
7357 << (isProperty ? 0 : 1)
7358 << RHS->getSourceRange();
7359 return true;
7360 }
7361 RHS = cast->getSubExpr();
7362 }
7363
7364 if (LT == Qualifiers::OCL_Weak &&
7365 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7366 return true;
7367
7368 return false;
7369}
7370
Ted Kremenekb36234d2012-12-21 08:04:20 +00007371bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7372 QualType LHS, Expr *RHS) {
7373 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7374
7375 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7376 return false;
7377
7378 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7379 return true;
7380
7381 return false;
7382}
7383
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007384void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7385 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007386 QualType LHSType;
7387 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007388 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007389 ObjCPropertyRefExpr *PRE
7390 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7391 if (PRE && !PRE->isImplicitProperty()) {
7392 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7393 if (PD)
7394 LHSType = PD->getType();
7395 }
7396
7397 if (LHSType.isNull())
7398 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007399
7400 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7401
7402 if (LT == Qualifiers::OCL_Weak) {
7403 DiagnosticsEngine::Level Level =
7404 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7405 if (Level != DiagnosticsEngine::Ignored)
7406 getCurFunction()->markSafeWeakUse(LHS);
7407 }
7408
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007409 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7410 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007411
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007412 // FIXME. Check for other life times.
7413 if (LT != Qualifiers::OCL_None)
7414 return;
7415
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007416 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007417 if (PRE->isImplicitProperty())
7418 return;
7419 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7420 if (!PD)
7421 return;
7422
Bill Wendling44426052012-12-20 19:22:21 +00007423 unsigned Attributes = PD->getPropertyAttributes();
7424 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007425 // when 'assign' attribute was not explicitly specified
7426 // by user, ignore it and rely on property type itself
7427 // for lifetime info.
7428 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7429 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7430 LHSType->isObjCRetainableType())
7431 return;
7432
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007433 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007434 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007435 Diag(Loc, diag::warn_arc_retained_property_assign)
7436 << RHS->getSourceRange();
7437 return;
7438 }
7439 RHS = cast->getSubExpr();
7440 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007441 }
Bill Wendling44426052012-12-20 19:22:21 +00007442 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007443 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7444 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007445 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007446 }
7447}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007448
7449//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7450
7451namespace {
7452bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7453 SourceLocation StmtLoc,
7454 const NullStmt *Body) {
7455 // Do not warn if the body is a macro that expands to nothing, e.g:
7456 //
7457 // #define CALL(x)
7458 // if (condition)
7459 // CALL(0);
7460 //
7461 if (Body->hasLeadingEmptyMacro())
7462 return false;
7463
7464 // Get line numbers of statement and body.
7465 bool StmtLineInvalid;
7466 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7467 &StmtLineInvalid);
7468 if (StmtLineInvalid)
7469 return false;
7470
7471 bool BodyLineInvalid;
7472 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7473 &BodyLineInvalid);
7474 if (BodyLineInvalid)
7475 return false;
7476
7477 // Warn if null statement and body are on the same line.
7478 if (StmtLine != BodyLine)
7479 return false;
7480
7481 return true;
7482}
7483} // Unnamed namespace
7484
7485void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7486 const Stmt *Body,
7487 unsigned DiagID) {
7488 // Since this is a syntactic check, don't emit diagnostic for template
7489 // instantiations, this just adds noise.
7490 if (CurrentInstantiationScope)
7491 return;
7492
7493 // The body should be a null statement.
7494 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7495 if (!NBody)
7496 return;
7497
7498 // Do the usual checks.
7499 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7500 return;
7501
7502 Diag(NBody->getSemiLoc(), DiagID);
7503 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7504}
7505
7506void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7507 const Stmt *PossibleBody) {
7508 assert(!CurrentInstantiationScope); // Ensured by caller
7509
7510 SourceLocation StmtLoc;
7511 const Stmt *Body;
7512 unsigned DiagID;
7513 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7514 StmtLoc = FS->getRParenLoc();
7515 Body = FS->getBody();
7516 DiagID = diag::warn_empty_for_body;
7517 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7518 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7519 Body = WS->getBody();
7520 DiagID = diag::warn_empty_while_body;
7521 } else
7522 return; // Neither `for' nor `while'.
7523
7524 // The body should be a null statement.
7525 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7526 if (!NBody)
7527 return;
7528
7529 // Skip expensive checks if diagnostic is disabled.
7530 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7531 DiagnosticsEngine::Ignored)
7532 return;
7533
7534 // Do the usual checks.
7535 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7536 return;
7537
7538 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7539 // noise level low, emit diagnostics only if for/while is followed by a
7540 // CompoundStmt, e.g.:
7541 // for (int i = 0; i < n; i++);
7542 // {
7543 // a(i);
7544 // }
7545 // or if for/while is followed by a statement with more indentation
7546 // than for/while itself:
7547 // for (int i = 0; i < n; i++);
7548 // a(i);
7549 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7550 if (!ProbableTypo) {
7551 bool BodyColInvalid;
7552 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7553 PossibleBody->getLocStart(),
7554 &BodyColInvalid);
7555 if (BodyColInvalid)
7556 return;
7557
7558 bool StmtColInvalid;
7559 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7560 S->getLocStart(),
7561 &StmtColInvalid);
7562 if (StmtColInvalid)
7563 return;
7564
7565 if (BodyCol > StmtCol)
7566 ProbableTypo = true;
7567 }
7568
7569 if (ProbableTypo) {
7570 Diag(NBody->getSemiLoc(), DiagID);
7571 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7572 }
7573}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007574
7575//===--- Layout compatibility ----------------------------------------------//
7576
7577namespace {
7578
7579bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7580
7581/// \brief Check if two enumeration types are layout-compatible.
7582bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7583 // C++11 [dcl.enum] p8:
7584 // Two enumeration types are layout-compatible if they have the same
7585 // underlying type.
7586 return ED1->isComplete() && ED2->isComplete() &&
7587 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7588}
7589
7590/// \brief Check if two fields are layout-compatible.
7591bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7592 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7593 return false;
7594
7595 if (Field1->isBitField() != Field2->isBitField())
7596 return false;
7597
7598 if (Field1->isBitField()) {
7599 // Make sure that the bit-fields are the same length.
7600 unsigned Bits1 = Field1->getBitWidthValue(C);
7601 unsigned Bits2 = Field2->getBitWidthValue(C);
7602
7603 if (Bits1 != Bits2)
7604 return false;
7605 }
7606
7607 return true;
7608}
7609
7610/// \brief Check if two standard-layout structs are layout-compatible.
7611/// (C++11 [class.mem] p17)
7612bool isLayoutCompatibleStruct(ASTContext &C,
7613 RecordDecl *RD1,
7614 RecordDecl *RD2) {
7615 // If both records are C++ classes, check that base classes match.
7616 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7617 // If one of records is a CXXRecordDecl we are in C++ mode,
7618 // thus the other one is a CXXRecordDecl, too.
7619 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7620 // Check number of base classes.
7621 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7622 return false;
7623
7624 // Check the base classes.
7625 for (CXXRecordDecl::base_class_const_iterator
7626 Base1 = D1CXX->bases_begin(),
7627 BaseEnd1 = D1CXX->bases_end(),
7628 Base2 = D2CXX->bases_begin();
7629 Base1 != BaseEnd1;
7630 ++Base1, ++Base2) {
7631 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7632 return false;
7633 }
7634 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7635 // If only RD2 is a C++ class, it should have zero base classes.
7636 if (D2CXX->getNumBases() > 0)
7637 return false;
7638 }
7639
7640 // Check the fields.
7641 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7642 Field2End = RD2->field_end(),
7643 Field1 = RD1->field_begin(),
7644 Field1End = RD1->field_end();
7645 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7646 if (!isLayoutCompatible(C, *Field1, *Field2))
7647 return false;
7648 }
7649 if (Field1 != Field1End || Field2 != Field2End)
7650 return false;
7651
7652 return true;
7653}
7654
7655/// \brief Check if two standard-layout unions are layout-compatible.
7656/// (C++11 [class.mem] p18)
7657bool isLayoutCompatibleUnion(ASTContext &C,
7658 RecordDecl *RD1,
7659 RecordDecl *RD2) {
7660 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007661 for (auto *Field2 : RD2->fields())
7662 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007663
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007664 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007665 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7666 I = UnmatchedFields.begin(),
7667 E = UnmatchedFields.end();
7668
7669 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007670 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007671 bool Result = UnmatchedFields.erase(*I);
7672 (void) Result;
7673 assert(Result);
7674 break;
7675 }
7676 }
7677 if (I == E)
7678 return false;
7679 }
7680
7681 return UnmatchedFields.empty();
7682}
7683
7684bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7685 if (RD1->isUnion() != RD2->isUnion())
7686 return false;
7687
7688 if (RD1->isUnion())
7689 return isLayoutCompatibleUnion(C, RD1, RD2);
7690 else
7691 return isLayoutCompatibleStruct(C, RD1, RD2);
7692}
7693
7694/// \brief Check if two types are layout-compatible in C++11 sense.
7695bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7696 if (T1.isNull() || T2.isNull())
7697 return false;
7698
7699 // C++11 [basic.types] p11:
7700 // If two types T1 and T2 are the same type, then T1 and T2 are
7701 // layout-compatible types.
7702 if (C.hasSameType(T1, T2))
7703 return true;
7704
7705 T1 = T1.getCanonicalType().getUnqualifiedType();
7706 T2 = T2.getCanonicalType().getUnqualifiedType();
7707
7708 const Type::TypeClass TC1 = T1->getTypeClass();
7709 const Type::TypeClass TC2 = T2->getTypeClass();
7710
7711 if (TC1 != TC2)
7712 return false;
7713
7714 if (TC1 == Type::Enum) {
7715 return isLayoutCompatible(C,
7716 cast<EnumType>(T1)->getDecl(),
7717 cast<EnumType>(T2)->getDecl());
7718 } else if (TC1 == Type::Record) {
7719 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7720 return false;
7721
7722 return isLayoutCompatible(C,
7723 cast<RecordType>(T1)->getDecl(),
7724 cast<RecordType>(T2)->getDecl());
7725 }
7726
7727 return false;
7728}
7729}
7730
7731//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7732
7733namespace {
7734/// \brief Given a type tag expression find the type tag itself.
7735///
7736/// \param TypeExpr Type tag expression, as it appears in user's code.
7737///
7738/// \param VD Declaration of an identifier that appears in a type tag.
7739///
7740/// \param MagicValue Type tag magic value.
7741bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7742 const ValueDecl **VD, uint64_t *MagicValue) {
7743 while(true) {
7744 if (!TypeExpr)
7745 return false;
7746
7747 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7748
7749 switch (TypeExpr->getStmtClass()) {
7750 case Stmt::UnaryOperatorClass: {
7751 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7752 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7753 TypeExpr = UO->getSubExpr();
7754 continue;
7755 }
7756 return false;
7757 }
7758
7759 case Stmt::DeclRefExprClass: {
7760 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7761 *VD = DRE->getDecl();
7762 return true;
7763 }
7764
7765 case Stmt::IntegerLiteralClass: {
7766 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7767 llvm::APInt MagicValueAPInt = IL->getValue();
7768 if (MagicValueAPInt.getActiveBits() <= 64) {
7769 *MagicValue = MagicValueAPInt.getZExtValue();
7770 return true;
7771 } else
7772 return false;
7773 }
7774
7775 case Stmt::BinaryConditionalOperatorClass:
7776 case Stmt::ConditionalOperatorClass: {
7777 const AbstractConditionalOperator *ACO =
7778 cast<AbstractConditionalOperator>(TypeExpr);
7779 bool Result;
7780 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7781 if (Result)
7782 TypeExpr = ACO->getTrueExpr();
7783 else
7784 TypeExpr = ACO->getFalseExpr();
7785 continue;
7786 }
7787 return false;
7788 }
7789
7790 case Stmt::BinaryOperatorClass: {
7791 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7792 if (BO->getOpcode() == BO_Comma) {
7793 TypeExpr = BO->getRHS();
7794 continue;
7795 }
7796 return false;
7797 }
7798
7799 default:
7800 return false;
7801 }
7802 }
7803}
7804
7805/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7806///
7807/// \param TypeExpr Expression that specifies a type tag.
7808///
7809/// \param MagicValues Registered magic values.
7810///
7811/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7812/// kind.
7813///
7814/// \param TypeInfo Information about the corresponding C type.
7815///
7816/// \returns true if the corresponding C type was found.
7817bool GetMatchingCType(
7818 const IdentifierInfo *ArgumentKind,
7819 const Expr *TypeExpr, const ASTContext &Ctx,
7820 const llvm::DenseMap<Sema::TypeTagMagicValue,
7821 Sema::TypeTagData> *MagicValues,
7822 bool &FoundWrongKind,
7823 Sema::TypeTagData &TypeInfo) {
7824 FoundWrongKind = false;
7825
7826 // Variable declaration that has type_tag_for_datatype attribute.
7827 const ValueDecl *VD = NULL;
7828
7829 uint64_t MagicValue;
7830
7831 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7832 return false;
7833
7834 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00007835 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007836 if (I->getArgumentKind() != ArgumentKind) {
7837 FoundWrongKind = true;
7838 return false;
7839 }
7840 TypeInfo.Type = I->getMatchingCType();
7841 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7842 TypeInfo.MustBeNull = I->getMustBeNull();
7843 return true;
7844 }
7845 return false;
7846 }
7847
7848 if (!MagicValues)
7849 return false;
7850
7851 llvm::DenseMap<Sema::TypeTagMagicValue,
7852 Sema::TypeTagData>::const_iterator I =
7853 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7854 if (I == MagicValues->end())
7855 return false;
7856
7857 TypeInfo = I->second;
7858 return true;
7859}
7860} // unnamed namespace
7861
7862void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7863 uint64_t MagicValue, QualType Type,
7864 bool LayoutCompatible,
7865 bool MustBeNull) {
7866 if (!TypeTagForDatatypeMagicValues)
7867 TypeTagForDatatypeMagicValues.reset(
7868 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7869
7870 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7871 (*TypeTagForDatatypeMagicValues)[Magic] =
7872 TypeTagData(Type, LayoutCompatible, MustBeNull);
7873}
7874
7875namespace {
7876bool IsSameCharType(QualType T1, QualType T2) {
7877 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7878 if (!BT1)
7879 return false;
7880
7881 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7882 if (!BT2)
7883 return false;
7884
7885 BuiltinType::Kind T1Kind = BT1->getKind();
7886 BuiltinType::Kind T2Kind = BT2->getKind();
7887
7888 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7889 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7890 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7891 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7892}
7893} // unnamed namespace
7894
7895void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7896 const Expr * const *ExprArgs) {
7897 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7898 bool IsPointerAttr = Attr->getIsPointer();
7899
7900 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7901 bool FoundWrongKind;
7902 TypeTagData TypeInfo;
7903 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7904 TypeTagForDatatypeMagicValues.get(),
7905 FoundWrongKind, TypeInfo)) {
7906 if (FoundWrongKind)
7907 Diag(TypeTagExpr->getExprLoc(),
7908 diag::warn_type_tag_for_datatype_wrong_kind)
7909 << TypeTagExpr->getSourceRange();
7910 return;
7911 }
7912
7913 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7914 if (IsPointerAttr) {
7915 // Skip implicit cast of pointer to `void *' (as a function argument).
7916 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007917 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007918 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007919 ArgumentExpr = ICE->getSubExpr();
7920 }
7921 QualType ArgumentType = ArgumentExpr->getType();
7922
7923 // Passing a `void*' pointer shouldn't trigger a warning.
7924 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7925 return;
7926
7927 if (TypeInfo.MustBeNull) {
7928 // Type tag with matching void type requires a null pointer.
7929 if (!ArgumentExpr->isNullPointerConstant(Context,
7930 Expr::NPC_ValueDependentIsNotNull)) {
7931 Diag(ArgumentExpr->getExprLoc(),
7932 diag::warn_type_safety_null_pointer_required)
7933 << ArgumentKind->getName()
7934 << ArgumentExpr->getSourceRange()
7935 << TypeTagExpr->getSourceRange();
7936 }
7937 return;
7938 }
7939
7940 QualType RequiredType = TypeInfo.Type;
7941 if (IsPointerAttr)
7942 RequiredType = Context.getPointerType(RequiredType);
7943
7944 bool mismatch = false;
7945 if (!TypeInfo.LayoutCompatible) {
7946 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7947
7948 // C++11 [basic.fundamental] p1:
7949 // Plain char, signed char, and unsigned char are three distinct types.
7950 //
7951 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7952 // char' depending on the current char signedness mode.
7953 if (mismatch)
7954 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7955 RequiredType->getPointeeType())) ||
7956 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7957 mismatch = false;
7958 } else
7959 if (IsPointerAttr)
7960 mismatch = !isLayoutCompatible(Context,
7961 ArgumentType->getPointeeType(),
7962 RequiredType->getPointeeType());
7963 else
7964 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7965
7966 if (mismatch)
7967 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00007968 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007969 << TypeInfo.LayoutCompatible << RequiredType
7970 << ArgumentExpr->getSourceRange()
7971 << TypeTagExpr->getSourceRange();
7972}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007973