blob: 82b3da6c2e1a0039b703ee5680132a506896db11 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattnere925d612010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCalldadc5752010-08-24 06:29:42 +0000114ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000117
Chris Lattner3be167f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000142 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000147 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000154 if (SemaBuiltinUnorderedCompare(TheCall))
155 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000156 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
159 return ExprError();
160 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000166 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000167 return ExprError();
168 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000169 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000173 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000174 if (SemaBuiltinPrefetch(TheCall))
175 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000176 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000177 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000178 if (SemaBuiltinObjectSize(TheCall))
179 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000180 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
183 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000184 break;
John McCallbebede42011-02-26 05:39:39 +0000185
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
189 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000190 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000193 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000194 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000200 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000206 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000224 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000230 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000236 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000242 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000248 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000254 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000260 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000266 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000272 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000278 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000284 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000289#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000290 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000291 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000292 return ExprError();
293 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
296 return ExprError();
297 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000298 }
299
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000303 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307 return ExprError();
308 break;
Tim Northover2fe823a2013-08-01 09:23:19 +0000309 case llvm::Triple::aarch64:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311 return ExprError();
312 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318 return ExprError();
319 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000320 default:
321 break;
322 }
323 }
324
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000325 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000326}
327
Nate Begeman91e1fea2010-06-14 05:21:25 +0000328// Get the valid immediate range for the specified NEON type code.
329static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000330 NeonTypeFlags Type(t);
331 int IsQuad = Type.isQuad();
332 switch (Type.getEltType()) {
333 case NeonTypeFlags::Int8:
334 case NeonTypeFlags::Poly8:
335 return shift ? 7 : (8 << IsQuad) - 1;
336 case NeonTypeFlags::Int16:
337 case NeonTypeFlags::Poly16:
338 return shift ? 15 : (4 << IsQuad) - 1;
339 case NeonTypeFlags::Int32:
340 return shift ? 31 : (2 << IsQuad) - 1;
341 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000342 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000343 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000344 case NeonTypeFlags::Poly128:
345 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000346 case NeonTypeFlags::Float16:
347 assert(!shift && "cannot shift float types!");
348 return (4 << IsQuad) - 1;
349 case NeonTypeFlags::Float32:
350 assert(!shift && "cannot shift float types!");
351 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000352 case NeonTypeFlags::Float64:
353 assert(!shift && "cannot shift float types!");
354 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000355 }
David Blaikie8a40f702012-01-17 06:56:22 +0000356 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000357}
358
Bob Wilsone4d77232011-11-08 05:04:11 +0000359/// getNeonEltType - Return the QualType corresponding to the elements of
360/// the vector type specified by the NeonTypeFlags. This is used to check
361/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000362static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
363 bool IsAArch64) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000364 switch (Flags.getEltType()) {
365 case NeonTypeFlags::Int8:
366 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
367 case NeonTypeFlags::Int16:
368 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
369 case NeonTypeFlags::Int32:
370 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
371 case NeonTypeFlags::Int64:
372 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
373 case NeonTypeFlags::Poly8:
Kevin Qincaac85e2013-11-14 03:29:16 +0000374 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000375 case NeonTypeFlags::Poly16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000376 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
377 case NeonTypeFlags::Poly64:
378 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000379 case NeonTypeFlags::Poly128:
380 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000381 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000382 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000383 case NeonTypeFlags::Float32:
384 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000385 case NeonTypeFlags::Float64:
386 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000387 }
David Blaikie8a40f702012-01-17 06:56:22 +0000388 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000389}
390
Tim Northover2fe823a2013-08-01 09:23:19 +0000391bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
392 CallExpr *TheCall) {
393
394 llvm::APSInt Result;
395
396 uint64_t mask = 0;
397 unsigned TV = 0;
398 int PtrArgNum = -1;
399 bool HasConstPtr = false;
400 switch (BuiltinID) {
401#define GET_NEON_AARCH64_OVERLOAD_CHECK
402#include "clang/Basic/arm_neon.inc"
403#undef GET_NEON_AARCH64_OVERLOAD_CHECK
404 }
405
406 // For NEON intrinsics which are overloaded on vector element type, validate
407 // the immediate which specifies which variant to emit.
408 unsigned ImmArg = TheCall->getNumArgs() - 1;
409 if (mask) {
410 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
411 return true;
412
413 TV = Result.getLimitedValue(64);
414 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
415 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
416 << TheCall->getArg(ImmArg)->getSourceRange();
417 }
418
419 if (PtrArgNum >= 0) {
420 // Check that pointer arguments have the specified type.
421 Expr *Arg = TheCall->getArg(PtrArgNum);
422 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
423 Arg = ICE->getSubExpr();
424 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
425 QualType RHSTy = RHS.get()->getType();
Kevin Qincaac85e2013-11-14 03:29:16 +0000426 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, true);
Tim Northover2fe823a2013-08-01 09:23:19 +0000427 if (HasConstPtr)
428 EltTy = EltTy.withConst();
429 QualType LHSTy = Context.getPointerType(EltTy);
430 AssignConvertType ConvTy;
431 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
432 if (RHS.isInvalid())
433 return true;
434 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
435 RHS.get(), AA_Assigning))
436 return true;
437 }
438
439 // For NEON intrinsics which take an immediate value as part of the
440 // instruction, range check them here.
441 unsigned i = 0, l = 0, u = 0;
442 switch (BuiltinID) {
443 default:
444 return false;
445#define GET_NEON_AARCH64_IMMEDIATE_CHECK
446#include "clang/Basic/arm_neon.inc"
447#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
448 }
449 ;
450
451 // We can't check the value of a dependent argument.
452 if (TheCall->getArg(i)->isTypeDependent() ||
453 TheCall->getArg(i)->isValueDependent())
454 return false;
455
456 // Check that the immediate argument is actually a constant.
457 if (SemaBuiltinConstantArg(TheCall, i, Result))
458 return true;
459
460 // Range check against the upper/lower values for this isntruction.
461 unsigned Val = Result.getZExtValue();
462 if (Val < l || Val > (u + l))
463 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
464 << l << u + l << TheCall->getArg(i)->getSourceRange();
465
466 return false;
467}
468
Tim Northover6aacd492013-07-16 09:47:53 +0000469bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
470 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
471 BuiltinID == ARM::BI__builtin_arm_strex) &&
472 "unexpected ARM builtin");
473 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
474
475 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
476
477 // Ensure that we have the proper number of arguments.
478 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
479 return true;
480
481 // Inspect the pointer argument of the atomic builtin. This should always be
482 // a pointer type, whose element is an integral scalar or pointer type.
483 // Because it is a pointer type, we don't have to worry about any implicit
484 // casts here.
485 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
486 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
487 if (PointerArgRes.isInvalid())
488 return true;
489 PointerArg = PointerArgRes.take();
490
491 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
492 if (!pointerType) {
493 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
494 << PointerArg->getType() << PointerArg->getSourceRange();
495 return true;
496 }
497
498 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
499 // task is to insert the appropriate casts into the AST. First work out just
500 // what the appropriate type is.
501 QualType ValType = pointerType->getPointeeType();
502 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
503 if (IsLdrex)
504 AddrType.addConst();
505
506 // Issue a warning if the cast is dodgy.
507 CastKind CastNeeded = CK_NoOp;
508 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
509 CastNeeded = CK_BitCast;
510 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
511 << PointerArg->getType()
512 << Context.getPointerType(AddrType)
513 << AA_Passing << PointerArg->getSourceRange();
514 }
515
516 // Finally, do the cast and replace the argument with the corrected version.
517 AddrType = Context.getPointerType(AddrType);
518 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
519 if (PointerArgRes.isInvalid())
520 return true;
521 PointerArg = PointerArgRes.take();
522
523 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
524
525 // In general, we allow ints, floats and pointers to be loaded and stored.
526 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
527 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
528 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
529 << PointerArg->getType() << PointerArg->getSourceRange();
530 return true;
531 }
532
533 // But ARM doesn't have instructions to deal with 128-bit versions.
534 if (Context.getTypeSize(ValType) > 64) {
535 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
536 << PointerArg->getType() << PointerArg->getSourceRange();
537 return true;
538 }
539
540 switch (ValType.getObjCLifetime()) {
541 case Qualifiers::OCL_None:
542 case Qualifiers::OCL_ExplicitNone:
543 // okay
544 break;
545
546 case Qualifiers::OCL_Weak:
547 case Qualifiers::OCL_Strong:
548 case Qualifiers::OCL_Autoreleasing:
549 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
550 << ValType << PointerArg->getSourceRange();
551 return true;
552 }
553
554
555 if (IsLdrex) {
556 TheCall->setType(ValType);
557 return false;
558 }
559
560 // Initialize the argument to be stored.
561 ExprResult ValArg = TheCall->getArg(0);
562 InitializedEntity Entity = InitializedEntity::InitializeParameter(
563 Context, ValType, /*consume*/ false);
564 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
565 if (ValArg.isInvalid())
566 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000567 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000568
569 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
570 // but the custom checker bypasses all default analysis.
571 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000572 return false;
573}
574
Nate Begeman4904e322010-06-08 02:47:44 +0000575bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000576 llvm::APSInt Result;
577
Tim Northover6aacd492013-07-16 09:47:53 +0000578 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
579 BuiltinID == ARM::BI__builtin_arm_strex) {
580 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
581 }
582
Richard Smith7d6d47b2012-08-14 01:28:02 +0000583 uint64_t mask = 0;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000584 unsigned TV = 0;
Bob Wilson89d14242011-11-16 21:32:23 +0000585 int PtrArgNum = -1;
Bob Wilsone4d77232011-11-08 05:04:11 +0000586 bool HasConstPtr = false;
Nate Begeman55483092010-06-09 01:10:23 +0000587 switch (BuiltinID) {
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000588#define GET_NEON_OVERLOAD_CHECK
589#include "clang/Basic/arm_neon.inc"
590#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman55483092010-06-09 01:10:23 +0000591 }
592
Nate Begemand773fe62010-06-13 04:47:52 +0000593 // For NEON intrinsics which are overloaded on vector element type, validate
594 // the immediate which specifies which variant to emit.
Bob Wilsone4d77232011-11-08 05:04:11 +0000595 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begemand773fe62010-06-13 04:47:52 +0000596 if (mask) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000597 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begemand773fe62010-06-13 04:47:52 +0000598 return true;
599
Bob Wilson98bc98c2011-11-08 01:16:11 +0000600 TV = Result.getLimitedValue(64);
Richard Smith7d6d47b2012-08-14 01:28:02 +0000601 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begemand773fe62010-06-13 04:47:52 +0000602 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilsone4d77232011-11-08 05:04:11 +0000603 << TheCall->getArg(ImmArg)->getSourceRange();
604 }
605
Bob Wilson89d14242011-11-16 21:32:23 +0000606 if (PtrArgNum >= 0) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000607 // Check that pointer arguments have the specified type.
Bob Wilson89d14242011-11-16 21:32:23 +0000608 Expr *Arg = TheCall->getArg(PtrArgNum);
609 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
610 Arg = ICE->getSubExpr();
611 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
612 QualType RHSTy = RHS.get()->getType();
Kevin Qincaac85e2013-11-14 03:29:16 +0000613 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, false);
Bob Wilson89d14242011-11-16 21:32:23 +0000614 if (HasConstPtr)
615 EltTy = EltTy.withConst();
616 QualType LHSTy = Context.getPointerType(EltTy);
617 AssignConvertType ConvTy;
618 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
619 if (RHS.isInvalid())
620 return true;
621 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
622 RHS.get(), AA_Assigning))
623 return true;
Nate Begemand773fe62010-06-13 04:47:52 +0000624 }
Nico Weber0e6daef2013-12-26 23:38:39 +0000625
Nate Begemand773fe62010-06-13 04:47:52 +0000626 // For NEON intrinsics which take an immediate value as part of the
627 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000628 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000629 switch (BuiltinID) {
630 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000631 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
632 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000633 case ARM::BI__builtin_arm_vcvtr_f:
634 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000635 case ARM::BI__builtin_arm_dmb:
636 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000637#define GET_NEON_IMMEDIATE_CHECK
638#include "clang/Basic/arm_neon.inc"
639#undef GET_NEON_IMMEDIATE_CHECK
Nate Begemand773fe62010-06-13 04:47:52 +0000640 };
641
Douglas Gregor98c3cfc2012-06-29 01:05:22 +0000642 // We can't check the value of a dependent argument.
643 if (TheCall->getArg(i)->isTypeDependent() ||
644 TheCall->getArg(i)->isValueDependent())
645 return false;
646
Nate Begeman91e1fea2010-06-14 05:21:25 +0000647 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000648 if (SemaBuiltinConstantArg(TheCall, i, Result))
649 return true;
650
Nate Begeman91e1fea2010-06-14 05:21:25 +0000651 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000652 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000653 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000654 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000655 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000656
Nate Begemanf568b072010-08-03 21:32:34 +0000657 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000658 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000659}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000660
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000661bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
662 unsigned i = 0, l = 0, u = 0;
663 switch (BuiltinID) {
664 default: return false;
665 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
666 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000667 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
668 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
669 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
670 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
671 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000672 };
673
674 // We can't check the value of a dependent argument.
675 if (TheCall->getArg(i)->isTypeDependent() ||
676 TheCall->getArg(i)->isValueDependent())
677 return false;
678
679 // Check that the immediate argument is actually a constant.
680 llvm::APSInt Result;
681 if (SemaBuiltinConstantArg(TheCall, i, Result))
682 return true;
683
684 // Range check against the upper/lower values for this instruction.
685 unsigned Val = Result.getZExtValue();
686 if (Val < l || Val > u)
687 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
688 << l << u << TheCall->getArg(i)->getSourceRange();
689
690 return false;
691}
692
Richard Smith55ce3522012-06-25 20:30:08 +0000693/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
694/// parameter with the FormatAttr's correct format_idx and firstDataArg.
695/// Returns true when the format fits the function and the FormatStringInfo has
696/// been populated.
697bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
698 FormatStringInfo *FSI) {
699 FSI->HasVAListArg = Format->getFirstArg() == 0;
700 FSI->FormatIdx = Format->getFormatIdx() - 1;
701 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000702
Richard Smith55ce3522012-06-25 20:30:08 +0000703 // The way the format attribute works in GCC, the implicit this argument
704 // of member functions is counted. However, it doesn't appear in our own
705 // lists, so decrement format_idx in that case.
706 if (IsCXXMember) {
707 if(FSI->FormatIdx == 0)
708 return false;
709 --FSI->FormatIdx;
710 if (FSI->FirstDataArg != 0)
711 --FSI->FirstDataArg;
712 }
713 return true;
714}
Mike Stump11289f42009-09-09 15:08:12 +0000715
Richard Smith55ce3522012-06-25 20:30:08 +0000716/// Handles the checks for format strings, non-POD arguments to vararg
717/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000718void Sema::checkCall(NamedDecl *FDecl,
719 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000720 unsigned NumProtoArgs,
721 bool IsMemberFunction,
722 SourceLocation Loc,
723 SourceRange Range,
724 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000725 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000726 if (CurContext->isDependentContext())
727 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000728
Ted Kremenekb8176da2010-09-09 04:33:05 +0000729 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000730 llvm::SmallBitVector CheckedVarArgs;
731 if (FDecl) {
Richard Trieu41bc0992013-06-22 00:20:41 +0000732 for (specific_attr_iterator<FormatAttr>
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000733 I = FDecl->specific_attr_begin<FormatAttr>(),
734 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000735 I != E; ++I) {
736 // Only create vector if there are format attributes.
737 CheckedVarArgs.resize(Args.size());
738
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000739 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
740 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000741 }
Richard Smithd7293d72013-08-05 18:49:43 +0000742 }
Richard Smith55ce3522012-06-25 20:30:08 +0000743
744 // Refuse POD arguments that weren't caught by the format string
745 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000746 if (CallType != VariadicDoesNotApply) {
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000747 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000748 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000749 if (const Expr *Arg = Args[ArgIdx]) {
750 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
751 checkVariadicArgument(Arg, CallType);
752 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000753 }
Richard Smithd7293d72013-08-05 18:49:43 +0000754 }
Mike Stump11289f42009-09-09 15:08:12 +0000755
Richard Trieu41bc0992013-06-22 00:20:41 +0000756 if (FDecl) {
757 for (specific_attr_iterator<NonNullAttr>
758 I = FDecl->specific_attr_begin<NonNullAttr>(),
759 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
760 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000761
Richard Trieu41bc0992013-06-22 00:20:41 +0000762 // Type safety checking.
763 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
764 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
765 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
766 i != e; ++i) {
767 CheckArgumentWithTypeTag(*i, Args.data());
768 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000769 }
Richard Smith55ce3522012-06-25 20:30:08 +0000770}
771
772/// CheckConstructorCall - Check a constructor call for correctness and safety
773/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000774void Sema::CheckConstructorCall(FunctionDecl *FDecl,
775 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000776 const FunctionProtoType *Proto,
777 SourceLocation Loc) {
778 VariadicCallType CallType =
779 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000780 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith55ce3522012-06-25 20:30:08 +0000781 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
782}
783
784/// CheckFunctionCall - Check a direct function call for various correctness
785/// and safety properties not strictly enforced by the C type system.
786bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
787 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000788 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
789 isa<CXXMethodDecl>(FDecl);
790 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
791 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000792 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
793 TheCall->getCallee());
794 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000795 Expr** Args = TheCall->getArgs();
796 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000797 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000798 // If this is a call to a member operator, hide the first argument
799 // from checkCall.
800 // FIXME: Our choice of AST representation here is less than ideal.
801 ++Args;
802 --NumArgs;
803 }
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000804 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
805 NumProtoArgs,
Richard Smith55ce3522012-06-25 20:30:08 +0000806 IsMemberFunction, TheCall->getRParenLoc(),
807 TheCall->getCallee()->getSourceRange(), CallType);
808
809 IdentifierInfo *FnInfo = FDecl->getIdentifier();
810 // None of the checks below are needed for functions that don't have
811 // simple names (e.g., C++ conversion functions).
812 if (!FnInfo)
813 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000814
Anna Zaks22122702012-01-17 00:37:07 +0000815 unsigned CMId = FDecl->getMemoryFunctionKind();
816 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000817 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000818
Anna Zaks201d4892012-01-13 21:52:01 +0000819 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000820 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000821 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000822 else if (CMId == Builtin::BIstrncat)
823 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000824 else
Anna Zaks22122702012-01-17 00:37:07 +0000825 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000826
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000827 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000828}
829
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000830bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000831 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000832 VariadicCallType CallType =
833 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000834
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000835 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000836 /*IsMemberFunction=*/false,
837 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000838
839 return false;
840}
841
Richard Trieu664c4c62013-06-20 21:03:13 +0000842bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
843 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000844 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
845 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000846 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000847
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000848 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000849 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000850 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000851
Richard Trieu664c4c62013-06-20 21:03:13 +0000852 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000853 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000854 CallType = VariadicDoesNotApply;
855 } else if (Ty->isBlockPointerType()) {
856 CallType = VariadicBlock;
857 } else { // Ty->isFunctionPointerType()
858 CallType = VariadicFunction;
859 }
Richard Smith55ce3522012-06-25 20:30:08 +0000860 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000861
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000862 checkCall(NDecl,
863 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
864 TheCall->getNumArgs()),
Richard Smith55ce3522012-06-25 20:30:08 +0000865 NumProtoArgs, /*IsMemberFunction=*/false,
866 TheCall->getRParenLoc(),
867 TheCall->getCallee()->getSourceRange(), CallType);
868
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000869 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000870}
871
Richard Trieu41bc0992013-06-22 00:20:41 +0000872/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
873/// such as function pointers returned from functions.
874bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
875 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
876 TheCall->getCallee());
877 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
878
879 checkCall(/*FDecl=*/0,
880 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
881 TheCall->getNumArgs()),
882 NumProtoArgs, /*IsMemberFunction=*/false,
883 TheCall->getRParenLoc(),
884 TheCall->getCallee()->getSourceRange(), CallType);
885
886 return false;
887}
888
Richard Smithfeea8832012-04-12 05:08:17 +0000889ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
890 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000891 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
892 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000893
Richard Smithfeea8832012-04-12 05:08:17 +0000894 // All these operations take one of the following forms:
895 enum {
896 // C __c11_atomic_init(A *, C)
897 Init,
898 // C __c11_atomic_load(A *, int)
899 Load,
900 // void __atomic_load(A *, CP, int)
901 Copy,
902 // C __c11_atomic_add(A *, M, int)
903 Arithmetic,
904 // C __atomic_exchange_n(A *, CP, int)
905 Xchg,
906 // void __atomic_exchange(A *, C *, CP, int)
907 GNUXchg,
908 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
909 C11CmpXchg,
910 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
911 GNUCmpXchg
912 } Form = Init;
913 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
914 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
915 // where:
916 // C is an appropriate type,
917 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
918 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
919 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
920 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000921
Richard Smithfeea8832012-04-12 05:08:17 +0000922 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
923 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
924 && "need to update code for modified C11 atomics");
925 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
926 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
927 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
928 Op == AtomicExpr::AO__atomic_store_n ||
929 Op == AtomicExpr::AO__atomic_exchange_n ||
930 Op == AtomicExpr::AO__atomic_compare_exchange_n;
931 bool IsAddSub = false;
932
933 switch (Op) {
934 case AtomicExpr::AO__c11_atomic_init:
935 Form = Init;
936 break;
937
938 case AtomicExpr::AO__c11_atomic_load:
939 case AtomicExpr::AO__atomic_load_n:
940 Form = Load;
941 break;
942
943 case AtomicExpr::AO__c11_atomic_store:
944 case AtomicExpr::AO__atomic_load:
945 case AtomicExpr::AO__atomic_store:
946 case AtomicExpr::AO__atomic_store_n:
947 Form = Copy;
948 break;
949
950 case AtomicExpr::AO__c11_atomic_fetch_add:
951 case AtomicExpr::AO__c11_atomic_fetch_sub:
952 case AtomicExpr::AO__atomic_fetch_add:
953 case AtomicExpr::AO__atomic_fetch_sub:
954 case AtomicExpr::AO__atomic_add_fetch:
955 case AtomicExpr::AO__atomic_sub_fetch:
956 IsAddSub = true;
957 // Fall through.
958 case AtomicExpr::AO__c11_atomic_fetch_and:
959 case AtomicExpr::AO__c11_atomic_fetch_or:
960 case AtomicExpr::AO__c11_atomic_fetch_xor:
961 case AtomicExpr::AO__atomic_fetch_and:
962 case AtomicExpr::AO__atomic_fetch_or:
963 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +0000964 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +0000965 case AtomicExpr::AO__atomic_and_fetch:
966 case AtomicExpr::AO__atomic_or_fetch:
967 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +0000968 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +0000969 Form = Arithmetic;
970 break;
971
972 case AtomicExpr::AO__c11_atomic_exchange:
973 case AtomicExpr::AO__atomic_exchange_n:
974 Form = Xchg;
975 break;
976
977 case AtomicExpr::AO__atomic_exchange:
978 Form = GNUXchg;
979 break;
980
981 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
982 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
983 Form = C11CmpXchg;
984 break;
985
986 case AtomicExpr::AO__atomic_compare_exchange:
987 case AtomicExpr::AO__atomic_compare_exchange_n:
988 Form = GNUCmpXchg;
989 break;
990 }
991
992 // Check we have the right number of arguments.
993 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000994 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +0000995 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000996 << TheCall->getCallee()->getSourceRange();
997 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +0000998 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
999 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001000 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001001 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001002 << TheCall->getCallee()->getSourceRange();
1003 return ExprError();
1004 }
1005
Richard Smithfeea8832012-04-12 05:08:17 +00001006 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001007 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001008 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1009 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1010 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001011 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001012 << Ptr->getType() << Ptr->getSourceRange();
1013 return ExprError();
1014 }
1015
Richard Smithfeea8832012-04-12 05:08:17 +00001016 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1017 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1018 QualType ValType = AtomTy; // 'C'
1019 if (IsC11) {
1020 if (!AtomTy->isAtomicType()) {
1021 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1022 << Ptr->getType() << Ptr->getSourceRange();
1023 return ExprError();
1024 }
Richard Smithe00921a2012-09-15 06:09:58 +00001025 if (AtomTy.isConstQualified()) {
1026 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1027 << Ptr->getType() << Ptr->getSourceRange();
1028 return ExprError();
1029 }
Richard Smithfeea8832012-04-12 05:08:17 +00001030 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001031 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001032
Richard Smithfeea8832012-04-12 05:08:17 +00001033 // For an arithmetic operation, the implied arithmetic must be well-formed.
1034 if (Form == Arithmetic) {
1035 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1036 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1037 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1038 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1039 return ExprError();
1040 }
1041 if (!IsAddSub && !ValType->isIntegerType()) {
1042 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1043 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1044 return ExprError();
1045 }
1046 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1047 // For __atomic_*_n operations, the value type must be a scalar integral or
1048 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001049 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001050 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1051 return ExprError();
1052 }
1053
Eli Friedmanaa769812013-09-11 03:49:34 +00001054 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1055 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001056 // For GNU atomics, require a trivially-copyable type. This is not part of
1057 // the GNU atomics specification, but we enforce it for sanity.
1058 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001059 << Ptr->getType() << Ptr->getSourceRange();
1060 return ExprError();
1061 }
1062
Richard Smithfeea8832012-04-12 05:08:17 +00001063 // FIXME: For any builtin other than a load, the ValType must not be
1064 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001065
1066 switch (ValType.getObjCLifetime()) {
1067 case Qualifiers::OCL_None:
1068 case Qualifiers::OCL_ExplicitNone:
1069 // okay
1070 break;
1071
1072 case Qualifiers::OCL_Weak:
1073 case Qualifiers::OCL_Strong:
1074 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001075 // FIXME: Can this happen? By this point, ValType should be known
1076 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001077 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1078 << ValType << Ptr->getSourceRange();
1079 return ExprError();
1080 }
1081
1082 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001083 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001084 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001085 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001086 ResultType = Context.BoolTy;
1087
Richard Smithfeea8832012-04-12 05:08:17 +00001088 // The type of a parameter passed 'by value'. In the GNU atomics, such
1089 // arguments are actually passed as pointers.
1090 QualType ByValType = ValType; // 'CP'
1091 if (!IsC11 && !IsN)
1092 ByValType = Ptr->getType();
1093
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001094 // The first argument --- the pointer --- has a fixed type; we
1095 // deduce the types of the rest of the arguments accordingly. Walk
1096 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001097 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001098 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001099 if (i < NumVals[Form] + 1) {
1100 switch (i) {
1101 case 1:
1102 // The second argument is the non-atomic operand. For arithmetic, this
1103 // is always passed by value, and for a compare_exchange it is always
1104 // passed by address. For the rest, GNU uses by-address and C11 uses
1105 // by-value.
1106 assert(Form != Load);
1107 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1108 Ty = ValType;
1109 else if (Form == Copy || Form == Xchg)
1110 Ty = ByValType;
1111 else if (Form == Arithmetic)
1112 Ty = Context.getPointerDiffType();
1113 else
1114 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1115 break;
1116 case 2:
1117 // The third argument to compare_exchange / GNU exchange is a
1118 // (pointer to a) desired value.
1119 Ty = ByValType;
1120 break;
1121 case 3:
1122 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1123 Ty = Context.BoolTy;
1124 break;
1125 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001126 } else {
1127 // The order(s) are always converted to int.
1128 Ty = Context.IntTy;
1129 }
Richard Smithfeea8832012-04-12 05:08:17 +00001130
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001131 InitializedEntity Entity =
1132 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001133 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001134 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1135 if (Arg.isInvalid())
1136 return true;
1137 TheCall->setArg(i, Arg.get());
1138 }
1139
Richard Smithfeea8832012-04-12 05:08:17 +00001140 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001141 SmallVector<Expr*, 5> SubExprs;
1142 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001143 switch (Form) {
1144 case Init:
1145 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001146 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001147 break;
1148 case Load:
1149 SubExprs.push_back(TheCall->getArg(1)); // Order
1150 break;
1151 case Copy:
1152 case Arithmetic:
1153 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001154 SubExprs.push_back(TheCall->getArg(2)); // Order
1155 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001156 break;
1157 case GNUXchg:
1158 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1159 SubExprs.push_back(TheCall->getArg(3)); // Order
1160 SubExprs.push_back(TheCall->getArg(1)); // Val1
1161 SubExprs.push_back(TheCall->getArg(2)); // Val2
1162 break;
1163 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001164 SubExprs.push_back(TheCall->getArg(3)); // Order
1165 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001166 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001167 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001168 break;
1169 case GNUCmpXchg:
1170 SubExprs.push_back(TheCall->getArg(4)); // Order
1171 SubExprs.push_back(TheCall->getArg(1)); // Val1
1172 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1173 SubExprs.push_back(TheCall->getArg(2)); // Val2
1174 SubExprs.push_back(TheCall->getArg(3)); // Weak
1175 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001176 }
Fariborz Jahanian615de762013-05-28 17:37:39 +00001177
1178 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1179 SubExprs, ResultType, Op,
1180 TheCall->getRParenLoc());
1181
1182 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1183 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1184 Context.AtomicUsesUnsupportedLibcall(AE))
1185 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1186 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001187
Fariborz Jahanian615de762013-05-28 17:37:39 +00001188 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001189}
1190
1191
John McCall29ad95b2011-08-27 01:09:30 +00001192/// checkBuiltinArgument - Given a call to a builtin function, perform
1193/// normal type-checking on the given argument, updating the call in
1194/// place. This is useful when a builtin function requires custom
1195/// type-checking for some of its arguments but not necessarily all of
1196/// them.
1197///
1198/// Returns true on error.
1199static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1200 FunctionDecl *Fn = E->getDirectCallee();
1201 assert(Fn && "builtin call without direct callee!");
1202
1203 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1204 InitializedEntity Entity =
1205 InitializedEntity::InitializeParameter(S.Context, Param);
1206
1207 ExprResult Arg = E->getArg(0);
1208 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1209 if (Arg.isInvalid())
1210 return true;
1211
1212 E->setArg(ArgIndex, Arg.take());
1213 return false;
1214}
1215
Chris Lattnerdc046542009-05-08 06:58:22 +00001216/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1217/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1218/// type of its first argument. The main ActOnCallExpr routines have already
1219/// promoted the types of arguments because all of these calls are prototyped as
1220/// void(...).
1221///
1222/// This function goes through and does final semantic checking for these
1223/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001224ExprResult
1225Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001226 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001227 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1228 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1229
1230 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001231 if (TheCall->getNumArgs() < 1) {
1232 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1233 << 0 << 1 << TheCall->getNumArgs()
1234 << TheCall->getCallee()->getSourceRange();
1235 return ExprError();
1236 }
Mike Stump11289f42009-09-09 15:08:12 +00001237
Chris Lattnerdc046542009-05-08 06:58:22 +00001238 // Inspect the first argument of the atomic builtin. This should always be
1239 // a pointer type, whose element is an integral scalar or pointer type.
1240 // Because it is a pointer type, we don't have to worry about any implicit
1241 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001242 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001243 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001244 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1245 if (FirstArgResult.isInvalid())
1246 return ExprError();
1247 FirstArg = FirstArgResult.take();
1248 TheCall->setArg(0, FirstArg);
1249
John McCall31168b02011-06-15 23:02:42 +00001250 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1251 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001252 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1253 << FirstArg->getType() << FirstArg->getSourceRange();
1254 return ExprError();
1255 }
Mike Stump11289f42009-09-09 15:08:12 +00001256
John McCall31168b02011-06-15 23:02:42 +00001257 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001258 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001259 !ValType->isBlockPointerType()) {
1260 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1261 << FirstArg->getType() << FirstArg->getSourceRange();
1262 return ExprError();
1263 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001264
John McCall31168b02011-06-15 23:02:42 +00001265 switch (ValType.getObjCLifetime()) {
1266 case Qualifiers::OCL_None:
1267 case Qualifiers::OCL_ExplicitNone:
1268 // okay
1269 break;
1270
1271 case Qualifiers::OCL_Weak:
1272 case Qualifiers::OCL_Strong:
1273 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001274 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001275 << ValType << FirstArg->getSourceRange();
1276 return ExprError();
1277 }
1278
John McCallb50451a2011-10-05 07:41:44 +00001279 // Strip any qualifiers off ValType.
1280 ValType = ValType.getUnqualifiedType();
1281
Chandler Carruth3973af72010-07-18 20:54:12 +00001282 // The majority of builtins return a value, but a few have special return
1283 // types, so allow them to override appropriately below.
1284 QualType ResultType = ValType;
1285
Chris Lattnerdc046542009-05-08 06:58:22 +00001286 // We need to figure out which concrete builtin this maps onto. For example,
1287 // __sync_fetch_and_add with a 2 byte object turns into
1288 // __sync_fetch_and_add_2.
1289#define BUILTIN_ROW(x) \
1290 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1291 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
Chris Lattnerdc046542009-05-08 06:58:22 +00001293 static const unsigned BuiltinIndices[][5] = {
1294 BUILTIN_ROW(__sync_fetch_and_add),
1295 BUILTIN_ROW(__sync_fetch_and_sub),
1296 BUILTIN_ROW(__sync_fetch_and_or),
1297 BUILTIN_ROW(__sync_fetch_and_and),
1298 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001299
Chris Lattnerdc046542009-05-08 06:58:22 +00001300 BUILTIN_ROW(__sync_add_and_fetch),
1301 BUILTIN_ROW(__sync_sub_and_fetch),
1302 BUILTIN_ROW(__sync_and_and_fetch),
1303 BUILTIN_ROW(__sync_or_and_fetch),
1304 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001305
Chris Lattnerdc046542009-05-08 06:58:22 +00001306 BUILTIN_ROW(__sync_val_compare_and_swap),
1307 BUILTIN_ROW(__sync_bool_compare_and_swap),
1308 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001309 BUILTIN_ROW(__sync_lock_release),
1310 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001311 };
Mike Stump11289f42009-09-09 15:08:12 +00001312#undef BUILTIN_ROW
1313
Chris Lattnerdc046542009-05-08 06:58:22 +00001314 // Determine the index of the size.
1315 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001316 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001317 case 1: SizeIndex = 0; break;
1318 case 2: SizeIndex = 1; break;
1319 case 4: SizeIndex = 2; break;
1320 case 8: SizeIndex = 3; break;
1321 case 16: SizeIndex = 4; break;
1322 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001323 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1324 << FirstArg->getType() << FirstArg->getSourceRange();
1325 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001326 }
Mike Stump11289f42009-09-09 15:08:12 +00001327
Chris Lattnerdc046542009-05-08 06:58:22 +00001328 // Each of these builtins has one pointer argument, followed by some number of
1329 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1330 // that we ignore. Find out which row of BuiltinIndices to read from as well
1331 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001332 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001333 unsigned BuiltinIndex, NumFixed = 1;
1334 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001335 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001336 case Builtin::BI__sync_fetch_and_add:
1337 case Builtin::BI__sync_fetch_and_add_1:
1338 case Builtin::BI__sync_fetch_and_add_2:
1339 case Builtin::BI__sync_fetch_and_add_4:
1340 case Builtin::BI__sync_fetch_and_add_8:
1341 case Builtin::BI__sync_fetch_and_add_16:
1342 BuiltinIndex = 0;
1343 break;
1344
1345 case Builtin::BI__sync_fetch_and_sub:
1346 case Builtin::BI__sync_fetch_and_sub_1:
1347 case Builtin::BI__sync_fetch_and_sub_2:
1348 case Builtin::BI__sync_fetch_and_sub_4:
1349 case Builtin::BI__sync_fetch_and_sub_8:
1350 case Builtin::BI__sync_fetch_and_sub_16:
1351 BuiltinIndex = 1;
1352 break;
1353
1354 case Builtin::BI__sync_fetch_and_or:
1355 case Builtin::BI__sync_fetch_and_or_1:
1356 case Builtin::BI__sync_fetch_and_or_2:
1357 case Builtin::BI__sync_fetch_and_or_4:
1358 case Builtin::BI__sync_fetch_and_or_8:
1359 case Builtin::BI__sync_fetch_and_or_16:
1360 BuiltinIndex = 2;
1361 break;
1362
1363 case Builtin::BI__sync_fetch_and_and:
1364 case Builtin::BI__sync_fetch_and_and_1:
1365 case Builtin::BI__sync_fetch_and_and_2:
1366 case Builtin::BI__sync_fetch_and_and_4:
1367 case Builtin::BI__sync_fetch_and_and_8:
1368 case Builtin::BI__sync_fetch_and_and_16:
1369 BuiltinIndex = 3;
1370 break;
Mike Stump11289f42009-09-09 15:08:12 +00001371
Douglas Gregor73722482011-11-28 16:30:08 +00001372 case Builtin::BI__sync_fetch_and_xor:
1373 case Builtin::BI__sync_fetch_and_xor_1:
1374 case Builtin::BI__sync_fetch_and_xor_2:
1375 case Builtin::BI__sync_fetch_and_xor_4:
1376 case Builtin::BI__sync_fetch_and_xor_8:
1377 case Builtin::BI__sync_fetch_and_xor_16:
1378 BuiltinIndex = 4;
1379 break;
1380
1381 case Builtin::BI__sync_add_and_fetch:
1382 case Builtin::BI__sync_add_and_fetch_1:
1383 case Builtin::BI__sync_add_and_fetch_2:
1384 case Builtin::BI__sync_add_and_fetch_4:
1385 case Builtin::BI__sync_add_and_fetch_8:
1386 case Builtin::BI__sync_add_and_fetch_16:
1387 BuiltinIndex = 5;
1388 break;
1389
1390 case Builtin::BI__sync_sub_and_fetch:
1391 case Builtin::BI__sync_sub_and_fetch_1:
1392 case Builtin::BI__sync_sub_and_fetch_2:
1393 case Builtin::BI__sync_sub_and_fetch_4:
1394 case Builtin::BI__sync_sub_and_fetch_8:
1395 case Builtin::BI__sync_sub_and_fetch_16:
1396 BuiltinIndex = 6;
1397 break;
1398
1399 case Builtin::BI__sync_and_and_fetch:
1400 case Builtin::BI__sync_and_and_fetch_1:
1401 case Builtin::BI__sync_and_and_fetch_2:
1402 case Builtin::BI__sync_and_and_fetch_4:
1403 case Builtin::BI__sync_and_and_fetch_8:
1404 case Builtin::BI__sync_and_and_fetch_16:
1405 BuiltinIndex = 7;
1406 break;
1407
1408 case Builtin::BI__sync_or_and_fetch:
1409 case Builtin::BI__sync_or_and_fetch_1:
1410 case Builtin::BI__sync_or_and_fetch_2:
1411 case Builtin::BI__sync_or_and_fetch_4:
1412 case Builtin::BI__sync_or_and_fetch_8:
1413 case Builtin::BI__sync_or_and_fetch_16:
1414 BuiltinIndex = 8;
1415 break;
1416
1417 case Builtin::BI__sync_xor_and_fetch:
1418 case Builtin::BI__sync_xor_and_fetch_1:
1419 case Builtin::BI__sync_xor_and_fetch_2:
1420 case Builtin::BI__sync_xor_and_fetch_4:
1421 case Builtin::BI__sync_xor_and_fetch_8:
1422 case Builtin::BI__sync_xor_and_fetch_16:
1423 BuiltinIndex = 9;
1424 break;
Mike Stump11289f42009-09-09 15:08:12 +00001425
Chris Lattnerdc046542009-05-08 06:58:22 +00001426 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001427 case Builtin::BI__sync_val_compare_and_swap_1:
1428 case Builtin::BI__sync_val_compare_and_swap_2:
1429 case Builtin::BI__sync_val_compare_and_swap_4:
1430 case Builtin::BI__sync_val_compare_and_swap_8:
1431 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001432 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001433 NumFixed = 2;
1434 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001435
Chris Lattnerdc046542009-05-08 06:58:22 +00001436 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001437 case Builtin::BI__sync_bool_compare_and_swap_1:
1438 case Builtin::BI__sync_bool_compare_and_swap_2:
1439 case Builtin::BI__sync_bool_compare_and_swap_4:
1440 case Builtin::BI__sync_bool_compare_and_swap_8:
1441 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001442 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001443 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001444 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001445 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001446
1447 case Builtin::BI__sync_lock_test_and_set:
1448 case Builtin::BI__sync_lock_test_and_set_1:
1449 case Builtin::BI__sync_lock_test_and_set_2:
1450 case Builtin::BI__sync_lock_test_and_set_4:
1451 case Builtin::BI__sync_lock_test_and_set_8:
1452 case Builtin::BI__sync_lock_test_and_set_16:
1453 BuiltinIndex = 12;
1454 break;
1455
Chris Lattnerdc046542009-05-08 06:58:22 +00001456 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001457 case Builtin::BI__sync_lock_release_1:
1458 case Builtin::BI__sync_lock_release_2:
1459 case Builtin::BI__sync_lock_release_4:
1460 case Builtin::BI__sync_lock_release_8:
1461 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001462 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001463 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001464 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001465 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001466
1467 case Builtin::BI__sync_swap:
1468 case Builtin::BI__sync_swap_1:
1469 case Builtin::BI__sync_swap_2:
1470 case Builtin::BI__sync_swap_4:
1471 case Builtin::BI__sync_swap_8:
1472 case Builtin::BI__sync_swap_16:
1473 BuiltinIndex = 14;
1474 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
Chris Lattnerdc046542009-05-08 06:58:22 +00001477 // Now that we know how many fixed arguments we expect, first check that we
1478 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001479 if (TheCall->getNumArgs() < 1+NumFixed) {
1480 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1481 << 0 << 1+NumFixed << TheCall->getNumArgs()
1482 << TheCall->getCallee()->getSourceRange();
1483 return ExprError();
1484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485
Chris Lattner5b9241b2009-05-08 15:36:58 +00001486 // Get the decl for the concrete builtin from this, we can tell what the
1487 // concrete integer type we should convert to is.
1488 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1489 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001490 FunctionDecl *NewBuiltinDecl;
1491 if (NewBuiltinID == BuiltinID)
1492 NewBuiltinDecl = FDecl;
1493 else {
1494 // Perform builtin lookup to avoid redeclaring it.
1495 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1496 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1497 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1498 assert(Res.getFoundDecl());
1499 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1500 if (NewBuiltinDecl == 0)
1501 return ExprError();
1502 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001503
John McCallcf142162010-08-07 06:22:56 +00001504 // The first argument --- the pointer --- has a fixed type; we
1505 // deduce the types of the rest of the arguments accordingly. Walk
1506 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001507 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001508 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001509
Chris Lattnerdc046542009-05-08 06:58:22 +00001510 // GCC does an implicit conversion to the pointer or integer ValType. This
1511 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001512 // Initialize the argument.
1513 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1514 ValType, /*consume*/ false);
1515 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001516 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001517 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001518
Chris Lattnerdc046542009-05-08 06:58:22 +00001519 // Okay, we have something that *can* be converted to the right type. Check
1520 // to see if there is a potentially weird extension going on here. This can
1521 // happen when you do an atomic operation on something like an char* and
1522 // pass in 42. The 42 gets converted to char. This is even more strange
1523 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001524 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001525 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001526 }
Mike Stump11289f42009-09-09 15:08:12 +00001527
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001528 ASTContext& Context = this->getASTContext();
1529
1530 // Create a new DeclRefExpr to refer to the new decl.
1531 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1532 Context,
1533 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001534 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001535 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001536 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001537 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001538 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001539 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001540
Chris Lattnerdc046542009-05-08 06:58:22 +00001541 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001542 // FIXME: This loses syntactic information.
1543 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1544 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1545 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001546 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001547
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001548 // Change the result type of the call to match the original value type. This
1549 // is arbitrary, but the codegen for these builtins ins design to handle it
1550 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001551 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001552
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001553 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001554}
1555
Chris Lattner6436fb62009-02-18 06:01:06 +00001556/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001557/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001558/// Note: It might also make sense to do the UTF-16 conversion here (would
1559/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001560bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001561 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001562 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1563
Douglas Gregorfb65e592011-07-27 05:40:30 +00001564 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001565 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1566 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001567 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001568 }
Mike Stump11289f42009-09-09 15:08:12 +00001569
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001570 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001571 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001572 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001573 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001574 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001575 UTF16 *ToPtr = &ToBuf[0];
1576
1577 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1578 &ToPtr, ToPtr + NumBytes,
1579 strictConversion);
1580 // Check for conversion failure.
1581 if (Result != conversionOK)
1582 Diag(Arg->getLocStart(),
1583 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1584 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001585 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001586}
1587
Chris Lattnere202e6a2007-12-20 00:05:45 +00001588/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1589/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001590bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1591 Expr *Fn = TheCall->getCallee();
1592 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001593 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001594 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001595 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1596 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001597 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001598 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001599 return true;
1600 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001601
1602 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001603 return Diag(TheCall->getLocEnd(),
1604 diag::err_typecheck_call_too_few_args_at_least)
1605 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001606 }
1607
John McCall29ad95b2011-08-27 01:09:30 +00001608 // Type-check the first argument normally.
1609 if (checkBuiltinArgument(*this, TheCall, 0))
1610 return true;
1611
Chris Lattnere202e6a2007-12-20 00:05:45 +00001612 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001613 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001614 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001615 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001616 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001617 else if (FunctionDecl *FD = getCurFunctionDecl())
1618 isVariadic = FD->isVariadic();
1619 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001620 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001621
Chris Lattnere202e6a2007-12-20 00:05:45 +00001622 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001623 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1624 return true;
1625 }
Mike Stump11289f42009-09-09 15:08:12 +00001626
Chris Lattner43be2e62007-12-19 23:59:04 +00001627 // Verify that the second argument to the builtin is the last argument of the
1628 // current function or method.
1629 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001630 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001631
Nico Weber9eea7642013-05-24 23:31:57 +00001632 // These are valid if SecondArgIsLastNamedArgument is false after the next
1633 // block.
1634 QualType Type;
1635 SourceLocation ParamLoc;
1636
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001637 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1638 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001639 // FIXME: This isn't correct for methods (results in bogus warning).
1640 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001641 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001642 if (CurBlock)
1643 LastArg = *(CurBlock->TheDecl->param_end()-1);
1644 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001645 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001646 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001647 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001648 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001649
1650 Type = PV->getType();
1651 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001652 }
1653 }
Mike Stump11289f42009-09-09 15:08:12 +00001654
Chris Lattner43be2e62007-12-19 23:59:04 +00001655 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001656 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001657 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001658 else if (Type->isReferenceType()) {
1659 Diag(Arg->getLocStart(),
1660 diag::warn_va_start_of_reference_type_is_undefined);
1661 Diag(ParamLoc, diag::note_parameter_type) << Type;
1662 }
1663
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001664 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001665 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001666}
Chris Lattner43be2e62007-12-19 23:59:04 +00001667
Chris Lattner2da14fb2007-12-20 00:26:33 +00001668/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1669/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001670bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1671 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001672 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001673 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001674 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001675 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001676 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001677 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001678 << SourceRange(TheCall->getArg(2)->getLocStart(),
1679 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001680
John Wiegley01296292011-04-08 18:41:53 +00001681 ExprResult OrigArg0 = TheCall->getArg(0);
1682 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001683
Chris Lattner2da14fb2007-12-20 00:26:33 +00001684 // Do standard promotions between the two arguments, returning their common
1685 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001686 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001687 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1688 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001689
1690 // Make sure any conversions are pushed back into the call; this is
1691 // type safe since unordered compare builtins are declared as "_Bool
1692 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001693 TheCall->setArg(0, OrigArg0.get());
1694 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001695
John Wiegley01296292011-04-08 18:41:53 +00001696 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001697 return false;
1698
Chris Lattner2da14fb2007-12-20 00:26:33 +00001699 // If the common type isn't a real floating type, then the arguments were
1700 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001701 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001702 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001703 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001704 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1705 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001706
Chris Lattner2da14fb2007-12-20 00:26:33 +00001707 return false;
1708}
1709
Benjamin Kramer634fc102010-02-15 22:42:31 +00001710/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1711/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001712/// to check everything. We expect the last argument to be a floating point
1713/// value.
1714bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1715 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001716 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001717 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001718 if (TheCall->getNumArgs() > NumArgs)
1719 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001720 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001721 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001722 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001723 (*(TheCall->arg_end()-1))->getLocEnd());
1724
Benjamin Kramer64aae502010-02-16 10:07:31 +00001725 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001726
Eli Friedman7e4faac2009-08-31 20:06:00 +00001727 if (OrigArg->isTypeDependent())
1728 return false;
1729
Chris Lattner68784ef2010-05-06 05:50:07 +00001730 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001731 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001732 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001733 diag::err_typecheck_call_invalid_unary_fp)
1734 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001735
Chris Lattner68784ef2010-05-06 05:50:07 +00001736 // If this is an implicit conversion from float -> double, remove it.
1737 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1738 Expr *CastArg = Cast->getSubExpr();
1739 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1740 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1741 "promotion from float to double is the only expected cast here");
1742 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001743 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001744 }
1745 }
1746
Eli Friedman7e4faac2009-08-31 20:06:00 +00001747 return false;
1748}
1749
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001750/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1751// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001752ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001753 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001754 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001755 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001756 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1757 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001758
Nate Begemana0110022010-06-08 00:16:34 +00001759 // Determine which of the following types of shufflevector we're checking:
1760 // 1) unary, vector mask: (lhs, mask)
1761 // 2) binary, vector mask: (lhs, rhs, mask)
1762 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1763 QualType resType = TheCall->getArg(0)->getType();
1764 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001765
Douglas Gregorc25f7662009-05-19 22:10:17 +00001766 if (!TheCall->getArg(0)->isTypeDependent() &&
1767 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001768 QualType LHSType = TheCall->getArg(0)->getType();
1769 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001770
Craig Topperbaca3892013-07-29 06:47:04 +00001771 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1772 return ExprError(Diag(TheCall->getLocStart(),
1773 diag::err_shufflevector_non_vector)
1774 << SourceRange(TheCall->getArg(0)->getLocStart(),
1775 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001776
Nate Begemana0110022010-06-08 00:16:34 +00001777 numElements = LHSType->getAs<VectorType>()->getNumElements();
1778 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001779
Nate Begemana0110022010-06-08 00:16:34 +00001780 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1781 // with mask. If so, verify that RHS is an integer vector type with the
1782 // same number of elts as lhs.
1783 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001784 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001785 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001786 return ExprError(Diag(TheCall->getLocStart(),
1787 diag::err_shufflevector_incompatible_vector)
1788 << SourceRange(TheCall->getArg(1)->getLocStart(),
1789 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001790 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001791 return ExprError(Diag(TheCall->getLocStart(),
1792 diag::err_shufflevector_incompatible_vector)
1793 << SourceRange(TheCall->getArg(0)->getLocStart(),
1794 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001795 } else if (numElements != numResElements) {
1796 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001797 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001798 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001799 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001800 }
1801
1802 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001803 if (TheCall->getArg(i)->isTypeDependent() ||
1804 TheCall->getArg(i)->isValueDependent())
1805 continue;
1806
Nate Begemana0110022010-06-08 00:16:34 +00001807 llvm::APSInt Result(32);
1808 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1809 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001810 diag::err_shufflevector_nonconstant_argument)
1811 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001812
Craig Topper50ad5b72013-08-03 17:40:38 +00001813 // Allow -1 which will be translated to undef in the IR.
1814 if (Result.isSigned() && Result.isAllOnesValue())
1815 continue;
1816
Chris Lattner7ab824e2008-08-10 02:05:13 +00001817 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001818 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001819 diag::err_shufflevector_argument_too_large)
1820 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001821 }
1822
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001823 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001824
Chris Lattner7ab824e2008-08-10 02:05:13 +00001825 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001826 exprs.push_back(TheCall->getArg(i));
1827 TheCall->setArg(i, 0);
1828 }
1829
Benjamin Kramerc215e762012-08-24 11:54:20 +00001830 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001831 TheCall->getCallee()->getLocStart(),
1832 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001833}
Chris Lattner43be2e62007-12-19 23:59:04 +00001834
Hal Finkelc4d7c822013-09-18 03:29:45 +00001835/// SemaConvertVectorExpr - Handle __builtin_convertvector
1836ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1837 SourceLocation BuiltinLoc,
1838 SourceLocation RParenLoc) {
1839 ExprValueKind VK = VK_RValue;
1840 ExprObjectKind OK = OK_Ordinary;
1841 QualType DstTy = TInfo->getType();
1842 QualType SrcTy = E->getType();
1843
1844 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1845 return ExprError(Diag(BuiltinLoc,
1846 diag::err_convertvector_non_vector)
1847 << E->getSourceRange());
1848 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1849 return ExprError(Diag(BuiltinLoc,
1850 diag::err_convertvector_non_vector_type));
1851
1852 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1853 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1854 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1855 if (SrcElts != DstElts)
1856 return ExprError(Diag(BuiltinLoc,
1857 diag::err_convertvector_incompatible_vector)
1858 << E->getSourceRange());
1859 }
1860
1861 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1862 BuiltinLoc, RParenLoc));
1863
1864}
1865
Daniel Dunbarb7257262008-07-21 22:59:13 +00001866/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1867// This is declared to take (const void*, ...) and can take two
1868// optional constant int args.
1869bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001870 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001871
Chris Lattner3b054132008-11-19 05:08:23 +00001872 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001873 return Diag(TheCall->getLocEnd(),
1874 diag::err_typecheck_call_too_many_args_at_most)
1875 << 0 /*function call*/ << 3 << NumArgs
1876 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001877
1878 // Argument 0 is checked for us and the remaining arguments must be
1879 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001880 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001881 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001882
1883 // We can't check the value of a dependent argument.
1884 if (Arg->isTypeDependent() || Arg->isValueDependent())
1885 continue;
1886
Eli Friedman5efba262009-12-04 00:30:06 +00001887 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001888 if (SemaBuiltinConstantArg(TheCall, i, Result))
1889 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001890
Daniel Dunbarb7257262008-07-21 22:59:13 +00001891 // FIXME: gcc issues a warning and rewrites these to 0. These
1892 // seems especially odd for the third argument since the default
1893 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001894 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001895 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001896 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001897 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001898 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001899 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001900 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001901 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001902 }
1903 }
1904
Chris Lattner3b054132008-11-19 05:08:23 +00001905 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001906}
1907
Eric Christopher8d0c6212010-04-17 02:26:23 +00001908/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1909/// TheCall is a constant expression.
1910bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1911 llvm::APSInt &Result) {
1912 Expr *Arg = TheCall->getArg(ArgNum);
1913 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1914 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1915
1916 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1917
1918 if (!Arg->isIntegerConstantExpr(Result, Context))
1919 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001920 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001921
Chris Lattnerd545ad12009-09-23 06:06:36 +00001922 return false;
1923}
1924
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001925/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1926/// int type). This simply type checks that type is one of the defined
1927/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001928// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001929bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001930 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001931
1932 // We can't check the value of a dependent argument.
1933 if (TheCall->getArg(1)->isTypeDependent() ||
1934 TheCall->getArg(1)->isValueDependent())
1935 return false;
1936
Eric Christopher8d0c6212010-04-17 02:26:23 +00001937 // Check constant-ness first.
1938 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1939 return true;
1940
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001941 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001942 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001943 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1944 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001945 }
1946
1947 return false;
1948}
1949
Eli Friedmanc97d0142009-05-03 06:04:26 +00001950/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001951/// This checks that val is a constant 1.
1952bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1953 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001954 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001955
Eric Christopher8d0c6212010-04-17 02:26:23 +00001956 // TODO: This is less than ideal. Overload this to take a value.
1957 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1958 return true;
1959
1960 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001961 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1962 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1963
1964 return false;
1965}
1966
Richard Smithd7293d72013-08-05 18:49:43 +00001967namespace {
1968enum StringLiteralCheckType {
1969 SLCT_NotALiteral,
1970 SLCT_UncheckedLiteral,
1971 SLCT_CheckedLiteral
1972};
1973}
1974
Richard Smith55ce3522012-06-25 20:30:08 +00001975// Determine if an expression is a string literal or constant string.
1976// If this function returns false on the arguments to a function expecting a
1977// format string, we will usually need to emit a warning.
1978// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00001979static StringLiteralCheckType
1980checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1981 bool HasVAListArg, unsigned format_idx,
1982 unsigned firstDataArg, Sema::FormatStringType Type,
1983 Sema::VariadicCallType CallType, bool InFunctionCall,
1984 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00001985 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00001986 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00001987 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001988
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001989 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00001990
Richard Smithd7293d72013-08-05 18:49:43 +00001991 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00001992 // Technically -Wformat-nonliteral does not warn about this case.
1993 // The behavior of printf and friends in this case is implementation
1994 // dependent. Ideally if the format string cannot be null then
1995 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00001996 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00001997
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001998 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00001999 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002000 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002001 // The expression is a literal if both sub-expressions were, and it was
2002 // completely checked only if both sub-expressions were checked.
2003 const AbstractConditionalOperator *C =
2004 cast<AbstractConditionalOperator>(E);
2005 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002006 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002007 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002008 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002009 if (Left == SLCT_NotALiteral)
2010 return SLCT_NotALiteral;
2011 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002012 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002013 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002014 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002015 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002016 }
2017
2018 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002019 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2020 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002021 }
2022
John McCallc07a0c72011-02-17 10:25:35 +00002023 case Stmt::OpaqueValueExprClass:
2024 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2025 E = src;
2026 goto tryAgain;
2027 }
Richard Smith55ce3522012-06-25 20:30:08 +00002028 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002029
Ted Kremeneka8890832011-02-24 23:03:04 +00002030 case Stmt::PredefinedExprClass:
2031 // While __func__, etc., are technically not string literals, they
2032 // cannot contain format specifiers and thus are not a security
2033 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002034 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002035
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002036 case Stmt::DeclRefExprClass: {
2037 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002038
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002039 // As an exception, do not flag errors for variables binding to
2040 // const string literals.
2041 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2042 bool isConstant = false;
2043 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002044
Richard Smithd7293d72013-08-05 18:49:43 +00002045 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2046 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002047 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002048 isConstant = T.isConstant(S.Context) &&
2049 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002050 } else if (T->isObjCObjectPointerType()) {
2051 // In ObjC, there is usually no "const ObjectPointer" type,
2052 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002053 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002054 }
Mike Stump11289f42009-09-09 15:08:12 +00002055
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002056 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002057 if (const Expr *Init = VD->getAnyInitializer()) {
2058 // Look through initializers like const char c[] = { "foo" }
2059 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2060 if (InitList->isStringLiteralInit())
2061 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2062 }
Richard Smithd7293d72013-08-05 18:49:43 +00002063 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002064 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002065 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002066 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002067 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002068 }
Mike Stump11289f42009-09-09 15:08:12 +00002069
Anders Carlssonb012ca92009-06-28 19:55:58 +00002070 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2071 // special check to see if the format string is a function parameter
2072 // of the function calling the printf function. If the function
2073 // has an attribute indicating it is a printf-like function, then we
2074 // should suppress warnings concerning non-literals being used in a call
2075 // to a vprintf function. For example:
2076 //
2077 // void
2078 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2079 // va_list ap;
2080 // va_start(ap, fmt);
2081 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2082 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002083 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002084 if (HasVAListArg) {
2085 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2086 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2087 int PVIndex = PV->getFunctionScopeIndex() + 1;
2088 for (specific_attr_iterator<FormatAttr>
2089 i = ND->specific_attr_begin<FormatAttr>(),
2090 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2091 FormatAttr *PVFormat = *i;
2092 // adjust for implicit parameter
2093 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2094 if (MD->isInstance())
2095 ++PVIndex;
2096 // We also check if the formats are compatible.
2097 // We can't pass a 'scanf' string to a 'printf' function.
2098 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002099 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002100 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002101 }
2102 }
2103 }
2104 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
Richard Smith55ce3522012-06-25 20:30:08 +00002107 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002108 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002109
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002110 case Stmt::CallExprClass:
2111 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002112 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002113 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2114 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2115 unsigned ArgIndex = FA->getFormatIdx();
2116 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2117 if (MD->isInstance())
2118 --ArgIndex;
2119 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002120
Richard Smithd7293d72013-08-05 18:49:43 +00002121 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002122 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002123 Type, CallType, InFunctionCall,
2124 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002125 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2126 unsigned BuiltinID = FD->getBuiltinID();
2127 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2128 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2129 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002130 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002131 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002132 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002133 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002134 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002135 }
2136 }
Mike Stump11289f42009-09-09 15:08:12 +00002137
Richard Smith55ce3522012-06-25 20:30:08 +00002138 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002139 }
Fariborz Jahanian4ba4a5b2013-10-18 21:20:34 +00002140
2141 case Stmt::ObjCMessageExprClass: {
2142 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2143 if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2144 if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2145 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2146 unsigned ArgIndex = FA->getFormatIdx();
2147 if (ArgIndex <= ME->getNumArgs()) {
2148 const Expr *Arg = ME->getArg(ArgIndex-1);
2149 return checkFormatStringExpr(S, Arg, Args,
2150 HasVAListArg, format_idx,
2151 firstDataArg, Type, CallType,
2152 InFunctionCall, CheckedVarArgs);
2153 }
2154 }
2155 }
2156 }
2157
2158 return SLCT_NotALiteral;
2159 }
2160
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002161 case Stmt::ObjCStringLiteralClass:
2162 case Stmt::StringLiteralClass: {
2163 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002164
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002165 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002166 StrE = ObjCFExpr->getString();
2167 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002168 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002169
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002170 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002171 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2172 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002173 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002174 }
Mike Stump11289f42009-09-09 15:08:12 +00002175
Richard Smith55ce3522012-06-25 20:30:08 +00002176 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002177 }
Mike Stump11289f42009-09-09 15:08:12 +00002178
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002179 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002180 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002181 }
2182}
2183
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00002184void
Mike Stump11289f42009-09-09 15:08:12 +00002185Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewyckyd4693212011-03-25 01:44:32 +00002186 const Expr * const *ExprArgs,
2187 SourceLocation CallSiteLoc) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002188 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2189 e = NonNull->args_end();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00002190 i != e; ++i) {
Nick Lewyckyd4693212011-03-25 01:44:32 +00002191 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewyckyc77c8e92013-01-23 05:08:29 +00002192
2193 // As a special case, transparent unions initialized with zero are
2194 // considered null for the purposes of the nonnull attribute.
2195 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2196 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2197 if (const CompoundLiteralExpr *CLE =
2198 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2199 if (const InitListExpr *ILE =
2200 dyn_cast<InitListExpr>(CLE->getInitializer()))
2201 ArgExpr = ILE->getInit(0);
2202 }
2203
2204 bool Result;
2205 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewyckyd4693212011-03-25 01:44:32 +00002206 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00002207 }
2208}
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002209
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002210Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002211 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002212 .Case("scanf", FST_Scanf)
2213 .Cases("printf", "printf0", FST_Printf)
2214 .Cases("NSString", "CFString", FST_NSString)
2215 .Case("strftime", FST_Strftime)
2216 .Case("strfmon", FST_Strfmon)
2217 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2218 .Default(FST_Unknown);
2219}
2220
Jordan Rose3e0ec582012-07-19 18:10:23 +00002221/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002222/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002223/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002224bool Sema::CheckFormatArguments(const FormatAttr *Format,
2225 ArrayRef<const Expr *> Args,
2226 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002227 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002228 SourceLocation Loc, SourceRange Range,
2229 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002230 FormatStringInfo FSI;
2231 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002232 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002233 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002234 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002235 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002236}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002237
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002238bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002239 bool HasVAListArg, unsigned format_idx,
2240 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002241 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002242 SourceLocation Loc, SourceRange Range,
2243 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002244 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002245 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002246 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002247 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002248 }
Mike Stump11289f42009-09-09 15:08:12 +00002249
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002250 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002251
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002252 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002253 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002254 // Dynamically generated format strings are difficult to
2255 // automatically vet at compile time. Requiring that format strings
2256 // are string literals: (1) permits the checking of format strings by
2257 // the compiler and thereby (2) can practically remove the source of
2258 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002259
Mike Stump11289f42009-09-09 15:08:12 +00002260 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002261 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002262 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002263 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002264 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002265 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2266 format_idx, firstDataArg, Type, CallType,
2267 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002268 if (CT != SLCT_NotALiteral)
2269 // Literal format string found, check done!
2270 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002271
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002272 // Strftime is particular as it always uses a single 'time' argument,
2273 // so it is safe to pass a non-literal string.
2274 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002275 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002276
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002277 // Do not emit diag when the string param is a macro expansion and the
2278 // format is either NSString or CFString. This is a hack to prevent
2279 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2280 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002281 if (Type == FST_NSString &&
2282 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002283 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002284
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002285 // If there are no arguments specified, warn with -Wformat-security, otherwise
2286 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002287 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002288 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002289 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002290 << OrigFormatExpr->getSourceRange();
2291 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002292 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002293 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002294 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002295 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002296}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002297
Ted Kremenekab278de2010-01-28 23:39:18 +00002298namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002299class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2300protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002301 Sema &S;
2302 const StringLiteral *FExpr;
2303 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002304 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002305 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002306 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002307 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002308 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002309 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002310 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002311 bool usesPositionalArgs;
2312 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002313 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002314 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002315 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002316public:
Ted Kremenek02087932010-07-16 02:11:22 +00002317 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002318 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002319 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002320 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002321 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002322 Sema::VariadicCallType callType,
2323 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002324 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002325 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2326 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002327 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002328 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002329 inFunctionCall(inFunctionCall), CallType(callType),
2330 CheckedVarArgs(CheckedVarArgs) {
2331 CoveredArgs.resize(numDataArgs);
2332 CoveredArgs.reset();
2333 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002334
Ted Kremenek019d2242010-01-29 01:50:07 +00002335 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002336
Ted Kremenek02087932010-07-16 02:11:22 +00002337 void HandleIncompleteSpecifier(const char *startSpecifier,
2338 unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002339
Jordan Rose92303592012-09-08 04:00:03 +00002340 void HandleInvalidLengthModifier(
2341 const analyze_format_string::FormatSpecifier &FS,
2342 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002343 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002344
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002345 void HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002346 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002347 const char *startSpecifier, unsigned specifierLen);
2348
2349 void HandleNonStandardConversionSpecifier(
2350 const analyze_format_string::ConversionSpecifier &CS,
2351 const char *startSpecifier, unsigned specifierLen);
2352
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002353 virtual void HandlePosition(const char *startPos, unsigned posLen);
2354
Ted Kremenekd1668192010-02-27 01:41:03 +00002355 virtual void HandleInvalidPosition(const char *startSpecifier,
2356 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00002357 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00002358
2359 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2360
Ted Kremenekab278de2010-01-28 23:39:18 +00002361 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002362
Richard Trieu03cf7b72011-10-28 00:41:25 +00002363 template <typename Range>
2364 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2365 const Expr *ArgumentExpr,
2366 PartialDiagnostic PDiag,
2367 SourceLocation StringLoc,
2368 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002369 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002370
Ted Kremenek02087932010-07-16 02:11:22 +00002371protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002372 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2373 const char *startSpec,
2374 unsigned specifierLen,
2375 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002376
2377 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2378 const char *startSpec,
2379 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002380
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002381 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002382 CharSourceRange getSpecifierRange(const char *startSpecifier,
2383 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002384 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002385
Ted Kremenek5739de72010-01-29 01:06:55 +00002386 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002387
2388 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2389 const analyze_format_string::ConversionSpecifier &CS,
2390 const char *startSpecifier, unsigned specifierLen,
2391 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002392
2393 template <typename Range>
2394 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2395 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002396 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002397
2398 void CheckPositionalAndNonpositionalArgs(
2399 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00002400};
2401}
2402
Ted Kremenek02087932010-07-16 02:11:22 +00002403SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002404 return OrigFormatExpr->getSourceRange();
2405}
2406
Ted Kremenek02087932010-07-16 02:11:22 +00002407CharSourceRange CheckFormatHandler::
2408getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002409 SourceLocation Start = getLocationOfByte(startSpecifier);
2410 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2411
2412 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002413 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002414
2415 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002416}
2417
Ted Kremenek02087932010-07-16 02:11:22 +00002418SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002419 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002420}
2421
Ted Kremenek02087932010-07-16 02:11:22 +00002422void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2423 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002424 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2425 getLocationOfByte(startSpecifier),
2426 /*IsStringLocation*/true,
2427 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002428}
2429
Jordan Rose92303592012-09-08 04:00:03 +00002430void CheckFormatHandler::HandleInvalidLengthModifier(
2431 const analyze_format_string::FormatSpecifier &FS,
2432 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002433 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002434 using namespace analyze_format_string;
2435
2436 const LengthModifier &LM = FS.getLengthModifier();
2437 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2438
2439 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002440 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002441 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002442 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002443 getLocationOfByte(LM.getStart()),
2444 /*IsStringLocation*/true,
2445 getSpecifierRange(startSpecifier, specifierLen));
2446
2447 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2448 << FixedLM->toString()
2449 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2450
2451 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002452 FixItHint Hint;
2453 if (DiagID == diag::warn_format_nonsensical_length)
2454 Hint = FixItHint::CreateRemoval(LMRange);
2455
2456 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002457 getLocationOfByte(LM.getStart()),
2458 /*IsStringLocation*/true,
2459 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002460 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002461 }
2462}
2463
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002464void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002465 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002466 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002467 using namespace analyze_format_string;
2468
2469 const LengthModifier &LM = FS.getLengthModifier();
2470 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2471
2472 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002473 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002474 if (FixedLM) {
2475 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2476 << LM.toString() << 0,
2477 getLocationOfByte(LM.getStart()),
2478 /*IsStringLocation*/true,
2479 getSpecifierRange(startSpecifier, specifierLen));
2480
2481 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2482 << FixedLM->toString()
2483 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2484
2485 } else {
2486 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2487 << LM.toString() << 0,
2488 getLocationOfByte(LM.getStart()),
2489 /*IsStringLocation*/true,
2490 getSpecifierRange(startSpecifier, specifierLen));
2491 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002492}
2493
2494void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2495 const analyze_format_string::ConversionSpecifier &CS,
2496 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002497 using namespace analyze_format_string;
2498
2499 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002500 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002501 if (FixedCS) {
2502 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2503 << CS.toString() << /*conversion specifier*/1,
2504 getLocationOfByte(CS.getStart()),
2505 /*IsStringLocation*/true,
2506 getSpecifierRange(startSpecifier, specifierLen));
2507
2508 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2509 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2510 << FixedCS->toString()
2511 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2512 } else {
2513 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2514 << CS.toString() << /*conversion specifier*/1,
2515 getLocationOfByte(CS.getStart()),
2516 /*IsStringLocation*/true,
2517 getSpecifierRange(startSpecifier, specifierLen));
2518 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002519}
2520
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002521void CheckFormatHandler::HandlePosition(const char *startPos,
2522 unsigned posLen) {
2523 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2524 getLocationOfByte(startPos),
2525 /*IsStringLocation*/true,
2526 getSpecifierRange(startPos, posLen));
2527}
2528
Ted Kremenekd1668192010-02-27 01:41:03 +00002529void
Ted Kremenek02087932010-07-16 02:11:22 +00002530CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2531 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002532 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2533 << (unsigned) p,
2534 getLocationOfByte(startPos), /*IsStringLocation*/true,
2535 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002536}
2537
Ted Kremenek02087932010-07-16 02:11:22 +00002538void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002539 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002540 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2541 getLocationOfByte(startPos),
2542 /*IsStringLocation*/true,
2543 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002544}
2545
Ted Kremenek02087932010-07-16 02:11:22 +00002546void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002547 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002548 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002549 EmitFormatDiagnostic(
2550 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2551 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2552 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002553 }
Ted Kremenek02087932010-07-16 02:11:22 +00002554}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002555
Jordan Rose58bbe422012-07-19 18:10:08 +00002556// Note that this may return NULL if there was an error parsing or building
2557// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002558const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002559 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002560}
2561
2562void CheckFormatHandler::DoneProcessing() {
2563 // Does the number of data arguments exceed the number of
2564 // format conversions in the format string?
2565 if (!HasVAListArg) {
2566 // Find any arguments that weren't covered.
2567 CoveredArgs.flip();
2568 signed notCoveredArg = CoveredArgs.find_first();
2569 if (notCoveredArg >= 0) {
2570 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002571 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2572 SourceLocation Loc = E->getLocStart();
2573 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2574 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2575 Loc, /*IsStringLocation*/false,
2576 getFormatStringRange());
2577 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002578 }
Ted Kremenek02087932010-07-16 02:11:22 +00002579 }
2580 }
2581}
2582
Ted Kremenekce815422010-07-19 21:25:57 +00002583bool
2584CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2585 SourceLocation Loc,
2586 const char *startSpec,
2587 unsigned specifierLen,
2588 const char *csStart,
2589 unsigned csLen) {
2590
2591 bool keepGoing = true;
2592 if (argIndex < NumDataArgs) {
2593 // Consider the argument coverered, even though the specifier doesn't
2594 // make sense.
2595 CoveredArgs.set(argIndex);
2596 }
2597 else {
2598 // If argIndex exceeds the number of data arguments we
2599 // don't issue a warning because that is just a cascade of warnings (and
2600 // they may have intended '%%' anyway). We don't want to continue processing
2601 // the format string after this point, however, as we will like just get
2602 // gibberish when trying to match arguments.
2603 keepGoing = false;
2604 }
2605
Richard Trieu03cf7b72011-10-28 00:41:25 +00002606 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2607 << StringRef(csStart, csLen),
2608 Loc, /*IsStringLocation*/true,
2609 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002610
2611 return keepGoing;
2612}
2613
Richard Trieu03cf7b72011-10-28 00:41:25 +00002614void
2615CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2616 const char *startSpec,
2617 unsigned specifierLen) {
2618 EmitFormatDiagnostic(
2619 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2620 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2621}
2622
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002623bool
2624CheckFormatHandler::CheckNumArgs(
2625 const analyze_format_string::FormatSpecifier &FS,
2626 const analyze_format_string::ConversionSpecifier &CS,
2627 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2628
2629 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002630 PartialDiagnostic PDiag = FS.usesPositionalArg()
2631 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2632 << (argIndex+1) << NumDataArgs)
2633 : S.PDiag(diag::warn_printf_insufficient_data_args);
2634 EmitFormatDiagnostic(
2635 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2636 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002637 return false;
2638 }
2639 return true;
2640}
2641
Richard Trieu03cf7b72011-10-28 00:41:25 +00002642template<typename Range>
2643void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2644 SourceLocation Loc,
2645 bool IsStringLocation,
2646 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002647 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002648 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002649 Loc, IsStringLocation, StringRange, FixIt);
2650}
2651
2652/// \brief If the format string is not within the funcion call, emit a note
2653/// so that the function call and string are in diagnostic messages.
2654///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002655/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002656/// call and only one diagnostic message will be produced. Otherwise, an
2657/// extra note will be emitted pointing to location of the format string.
2658///
2659/// \param ArgumentExpr the expression that is passed as the format string
2660/// argument in the function call. Used for getting locations when two
2661/// diagnostics are emitted.
2662///
2663/// \param PDiag the callee should already have provided any strings for the
2664/// diagnostic message. This function only adds locations and fixits
2665/// to diagnostics.
2666///
2667/// \param Loc primary location for diagnostic. If two diagnostics are
2668/// required, one will be at Loc and a new SourceLocation will be created for
2669/// the other one.
2670///
2671/// \param IsStringLocation if true, Loc points to the format string should be
2672/// used for the note. Otherwise, Loc points to the argument list and will
2673/// be used with PDiag.
2674///
2675/// \param StringRange some or all of the string to highlight. This is
2676/// templated so it can accept either a CharSourceRange or a SourceRange.
2677///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002678/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002679template<typename Range>
2680void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2681 const Expr *ArgumentExpr,
2682 PartialDiagnostic PDiag,
2683 SourceLocation Loc,
2684 bool IsStringLocation,
2685 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002686 ArrayRef<FixItHint> FixIt) {
2687 if (InFunctionCall) {
2688 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2689 D << StringRange;
2690 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2691 I != E; ++I) {
2692 D << *I;
2693 }
2694 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002695 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2696 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002697
2698 const Sema::SemaDiagnosticBuilder &Note =
2699 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2700 diag::note_format_string_defined);
2701
2702 Note << StringRange;
2703 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2704 I != E; ++I) {
2705 Note << *I;
2706 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002707 }
2708}
2709
Ted Kremenek02087932010-07-16 02:11:22 +00002710//===--- CHECK: Printf format string checking ------------------------------===//
2711
2712namespace {
2713class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002714 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002715public:
2716 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2717 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002718 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002719 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002720 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002721 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002722 Sema::VariadicCallType CallType,
2723 llvm::SmallBitVector &CheckedVarArgs)
2724 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2725 numDataArgs, beg, hasVAListArg, Args,
2726 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2727 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002728 {}
2729
Ted Kremenek02087932010-07-16 02:11:22 +00002730
2731 bool HandleInvalidPrintfConversionSpecifier(
2732 const analyze_printf::PrintfSpecifier &FS,
2733 const char *startSpecifier,
2734 unsigned specifierLen);
2735
2736 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2737 const char *startSpecifier,
2738 unsigned specifierLen);
Richard Smith55ce3522012-06-25 20:30:08 +00002739 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2740 const char *StartSpecifier,
2741 unsigned SpecifierLen,
2742 const Expr *E);
2743
Ted Kremenek02087932010-07-16 02:11:22 +00002744 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2745 const char *startSpecifier, unsigned specifierLen);
2746 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2747 const analyze_printf::OptionalAmount &Amt,
2748 unsigned type,
2749 const char *startSpecifier, unsigned specifierLen);
2750 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2751 const analyze_printf::OptionalFlag &flag,
2752 const char *startSpecifier, unsigned specifierLen);
2753 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2754 const analyze_printf::OptionalFlag &ignoredFlag,
2755 const analyze_printf::OptionalFlag &flag,
2756 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002757 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith55ce3522012-06-25 20:30:08 +00002758 const Expr *E, const CharSourceRange &CSR);
2759
Ted Kremenek02087932010-07-16 02:11:22 +00002760};
2761}
2762
2763bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2764 const analyze_printf::PrintfSpecifier &FS,
2765 const char *startSpecifier,
2766 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002767 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002768 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002769
Ted Kremenekce815422010-07-19 21:25:57 +00002770 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2771 getLocationOfByte(CS.getStart()),
2772 startSpecifier, specifierLen,
2773 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002774}
2775
Ted Kremenek02087932010-07-16 02:11:22 +00002776bool CheckPrintfHandler::HandleAmount(
2777 const analyze_format_string::OptionalAmount &Amt,
2778 unsigned k, const char *startSpecifier,
2779 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002780
2781 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002782 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002783 unsigned argIndex = Amt.getArgIndex();
2784 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002785 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2786 << k,
2787 getLocationOfByte(Amt.getStart()),
2788 /*IsStringLocation*/true,
2789 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002790 // Don't do any more checking. We will just emit
2791 // spurious errors.
2792 return false;
2793 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002794
Ted Kremenek5739de72010-01-29 01:06:55 +00002795 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002796 // Although not in conformance with C99, we also allow the argument to be
2797 // an 'unsigned int' as that is a reasonably safe case. GCC also
2798 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002799 CoveredArgs.set(argIndex);
2800 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002801 if (!Arg)
2802 return false;
2803
Ted Kremenek5739de72010-01-29 01:06:55 +00002804 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002805
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002806 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2807 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002808
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002809 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002810 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002811 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002812 << T << Arg->getSourceRange(),
2813 getLocationOfByte(Amt.getStart()),
2814 /*IsStringLocation*/true,
2815 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002816 // Don't do any more checking. We will just emit
2817 // spurious errors.
2818 return false;
2819 }
2820 }
2821 }
2822 return true;
2823}
Ted Kremenek5739de72010-01-29 01:06:55 +00002824
Tom Careb49ec692010-06-17 19:00:27 +00002825void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002826 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002827 const analyze_printf::OptionalAmount &Amt,
2828 unsigned type,
2829 const char *startSpecifier,
2830 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002831 const analyze_printf::PrintfConversionSpecifier &CS =
2832 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002833
Richard Trieu03cf7b72011-10-28 00:41:25 +00002834 FixItHint fixit =
2835 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2836 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2837 Amt.getConstantLength()))
2838 : FixItHint();
2839
2840 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2841 << type << CS.toString(),
2842 getLocationOfByte(Amt.getStart()),
2843 /*IsStringLocation*/true,
2844 getSpecifierRange(startSpecifier, specifierLen),
2845 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002846}
2847
Ted Kremenek02087932010-07-16 02:11:22 +00002848void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002849 const analyze_printf::OptionalFlag &flag,
2850 const char *startSpecifier,
2851 unsigned specifierLen) {
2852 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002853 const analyze_printf::PrintfConversionSpecifier &CS =
2854 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002855 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2856 << flag.toString() << CS.toString(),
2857 getLocationOfByte(flag.getPosition()),
2858 /*IsStringLocation*/true,
2859 getSpecifierRange(startSpecifier, specifierLen),
2860 FixItHint::CreateRemoval(
2861 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002862}
2863
2864void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002865 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002866 const analyze_printf::OptionalFlag &ignoredFlag,
2867 const analyze_printf::OptionalFlag &flag,
2868 const char *startSpecifier,
2869 unsigned specifierLen) {
2870 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002871 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2872 << ignoredFlag.toString() << flag.toString(),
2873 getLocationOfByte(ignoredFlag.getPosition()),
2874 /*IsStringLocation*/true,
2875 getSpecifierRange(startSpecifier, specifierLen),
2876 FixItHint::CreateRemoval(
2877 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002878}
2879
Richard Smith55ce3522012-06-25 20:30:08 +00002880// Determines if the specified is a C++ class or struct containing
2881// a member with the specified name and kind (e.g. a CXXMethodDecl named
2882// "c_str()").
2883template<typename MemberKind>
2884static llvm::SmallPtrSet<MemberKind*, 1>
2885CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2886 const RecordType *RT = Ty->getAs<RecordType>();
2887 llvm::SmallPtrSet<MemberKind*, 1> Results;
2888
2889 if (!RT)
2890 return Results;
2891 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2892 if (!RD)
2893 return Results;
2894
2895 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2896 Sema::LookupMemberName);
2897
2898 // We just need to include all members of the right kind turned up by the
2899 // filter, at this point.
2900 if (S.LookupQualifiedName(R, RT->getDecl()))
2901 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2902 NamedDecl *decl = (*I)->getUnderlyingDecl();
2903 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2904 Results.insert(FK);
2905 }
2906 return Results;
2907}
2908
2909// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002910// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002911// Returns true when a c_str() conversion method is found.
2912bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002913 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith55ce3522012-06-25 20:30:08 +00002914 const CharSourceRange &CSR) {
2915 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2916
2917 MethodSet Results =
2918 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2919
2920 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2921 MI != ME; ++MI) {
2922 const CXXMethodDecl *Method = *MI;
2923 if (Method->getNumParams() == 0 &&
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002924 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002925 // FIXME: Suggest parens if the expression needs them.
2926 SourceLocation EndLoc =
2927 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2928 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2929 << "c_str()"
2930 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2931 return true;
2932 }
2933 }
2934
2935 return false;
2936}
2937
Ted Kremenekab278de2010-01-28 23:39:18 +00002938bool
Ted Kremenek02087932010-07-16 02:11:22 +00002939CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002940 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002941 const char *startSpecifier,
2942 unsigned specifierLen) {
2943
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002944 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002945 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002946 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002947
Ted Kremenek6cd69422010-07-19 22:01:06 +00002948 if (FS.consumesDataArgument()) {
2949 if (atFirstArg) {
2950 atFirstArg = false;
2951 usesPositionalArgs = FS.usesPositionalArg();
2952 }
2953 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002954 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2955 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002956 return false;
2957 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002958 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002959
Ted Kremenekd1668192010-02-27 01:41:03 +00002960 // First check if the field width, precision, and conversion specifier
2961 // have matching data arguments.
2962 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2963 startSpecifier, specifierLen)) {
2964 return false;
2965 }
2966
2967 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2968 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002969 return false;
2970 }
2971
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002972 if (!CS.consumesDataArgument()) {
2973 // FIXME: Technically specifying a precision or field width here
2974 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002975 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002976 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002977
Ted Kremenek4a49d982010-02-26 19:18:41 +00002978 // Consume the argument.
2979 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002980 if (argIndex < NumDataArgs) {
2981 // The check to see if the argIndex is valid will come later.
2982 // We set the bit here because we may exit early from this
2983 // function if we encounter some other error.
2984 CoveredArgs.set(argIndex);
2985 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002986
2987 // Check for using an Objective-C specific conversion specifier
2988 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002989 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002990 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2991 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00002992 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002993
Tom Careb49ec692010-06-17 19:00:27 +00002994 // Check for invalid use of field width
2995 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00002996 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00002997 startSpecifier, specifierLen);
2998 }
2999
3000 // Check for invalid use of precision
3001 if (!FS.hasValidPrecision()) {
3002 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3003 startSpecifier, specifierLen);
3004 }
3005
3006 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003007 if (!FS.hasValidThousandsGroupingPrefix())
3008 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003009 if (!FS.hasValidLeadingZeros())
3010 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3011 if (!FS.hasValidPlusPrefix())
3012 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003013 if (!FS.hasValidSpacePrefix())
3014 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003015 if (!FS.hasValidAlternativeForm())
3016 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3017 if (!FS.hasValidLeftJustified())
3018 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3019
3020 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003021 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3022 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3023 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003024 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3025 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3026 startSpecifier, specifierLen);
3027
3028 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003029 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003030 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3031 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003032 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003033 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003034 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003035 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3036 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003037
Jordan Rose92303592012-09-08 04:00:03 +00003038 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3039 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3040
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003041 // The remaining checks depend on the data arguments.
3042 if (HasVAListArg)
3043 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003044
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003045 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003046 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003047
Jordan Rose58bbe422012-07-19 18:10:08 +00003048 const Expr *Arg = getDataArg(argIndex);
3049 if (!Arg)
3050 return true;
3051
3052 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003053}
3054
Jordan Roseaee34382012-09-05 22:56:26 +00003055static bool requiresParensToAddCast(const Expr *E) {
3056 // FIXME: We should have a general way to reason about operator
3057 // precedence and whether parens are actually needed here.
3058 // Take care of a few common cases where they aren't.
3059 const Expr *Inside = E->IgnoreImpCasts();
3060 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3061 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3062
3063 switch (Inside->getStmtClass()) {
3064 case Stmt::ArraySubscriptExprClass:
3065 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003066 case Stmt::CharacterLiteralClass:
3067 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003068 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003069 case Stmt::FloatingLiteralClass:
3070 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003071 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003072 case Stmt::ObjCArrayLiteralClass:
3073 case Stmt::ObjCBoolLiteralExprClass:
3074 case Stmt::ObjCBoxedExprClass:
3075 case Stmt::ObjCDictionaryLiteralClass:
3076 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003077 case Stmt::ObjCIvarRefExprClass:
3078 case Stmt::ObjCMessageExprClass:
3079 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003080 case Stmt::ObjCStringLiteralClass:
3081 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003082 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003083 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003084 case Stmt::UnaryOperatorClass:
3085 return false;
3086 default:
3087 return true;
3088 }
3089}
3090
Richard Smith55ce3522012-06-25 20:30:08 +00003091bool
3092CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3093 const char *StartSpecifier,
3094 unsigned SpecifierLen,
3095 const Expr *E) {
3096 using namespace analyze_format_string;
3097 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003098 // Now type check the data expression that matches the
3099 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003100 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3101 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003102 if (!AT.isValid())
3103 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003104
Jordan Rose598ec092012-12-05 18:44:40 +00003105 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003106 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3107 ExprTy = TET->getUnderlyingExpr()->getType();
3108 }
3109
Jordan Rose598ec092012-12-05 18:44:40 +00003110 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003111 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003112
Jordan Rose22b74712012-09-05 22:56:19 +00003113 // Look through argument promotions for our error message's reported type.
3114 // This includes the integral and floating promotions, but excludes array
3115 // and function pointer decay; seeing that an argument intended to be a
3116 // string has type 'char [6]' is probably more confusing than 'char *'.
3117 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3118 if (ICE->getCastKind() == CK_IntegralCast ||
3119 ICE->getCastKind() == CK_FloatingCast) {
3120 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003121 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003122
3123 // Check if we didn't match because of an implicit cast from a 'char'
3124 // or 'short' to an 'int'. This is done because printf is a varargs
3125 // function.
3126 if (ICE->getType() == S.Context.IntTy ||
3127 ICE->getType() == S.Context.UnsignedIntTy) {
3128 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003129 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003130 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003131 }
Jordan Rose98709982012-06-04 22:48:57 +00003132 }
Jordan Rose598ec092012-12-05 18:44:40 +00003133 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3134 // Special case for 'a', which has type 'int' in C.
3135 // Note, however, that we do /not/ want to treat multibyte constants like
3136 // 'MooV' as characters! This form is deprecated but still exists.
3137 if (ExprTy == S.Context.IntTy)
3138 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3139 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003140 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003141
Jordan Rose0e5badd2012-12-05 18:44:49 +00003142 // %C in an Objective-C context prints a unichar, not a wchar_t.
3143 // If the argument is an integer of some kind, believe the %C and suggest
3144 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003145 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003146 if (ObjCContext &&
3147 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3148 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3149 !ExprTy->isCharType()) {
3150 // 'unichar' is defined as a typedef of unsigned short, but we should
3151 // prefer using the typedef if it is visible.
3152 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003153
3154 // While we are here, check if the value is an IntegerLiteral that happens
3155 // to be within the valid range.
3156 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3157 const llvm::APInt &V = IL->getValue();
3158 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3159 return true;
3160 }
3161
Jordan Rose0e5badd2012-12-05 18:44:49 +00003162 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3163 Sema::LookupOrdinaryName);
3164 if (S.LookupName(Result, S.getCurScope())) {
3165 NamedDecl *ND = Result.getFoundDecl();
3166 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3167 if (TD->getUnderlyingType() == IntendedTy)
3168 IntendedTy = S.Context.getTypedefType(TD);
3169 }
3170 }
3171 }
3172
3173 // Special-case some of Darwin's platform-independence types by suggesting
3174 // casts to primitive types that are known to be large enough.
3175 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003176 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003177 // Use a 'while' to peel off layers of typedefs.
3178 QualType TyTy = IntendedTy;
3179 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003180 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003181 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003182 .Case("NSInteger", S.Context.LongTy)
3183 .Case("NSUInteger", S.Context.UnsignedLongTy)
3184 .Case("SInt32", S.Context.IntTy)
3185 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003186 .Default(QualType());
3187
3188 if (!CastTy.isNull()) {
3189 ShouldNotPrintDirectly = true;
3190 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003191 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003192 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003193 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003194 }
3195 }
3196
Jordan Rose22b74712012-09-05 22:56:19 +00003197 // We may be able to offer a FixItHint if it is a supported type.
3198 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003199 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003200 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003201
Jordan Rose22b74712012-09-05 22:56:19 +00003202 if (success) {
3203 // Get the fix string from the fixed format specifier
3204 SmallString<16> buf;
3205 llvm::raw_svector_ostream os(buf);
3206 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003207
Jordan Roseaee34382012-09-05 22:56:26 +00003208 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3209
Jordan Rose0e5badd2012-12-05 18:44:49 +00003210 if (IntendedTy == ExprTy) {
3211 // In this case, the specifier is wrong and should be changed to match
3212 // the argument.
3213 EmitFormatDiagnostic(
3214 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3215 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3216 << E->getSourceRange(),
3217 E->getLocStart(),
3218 /*IsStringLocation*/false,
3219 SpecRange,
3220 FixItHint::CreateReplacement(SpecRange, os.str()));
3221
3222 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003223 // The canonical type for formatting this value is different from the
3224 // actual type of the expression. (This occurs, for example, with Darwin's
3225 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3226 // should be printed as 'long' for 64-bit compatibility.)
3227 // Rather than emitting a normal format/argument mismatch, we want to
3228 // add a cast to the recommended type (and correct the format string
3229 // if necessary).
3230 SmallString<16> CastBuf;
3231 llvm::raw_svector_ostream CastFix(CastBuf);
3232 CastFix << "(";
3233 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3234 CastFix << ")";
3235
3236 SmallVector<FixItHint,4> Hints;
3237 if (!AT.matchesType(S.Context, IntendedTy))
3238 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3239
3240 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3241 // If there's already a cast present, just replace it.
3242 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3243 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3244
3245 } else if (!requiresParensToAddCast(E)) {
3246 // If the expression has high enough precedence,
3247 // just write the C-style cast.
3248 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3249 CastFix.str()));
3250 } else {
3251 // Otherwise, add parens around the expression as well as the cast.
3252 CastFix << "(";
3253 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3254 CastFix.str()));
3255
3256 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3257 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3258 }
3259
Jordan Rose0e5badd2012-12-05 18:44:49 +00003260 if (ShouldNotPrintDirectly) {
3261 // The expression has a type that should not be printed directly.
3262 // We extract the name from the typedef because we don't want to show
3263 // the underlying type in the diagnostic.
3264 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003265
Jordan Rose0e5badd2012-12-05 18:44:49 +00003266 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3267 << Name << IntendedTy
3268 << E->getSourceRange(),
3269 E->getLocStart(), /*IsStringLocation=*/false,
3270 SpecRange, Hints);
3271 } else {
3272 // In this case, the expression could be printed using a different
3273 // specifier, but we've decided that the specifier is probably correct
3274 // and we should cast instead. Just use the normal warning message.
3275 EmitFormatDiagnostic(
3276 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3277 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3278 << E->getSourceRange(),
3279 E->getLocStart(), /*IsStringLocation*/false,
3280 SpecRange, Hints);
3281 }
Jordan Roseaee34382012-09-05 22:56:26 +00003282 }
Jordan Rose22b74712012-09-05 22:56:19 +00003283 } else {
3284 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3285 SpecifierLen);
3286 // Since the warning for passing non-POD types to variadic functions
3287 // was deferred until now, we emit a warning for non-POD
3288 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003289 switch (S.isValidVarArgType(ExprTy)) {
3290 case Sema::VAK_Valid:
3291 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003292 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003293 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3294 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3295 << CSR
3296 << E->getSourceRange(),
3297 E->getLocStart(), /*IsStringLocation*/false, CSR);
3298 break;
3299
3300 case Sema::VAK_Undefined:
3301 EmitFormatDiagnostic(
3302 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003303 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003304 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003305 << CallType
3306 << AT.getRepresentativeTypeName(S.Context)
3307 << CSR
3308 << E->getSourceRange(),
3309 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose22b74712012-09-05 22:56:19 +00003310 checkForCStrMembers(AT, E, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00003311 break;
3312
3313 case Sema::VAK_Invalid:
3314 if (ExprTy->isObjCObjectType())
3315 EmitFormatDiagnostic(
3316 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3317 << S.getLangOpts().CPlusPlus11
3318 << ExprTy
3319 << CallType
3320 << AT.getRepresentativeTypeName(S.Context)
3321 << CSR
3322 << E->getSourceRange(),
3323 E->getLocStart(), /*IsStringLocation*/false, CSR);
3324 else
3325 // FIXME: If this is an initializer list, suggest removing the braces
3326 // or inserting a cast to the target type.
3327 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3328 << isa<InitListExpr>(E) << ExprTy << CallType
3329 << AT.getRepresentativeTypeName(S.Context)
3330 << E->getSourceRange();
3331 break;
3332 }
3333
3334 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3335 "format string specifier index out of range");
3336 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003337 }
3338
Ted Kremenekab278de2010-01-28 23:39:18 +00003339 return true;
3340}
3341
Ted Kremenek02087932010-07-16 02:11:22 +00003342//===--- CHECK: Scanf format string checking ------------------------------===//
3343
3344namespace {
3345class CheckScanfHandler : public CheckFormatHandler {
3346public:
3347 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3348 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003349 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003350 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003351 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003352 Sema::VariadicCallType CallType,
3353 llvm::SmallBitVector &CheckedVarArgs)
3354 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3355 numDataArgs, beg, hasVAListArg,
3356 Args, formatIdx, inFunctionCall, CallType,
3357 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003358 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003359
3360 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3361 const char *startSpecifier,
3362 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003363
3364 bool HandleInvalidScanfConversionSpecifier(
3365 const analyze_scanf::ScanfSpecifier &FS,
3366 const char *startSpecifier,
3367 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003368
3369 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00003370};
Ted Kremenek019d2242010-01-29 01:50:07 +00003371}
Ted Kremenekab278de2010-01-28 23:39:18 +00003372
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003373void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3374 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003375 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3376 getLocationOfByte(end), /*IsStringLocation*/true,
3377 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003378}
3379
Ted Kremenekce815422010-07-19 21:25:57 +00003380bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3381 const analyze_scanf::ScanfSpecifier &FS,
3382 const char *startSpecifier,
3383 unsigned specifierLen) {
3384
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003385 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003386 FS.getConversionSpecifier();
3387
3388 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3389 getLocationOfByte(CS.getStart()),
3390 startSpecifier, specifierLen,
3391 CS.getStart(), CS.getLength());
3392}
3393
Ted Kremenek02087932010-07-16 02:11:22 +00003394bool CheckScanfHandler::HandleScanfSpecifier(
3395 const analyze_scanf::ScanfSpecifier &FS,
3396 const char *startSpecifier,
3397 unsigned specifierLen) {
3398
3399 using namespace analyze_scanf;
3400 using namespace analyze_format_string;
3401
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003402 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003403
Ted Kremenek6cd69422010-07-19 22:01:06 +00003404 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3405 // be used to decide if we are using positional arguments consistently.
3406 if (FS.consumesDataArgument()) {
3407 if (atFirstArg) {
3408 atFirstArg = false;
3409 usesPositionalArgs = FS.usesPositionalArg();
3410 }
3411 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003412 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3413 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003414 return false;
3415 }
Ted Kremenek02087932010-07-16 02:11:22 +00003416 }
3417
3418 // Check if the field with is non-zero.
3419 const OptionalAmount &Amt = FS.getFieldWidth();
3420 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3421 if (Amt.getConstantAmount() == 0) {
3422 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3423 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003424 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3425 getLocationOfByte(Amt.getStart()),
3426 /*IsStringLocation*/true, R,
3427 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003428 }
3429 }
3430
3431 if (!FS.consumesDataArgument()) {
3432 // FIXME: Technically specifying a precision or field width here
3433 // makes no sense. Worth issuing a warning at some point.
3434 return true;
3435 }
3436
3437 // Consume the argument.
3438 unsigned argIndex = FS.getArgIndex();
3439 if (argIndex < NumDataArgs) {
3440 // The check to see if the argIndex is valid will come later.
3441 // We set the bit here because we may exit early from this
3442 // function if we encounter some other error.
3443 CoveredArgs.set(argIndex);
3444 }
3445
Ted Kremenek4407ea42010-07-20 20:04:47 +00003446 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003447 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003448 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3449 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003450 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003451 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003452 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003453 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3454 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003455
Jordan Rose92303592012-09-08 04:00:03 +00003456 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3457 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3458
Ted Kremenek02087932010-07-16 02:11:22 +00003459 // The remaining checks depend on the data arguments.
3460 if (HasVAListArg)
3461 return true;
3462
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003463 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003464 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003465
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003466 // Check that the argument type matches the format specifier.
3467 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003468 if (!Ex)
3469 return true;
3470
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003471 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3472 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003473 ScanfSpecifier fixedFS = FS;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003474 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgd99d6882012-02-15 09:59:46 +00003475 S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003476
3477 if (success) {
3478 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003479 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003480 llvm::raw_svector_ostream os(buf);
3481 fixedFS.toString(os);
3482
3483 EmitFormatDiagnostic(
3484 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003485 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003486 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003487 Ex->getLocStart(),
3488 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003489 getSpecifierRange(startSpecifier, specifierLen),
3490 FixItHint::CreateReplacement(
3491 getSpecifierRange(startSpecifier, specifierLen),
3492 os.str()));
3493 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003494 EmitFormatDiagnostic(
3495 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003496 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003497 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003498 Ex->getLocStart(),
3499 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003500 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003501 }
3502 }
3503
Ted Kremenek02087932010-07-16 02:11:22 +00003504 return true;
3505}
3506
3507void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003508 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003509 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003510 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003511 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003512 bool inFunctionCall, VariadicCallType CallType,
3513 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003514
Ted Kremenekab278de2010-01-28 23:39:18 +00003515 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003516 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003517 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003518 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003519 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3520 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003521 return;
3522 }
Ted Kremenek02087932010-07-16 02:11:22 +00003523
Ted Kremenekab278de2010-01-28 23:39:18 +00003524 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003525 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003526 const char *Str = StrRef.data();
3527 unsigned StrLen = StrRef.size();
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003528 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek02087932010-07-16 02:11:22 +00003529
Ted Kremenekab278de2010-01-28 23:39:18 +00003530 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003531 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003532 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003533 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003534 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3535 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003536 return;
3537 }
Ted Kremenek02087932010-07-16 02:11:22 +00003538
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003539 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003540 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003541 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003542 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003543 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003544
Hans Wennborg23926bd2011-12-15 10:25:47 +00003545 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003546 getLangOpts(),
3547 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003548 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003549 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003550 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003551 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003552 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003553
Hans Wennborg23926bd2011-12-15 10:25:47 +00003554 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003555 getLangOpts(),
3556 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003557 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003558 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003559}
3560
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003561//===--- CHECK: Standard memory functions ---------------------------------===//
3562
Nico Weber0e6daef2013-12-26 23:38:39 +00003563/// \brief Takes the expression passed to the size_t parameter of functions
3564/// such as memcmp, strncat, etc and warns if it's a comparison.
3565///
3566/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3567static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3568 IdentifierInfo *FnName,
3569 SourceLocation FnLoc,
3570 SourceLocation RParenLoc) {
3571 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3572 if (!Size)
3573 return false;
3574
3575 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3576 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3577 return false;
3578
3579 Preprocessor &PP = S.getPreprocessor();
3580 SourceRange SizeRange = Size->getSourceRange();
3581 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3582 << SizeRange << FnName;
3583 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3584 << FnName
3585 << FixItHint::CreateInsertion(
3586 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3587 ")")
3588 << FixItHint::CreateRemoval(RParenLoc);
3589 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3590 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3591 << FixItHint::CreateInsertion(
3592 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3593
3594 return true;
3595}
3596
Douglas Gregora74926b2011-05-03 20:05:22 +00003597/// \brief Determine whether the given type is a dynamic class type (e.g.,
3598/// whether it has a vtable).
3599static bool isDynamicClassType(QualType T) {
3600 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3601 if (CXXRecordDecl *Definition = Record->getDefinition())
3602 if (Definition->isDynamicClass())
3603 return true;
3604
3605 return false;
3606}
3607
Chandler Carruth889ed862011-06-21 23:04:20 +00003608/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003609/// otherwise returns NULL.
3610static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003611 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003612 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3613 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3614 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003615
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003616 return 0;
3617}
3618
Chandler Carruth889ed862011-06-21 23:04:20 +00003619/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003620static QualType getSizeOfArgType(const Expr* E) {
3621 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3622 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3623 if (SizeOf->getKind() == clang::UETT_SizeOf)
3624 return SizeOf->getTypeOfArgument();
3625
3626 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00003627}
3628
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003629/// \brief Check for dangerous or invalid arguments to memset().
3630///
Chandler Carruthac687262011-06-03 06:23:57 +00003631/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003632/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3633/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003634///
3635/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003636void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00003637 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003638 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00003639 assert(BId != 0);
3640
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003641 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00003642 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00003643 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00003644 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003645 return;
3646
Anna Zaks22122702012-01-17 00:37:07 +00003647 unsigned LastArg = (BId == Builtin::BImemset ||
3648 BId == Builtin::BIstrndup ? 1 : 2);
3649 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00003650 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003651
Nico Weber0e6daef2013-12-26 23:38:39 +00003652 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
3653 Call->getLocStart(), Call->getRParenLoc()))
3654 return;
3655
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003656 // We have special checking when the length is a sizeof expression.
3657 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3658 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3659 llvm::FoldingSetNodeID SizeOfArgID;
3660
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003661 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3662 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003663 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003664
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003665 QualType DestTy = Dest->getType();
3666 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3667 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00003668
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003669 // Never warn about void type pointers. This can be used to suppress
3670 // false positives.
3671 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003672 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003673
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003674 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3675 // actually comparing the expressions for equality. Because computing the
3676 // expression IDs can be expensive, we only do this if the diagnostic is
3677 // enabled.
3678 if (SizeOfArg &&
3679 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3680 SizeOfArg->getExprLoc())) {
3681 // We only compute IDs for expressions if the warning is enabled, and
3682 // cache the sizeof arg's ID.
3683 if (SizeOfArgID == llvm::FoldingSetNodeID())
3684 SizeOfArg->Profile(SizeOfArgID, Context, true);
3685 llvm::FoldingSetNodeID DestID;
3686 Dest->Profile(DestID, Context, true);
3687 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00003688 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3689 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003690 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00003691 StringRef ReadableName = FnName->getName();
3692
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003693 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00003694 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003695 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00003696 if (!PointeeTy->isIncompleteType() &&
3697 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003698 ActionIdx = 2; // If the pointee's size is sizeof(char),
3699 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00003700
3701 // If the function is defined as a builtin macro, do not show macro
3702 // expansion.
3703 SourceLocation SL = SizeOfArg->getExprLoc();
3704 SourceRange DSR = Dest->getSourceRange();
3705 SourceRange SSR = SizeOfArg->getSourceRange();
3706 SourceManager &SM = PP.getSourceManager();
3707
3708 if (SM.isMacroArgExpansion(SL)) {
3709 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3710 SL = SM.getSpellingLoc(SL);
3711 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3712 SM.getSpellingLoc(DSR.getEnd()));
3713 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3714 SM.getSpellingLoc(SSR.getEnd()));
3715 }
3716
Anna Zaksd08d9152012-05-30 23:14:52 +00003717 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003718 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00003719 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00003720 << PointeeTy
3721 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00003722 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00003723 << SSR);
3724 DiagRuntimeBehavior(SL, SizeOfArg,
3725 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3726 << ActionIdx
3727 << SSR);
3728
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003729 break;
3730 }
3731 }
3732
3733 // Also check for cases where the sizeof argument is the exact same
3734 // type as the memory argument, and where it points to a user-defined
3735 // record type.
3736 if (SizeOfArgTy != QualType()) {
3737 if (PointeeTy->isRecordType() &&
3738 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3739 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3740 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3741 << FnName << SizeOfArgTy << ArgIdx
3742 << PointeeTy << Dest->getSourceRange()
3743 << LenExpr->getSourceRange());
3744 break;
3745 }
Nico Weberc5e73862011-06-14 16:14:58 +00003746 }
3747
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003748 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00003749 if (isDynamicClassType(PointeeTy)) {
3750
3751 unsigned OperationType = 0;
3752 // "overwritten" if we're warning about the destination for any call
3753 // but memcmp; otherwise a verb appropriate to the call.
3754 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3755 if (BId == Builtin::BImemcpy)
3756 OperationType = 1;
3757 else if(BId == Builtin::BImemmove)
3758 OperationType = 2;
3759 else if (BId == Builtin::BImemcmp)
3760 OperationType = 3;
3761 }
3762
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003763 DiagRuntimeBehavior(
3764 Dest->getExprLoc(), Dest,
3765 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00003766 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00003767 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00003768 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003769 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00003770 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3771 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003772 DiagRuntimeBehavior(
3773 Dest->getExprLoc(), Dest,
3774 PDiag(diag::warn_arc_object_memaccess)
3775 << ArgIdx << FnName << PointeeTy
3776 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00003777 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003778 continue;
John McCall31168b02011-06-15 23:02:42 +00003779
3780 DiagRuntimeBehavior(
3781 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00003782 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003783 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3784 break;
3785 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003786 }
3787}
3788
Ted Kremenek6865f772011-08-18 20:55:45 +00003789// A little helper routine: ignore addition and subtraction of integer literals.
3790// This intentionally does not ignore all integer constant expressions because
3791// we don't want to remove sizeof().
3792static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3793 Ex = Ex->IgnoreParenCasts();
3794
3795 for (;;) {
3796 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3797 if (!BO || !BO->isAdditiveOp())
3798 break;
3799
3800 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3801 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3802
3803 if (isa<IntegerLiteral>(RHS))
3804 Ex = LHS;
3805 else if (isa<IntegerLiteral>(LHS))
3806 Ex = RHS;
3807 else
3808 break;
3809 }
3810
3811 return Ex;
3812}
3813
Anna Zaks13b08572012-08-08 21:42:23 +00003814static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3815 ASTContext &Context) {
3816 // Only handle constant-sized or VLAs, but not flexible members.
3817 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3818 // Only issue the FIXIT for arrays of size > 1.
3819 if (CAT->getSize().getSExtValue() <= 1)
3820 return false;
3821 } else if (!Ty->isVariableArrayType()) {
3822 return false;
3823 }
3824 return true;
3825}
3826
Ted Kremenek6865f772011-08-18 20:55:45 +00003827// Warn if the user has made the 'size' argument to strlcpy or strlcat
3828// be the size of the source, instead of the destination.
3829void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3830 IdentifierInfo *FnName) {
3831
3832 // Don't crash if the user has the wrong number of arguments
3833 if (Call->getNumArgs() != 3)
3834 return;
3835
3836 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3837 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3838 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00003839
3840 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
3841 Call->getLocStart(), Call->getRParenLoc()))
3842 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00003843
3844 // Look for 'strlcpy(dst, x, sizeof(x))'
3845 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3846 CompareWithSrc = Ex;
3847 else {
3848 // Look for 'strlcpy(dst, x, strlen(x))'
3849 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00003850 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
3851 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00003852 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3853 }
3854 }
3855
3856 if (!CompareWithSrc)
3857 return;
3858
3859 // Determine if the argument to sizeof/strlen is equal to the source
3860 // argument. In principle there's all kinds of things you could do
3861 // here, for instance creating an == expression and evaluating it with
3862 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3863 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3864 if (!SrcArgDRE)
3865 return;
3866
3867 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3868 if (!CompareWithSrcDRE ||
3869 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3870 return;
3871
3872 const Expr *OriginalSizeArg = Call->getArg(2);
3873 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3874 << OriginalSizeArg->getSourceRange() << FnName;
3875
3876 // Output a FIXIT hint if the destination is an array (rather than a
3877 // pointer to an array). This could be enhanced to handle some
3878 // pointers if we know the actual size, like if DstArg is 'array+2'
3879 // we could say 'sizeof(array)-2'.
3880 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00003881 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00003882 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003883
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003884 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003885 llvm::raw_svector_ostream OS(sizeString);
3886 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00003887 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00003888 OS << ")";
3889
3890 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3891 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3892 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00003893}
3894
Anna Zaks314cd092012-02-01 19:08:57 +00003895/// Check if two expressions refer to the same declaration.
3896static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3897 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3898 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3899 return D1->getDecl() == D2->getDecl();
3900 return false;
3901}
3902
3903static const Expr *getStrlenExprArg(const Expr *E) {
3904 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3905 const FunctionDecl *FD = CE->getDirectCallee();
3906 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3907 return 0;
3908 return CE->getArg(0)->IgnoreParenCasts();
3909 }
3910 return 0;
3911}
3912
3913// Warn on anti-patterns as the 'size' argument to strncat.
3914// The correct size argument should look like following:
3915// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3916void Sema::CheckStrncatArguments(const CallExpr *CE,
3917 IdentifierInfo *FnName) {
3918 // Don't crash if the user has the wrong number of arguments.
3919 if (CE->getNumArgs() < 3)
3920 return;
3921 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3922 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3923 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3924
Nico Weber0e6daef2013-12-26 23:38:39 +00003925 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
3926 CE->getRParenLoc()))
3927 return;
3928
Anna Zaks314cd092012-02-01 19:08:57 +00003929 // Identify common expressions, which are wrongly used as the size argument
3930 // to strncat and may lead to buffer overflows.
3931 unsigned PatternType = 0;
3932 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3933 // - sizeof(dst)
3934 if (referToTheSameDecl(SizeOfArg, DstArg))
3935 PatternType = 1;
3936 // - sizeof(src)
3937 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3938 PatternType = 2;
3939 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3940 if (BE->getOpcode() == BO_Sub) {
3941 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3942 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3943 // - sizeof(dst) - strlen(dst)
3944 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3945 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3946 PatternType = 1;
3947 // - sizeof(src) - (anything)
3948 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3949 PatternType = 2;
3950 }
3951 }
3952
3953 if (PatternType == 0)
3954 return;
3955
Anna Zaks5069aa32012-02-03 01:27:37 +00003956 // Generate the diagnostic.
3957 SourceLocation SL = LenArg->getLocStart();
3958 SourceRange SR = LenArg->getSourceRange();
3959 SourceManager &SM = PP.getSourceManager();
3960
3961 // If the function is defined as a builtin macro, do not show macro expansion.
3962 if (SM.isMacroArgExpansion(SL)) {
3963 SL = SM.getSpellingLoc(SL);
3964 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3965 SM.getSpellingLoc(SR.getEnd()));
3966 }
3967
Anna Zaks13b08572012-08-08 21:42:23 +00003968 // Check if the destination is an array (rather than a pointer to an array).
3969 QualType DstTy = DstArg->getType();
3970 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3971 Context);
3972 if (!isKnownSizeArray) {
3973 if (PatternType == 1)
3974 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3975 else
3976 Diag(SL, diag::warn_strncat_src_size) << SR;
3977 return;
3978 }
3979
Anna Zaks314cd092012-02-01 19:08:57 +00003980 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00003981 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00003982 else
Anna Zaks5069aa32012-02-03 01:27:37 +00003983 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00003984
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003985 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00003986 llvm::raw_svector_ostream OS(sizeString);
3987 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00003988 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00003989 OS << ") - ";
3990 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00003991 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00003992 OS << ") - 1";
3993
Anna Zaks5069aa32012-02-03 01:27:37 +00003994 Diag(SL, diag::note_strncat_wrong_size)
3995 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00003996}
3997
Ted Kremenekcff94fa2007-08-17 16:46:58 +00003998//===--- CHECK: Return Address of Stack Variable --------------------------===//
3999
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004000static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4001 Decl *ParentDecl);
4002static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4003 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004004
4005/// CheckReturnStackAddr - Check if a return statement returns the address
4006/// of a stack variable.
4007void
4008Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
4009 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004010
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004011 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004012 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004013
4014 // Perform checking for returned stack addresses, local blocks,
4015 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004016 if (lhsType->isPointerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004017 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004018 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004019 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004020 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004021 }
4022
4023 if (stackE == 0)
4024 return; // Nothing suspicious was found.
4025
4026 SourceLocation diagLoc;
4027 SourceRange diagRange;
4028 if (refVars.empty()) {
4029 diagLoc = stackE->getLocStart();
4030 diagRange = stackE->getSourceRange();
4031 } else {
4032 // We followed through a reference variable. 'stackE' contains the
4033 // problematic expression but we will warn at the return statement pointing
4034 // at the reference variable. We will later display the "trail" of
4035 // reference variables using notes.
4036 diagLoc = refVars[0]->getLocStart();
4037 diagRange = refVars[0]->getSourceRange();
4038 }
4039
4040 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4041 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4042 : diag::warn_ret_stack_addr)
4043 << DR->getDecl()->getDeclName() << diagRange;
4044 } else if (isa<BlockExpr>(stackE)) { // local block.
4045 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4046 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4047 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4048 } else { // local temporary.
4049 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4050 : diag::warn_ret_local_temp_addr)
4051 << diagRange;
4052 }
4053
4054 // Display the "trail" of reference variables that we followed until we
4055 // found the problematic expression using notes.
4056 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4057 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4058 // If this var binds to another reference var, show the range of the next
4059 // var, otherwise the var binds to the problematic expression, in which case
4060 // show the range of the expression.
4061 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4062 : stackE->getSourceRange();
4063 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4064 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004065 }
4066}
4067
4068/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4069/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004070/// to a location on the stack, a local block, an address of a label, or a
4071/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004072/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004073/// encounter a subexpression that (1) clearly does not lead to one of the
4074/// above problematic expressions (2) is something we cannot determine leads to
4075/// a problematic expression based on such local checking.
4076///
4077/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4078/// the expression that they point to. Such variables are added to the
4079/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004080///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004081/// EvalAddr processes expressions that are pointers that are used as
4082/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004083/// At the base case of the recursion is a check for the above problematic
4084/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004085///
4086/// This implementation handles:
4087///
4088/// * pointer-to-pointer casts
4089/// * implicit conversions from array references to pointers
4090/// * taking the address of fields
4091/// * arbitrary interplay between "&" and "*" operators
4092/// * pointer arithmetic from an address of a stack variable
4093/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004094static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4095 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004096 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004097 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004098
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004099 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004100 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004101 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004102 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004103 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004104
Peter Collingbourne91147592011-04-15 00:35:48 +00004105 E = E->IgnoreParens();
4106
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004107 // Our "symbolic interpreter" is just a dispatch off the currently
4108 // viewed AST node. We then recursively traverse the AST by calling
4109 // EvalAddr and EvalVal appropriately.
4110 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004111 case Stmt::DeclRefExprClass: {
4112 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4113
4114 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4115 // If this is a reference variable, follow through to the expression that
4116 // it points to.
4117 if (V->hasLocalStorage() &&
4118 V->getType()->isReferenceType() && V->hasInit()) {
4119 // Add the reference variable to the "trail".
4120 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004121 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004122 }
4123
4124 return NULL;
4125 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004126
Chris Lattner934edb22007-12-28 05:31:15 +00004127 case Stmt::UnaryOperatorClass: {
4128 // The only unary operator that make sense to handle here
4129 // is AddrOf. All others don't make sense as pointers.
4130 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004131
John McCalle3027922010-08-25 11:45:40 +00004132 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004133 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004134 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004135 return NULL;
4136 }
Mike Stump11289f42009-09-09 15:08:12 +00004137
Chris Lattner934edb22007-12-28 05:31:15 +00004138 case Stmt::BinaryOperatorClass: {
4139 // Handle pointer arithmetic. All other binary operators are not valid
4140 // in this context.
4141 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004142 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004143
John McCalle3027922010-08-25 11:45:40 +00004144 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004145 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004146
Chris Lattner934edb22007-12-28 05:31:15 +00004147 Expr *Base = B->getLHS();
4148
4149 // Determine which argument is the real pointer base. It could be
4150 // the RHS argument instead of the LHS.
4151 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004152
Chris Lattner934edb22007-12-28 05:31:15 +00004153 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004154 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004155 }
Steve Naroff2752a172008-09-10 19:17:48 +00004156
Chris Lattner934edb22007-12-28 05:31:15 +00004157 // For conditional operators we need to see if either the LHS or RHS are
4158 // valid DeclRefExpr*s. If one of them is valid, we return it.
4159 case Stmt::ConditionalOperatorClass: {
4160 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004161
Chris Lattner934edb22007-12-28 05:31:15 +00004162 // Handle the GNU extension for missing LHS.
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004163 if (Expr *lhsExpr = C->getLHS()) {
4164 // In C++, we can have a throw-expression, which has 'void' type.
4165 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004166 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004167 return LHS;
4168 }
Chris Lattner934edb22007-12-28 05:31:15 +00004169
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004170 // In C++, we can have a throw-expression, which has 'void' type.
4171 if (C->getRHS()->getType()->isVoidType())
4172 return NULL;
4173
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004174 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004175 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004176
4177 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004178 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004179 return E; // local block.
4180 return NULL;
4181
4182 case Stmt::AddrLabelExprClass:
4183 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004184
John McCall28fc7092011-11-10 05:35:25 +00004185 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004186 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4187 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004188
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004189 // For casts, we need to handle conversions from arrays to
4190 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004191 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004192 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004193 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004194 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004195 case Stmt::CXXStaticCastExprClass:
4196 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004197 case Stmt::CXXConstCastExprClass:
4198 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004199 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4200 switch (cast<CastExpr>(E)->getCastKind()) {
4201 case CK_BitCast:
4202 case CK_LValueToRValue:
4203 case CK_NoOp:
4204 case CK_BaseToDerived:
4205 case CK_DerivedToBase:
4206 case CK_UncheckedDerivedToBase:
4207 case CK_Dynamic:
4208 case CK_CPointerToObjCPointerCast:
4209 case CK_BlockPointerToObjCPointerCast:
4210 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004211 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004212
4213 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004214 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004215
4216 default:
4217 return 0;
4218 }
Chris Lattner934edb22007-12-28 05:31:15 +00004219 }
Mike Stump11289f42009-09-09 15:08:12 +00004220
Douglas Gregorfe314812011-06-21 17:03:29 +00004221 case Stmt::MaterializeTemporaryExprClass:
4222 if (Expr *Result = EvalAddr(
4223 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004224 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004225 return Result;
4226
4227 return E;
4228
Chris Lattner934edb22007-12-28 05:31:15 +00004229 // Everything else: we simply don't reason about them.
4230 default:
4231 return NULL;
4232 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004233}
Mike Stump11289f42009-09-09 15:08:12 +00004234
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004235
4236/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4237/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004238static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4239 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004240do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004241 // We should only be called for evaluating non-pointer expressions, or
4242 // expressions with a pointer type that are not used as references but instead
4243 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004244
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004245 // Our "symbolic interpreter" is just a dispatch off the currently
4246 // viewed AST node. We then recursively traverse the AST by calling
4247 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004248
4249 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004250 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004251 case Stmt::ImplicitCastExprClass: {
4252 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004253 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004254 E = IE->getSubExpr();
4255 continue;
4256 }
4257 return NULL;
4258 }
4259
John McCall28fc7092011-11-10 05:35:25 +00004260 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004261 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004262
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004263 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004264 // When we hit a DeclRefExpr we are looking at code that refers to a
4265 // variable's name. If it's not a reference variable we check if it has
4266 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004267 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004268
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004269 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4270 // Check if it refers to itself, e.g. "int& i = i;".
4271 if (V == ParentDecl)
4272 return DR;
4273
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004274 if (V->hasLocalStorage()) {
4275 if (!V->getType()->isReferenceType())
4276 return DR;
4277
4278 // Reference variable, follow through to the expression that
4279 // it points to.
4280 if (V->hasInit()) {
4281 // Add the reference variable to the "trail".
4282 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004283 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004284 }
4285 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004286 }
Mike Stump11289f42009-09-09 15:08:12 +00004287
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004288 return NULL;
4289 }
Mike Stump11289f42009-09-09 15:08:12 +00004290
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004291 case Stmt::UnaryOperatorClass: {
4292 // The only unary operator that make sense to handle here
4293 // is Deref. All others don't resolve to a "name." This includes
4294 // handling all sorts of rvalues passed to a unary operator.
4295 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004296
John McCalle3027922010-08-25 11:45:40 +00004297 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004298 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004299
4300 return NULL;
4301 }
Mike Stump11289f42009-09-09 15:08:12 +00004302
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004303 case Stmt::ArraySubscriptExprClass: {
4304 // Array subscripts are potential references to data on the stack. We
4305 // retrieve the DeclRefExpr* for the array variable if it indeed
4306 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004307 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004308 }
Mike Stump11289f42009-09-09 15:08:12 +00004309
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004310 case Stmt::ConditionalOperatorClass: {
4311 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004312 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004313 ConditionalOperator *C = cast<ConditionalOperator>(E);
4314
Anders Carlsson801c5c72007-11-30 19:04:31 +00004315 // Handle the GNU extension for missing LHS.
4316 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004317 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson801c5c72007-11-30 19:04:31 +00004318 return LHS;
4319
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004320 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004321 }
Mike Stump11289f42009-09-09 15:08:12 +00004322
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004323 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004324 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004325 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004326
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004327 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004328 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004329 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004330
4331 // Check whether the member type is itself a reference, in which case
4332 // we're not going to refer to the member, but to what the member refers to.
4333 if (M->getMemberDecl()->getType()->isReferenceType())
4334 return NULL;
4335
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004336 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004337 }
Mike Stump11289f42009-09-09 15:08:12 +00004338
Douglas Gregorfe314812011-06-21 17:03:29 +00004339 case Stmt::MaterializeTemporaryExprClass:
4340 if (Expr *Result = EvalVal(
4341 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004342 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004343 return Result;
4344
4345 return E;
4346
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004347 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004348 // Check that we don't return or take the address of a reference to a
4349 // temporary. This is only useful in C++.
4350 if (!E->isTypeDependent() && E->isRValue())
4351 return E;
4352
4353 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004354 return NULL;
4355 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004356} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004357}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004358
4359//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4360
4361/// Check for comparisons of floating point operands using != and ==.
4362/// Issue a warning if these are no self-comparisons, as they are not likely
4363/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004364void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004365 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4366 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004367
4368 // Special case: check for x == x (which is OK).
4369 // Do not emit warnings for such cases.
4370 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4371 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4372 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004373 return;
Mike Stump11289f42009-09-09 15:08:12 +00004374
4375
Ted Kremenekeda40e22007-11-29 00:59:04 +00004376 // Special case: check for comparisons against literals that can be exactly
4377 // represented by APFloat. In such cases, do not emit a warning. This
4378 // is a heuristic: often comparison against such literals are used to
4379 // detect if a value in a variable has not changed. This clearly can
4380 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004381 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4382 if (FLL->isExact())
4383 return;
4384 } else
4385 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4386 if (FLR->isExact())
4387 return;
Mike Stump11289f42009-09-09 15:08:12 +00004388
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004389 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004390 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004391 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004392 return;
Mike Stump11289f42009-09-09 15:08:12 +00004393
David Blaikie1f4ff152012-07-16 20:47:22 +00004394 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004395 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004396 return;
Mike Stump11289f42009-09-09 15:08:12 +00004397
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004398 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004399 Diag(Loc, diag::warn_floatingpoint_eq)
4400 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004401}
John McCallca01b222010-01-04 23:21:16 +00004402
John McCall70aa5392010-01-06 05:24:50 +00004403//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4404//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004405
John McCall70aa5392010-01-06 05:24:50 +00004406namespace {
John McCallca01b222010-01-04 23:21:16 +00004407
John McCall70aa5392010-01-06 05:24:50 +00004408/// Structure recording the 'active' range of an integer-valued
4409/// expression.
4410struct IntRange {
4411 /// The number of bits active in the int.
4412 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004413
John McCall70aa5392010-01-06 05:24:50 +00004414 /// True if the int is known not to have negative values.
4415 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004416
John McCall70aa5392010-01-06 05:24:50 +00004417 IntRange(unsigned Width, bool NonNegative)
4418 : Width(Width), NonNegative(NonNegative)
4419 {}
John McCallca01b222010-01-04 23:21:16 +00004420
John McCall817d4af2010-11-10 23:38:19 +00004421 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004422 static IntRange forBoolType() {
4423 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004424 }
4425
John McCall817d4af2010-11-10 23:38:19 +00004426 /// Returns the range of an opaque value of the given integral type.
4427 static IntRange forValueOfType(ASTContext &C, QualType T) {
4428 return forValueOfCanonicalType(C,
4429 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004430 }
4431
John McCall817d4af2010-11-10 23:38:19 +00004432 /// Returns the range of an opaque value of a canonical integral type.
4433 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004434 assert(T->isCanonicalUnqualified());
4435
4436 if (const VectorType *VT = dyn_cast<VectorType>(T))
4437 T = VT->getElementType().getTypePtr();
4438 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4439 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004440
David Majnemer6a426652013-06-07 22:07:20 +00004441 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004442 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004443 EnumDecl *Enum = ET->getDecl();
4444 if (!Enum->isCompleteDefinition())
4445 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004446
David Majnemer6a426652013-06-07 22:07:20 +00004447 unsigned NumPositive = Enum->getNumPositiveBits();
4448 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004449
David Majnemer6a426652013-06-07 22:07:20 +00004450 if (NumNegative == 0)
4451 return IntRange(NumPositive, true/*NonNegative*/);
4452 else
4453 return IntRange(std::max(NumPositive + 1, NumNegative),
4454 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004455 }
John McCall70aa5392010-01-06 05:24:50 +00004456
4457 const BuiltinType *BT = cast<BuiltinType>(T);
4458 assert(BT->isInteger());
4459
4460 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4461 }
4462
John McCall817d4af2010-11-10 23:38:19 +00004463 /// Returns the "target" range of a canonical integral type, i.e.
4464 /// the range of values expressible in the type.
4465 ///
4466 /// This matches forValueOfCanonicalType except that enums have the
4467 /// full range of their type, not the range of their enumerators.
4468 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4469 assert(T->isCanonicalUnqualified());
4470
4471 if (const VectorType *VT = dyn_cast<VectorType>(T))
4472 T = VT->getElementType().getTypePtr();
4473 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4474 T = CT->getElementType().getTypePtr();
4475 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004476 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004477
4478 const BuiltinType *BT = cast<BuiltinType>(T);
4479 assert(BT->isInteger());
4480
4481 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4482 }
4483
4484 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004485 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004486 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004487 L.NonNegative && R.NonNegative);
4488 }
4489
John McCall817d4af2010-11-10 23:38:19 +00004490 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004491 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004492 return IntRange(std::min(L.Width, R.Width),
4493 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004494 }
4495};
4496
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004497static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4498 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004499 if (value.isSigned() && value.isNegative())
4500 return IntRange(value.getMinSignedBits(), false);
4501
4502 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004503 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004504
4505 // isNonNegative() just checks the sign bit without considering
4506 // signedness.
4507 return IntRange(value.getActiveBits(), true);
4508}
4509
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004510static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4511 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004512 if (result.isInt())
4513 return GetValueRange(C, result.getInt(), MaxWidth);
4514
4515 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004516 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4517 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4518 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4519 R = IntRange::join(R, El);
4520 }
John McCall70aa5392010-01-06 05:24:50 +00004521 return R;
4522 }
4523
4524 if (result.isComplexInt()) {
4525 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4526 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4527 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004528 }
4529
4530 // This can happen with lossless casts to intptr_t of "based" lvalues.
4531 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004532 // FIXME: The only reason we need to pass the type in here is to get
4533 // the sign right on this one case. It would be nice if APValue
4534 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004535 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004536 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004537}
John McCall70aa5392010-01-06 05:24:50 +00004538
Eli Friedmane6d33952013-07-08 20:20:06 +00004539static QualType GetExprType(Expr *E) {
4540 QualType Ty = E->getType();
4541 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4542 Ty = AtomicRHS->getValueType();
4543 return Ty;
4544}
4545
John McCall70aa5392010-01-06 05:24:50 +00004546/// Pseudo-evaluate the given integer expression, estimating the
4547/// range of values it might take.
4548///
4549/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004550static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004551 E = E->IgnoreParens();
4552
4553 // Try a full evaluation first.
4554 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004555 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004556 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004557
4558 // I think we only want to look through implicit casts here; if the
4559 // user has an explicit widening cast, we should treat the value as
4560 // being of the new, wider type.
4561 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004562 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004563 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4564
Eli Friedmane6d33952013-07-08 20:20:06 +00004565 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00004566
John McCalle3027922010-08-25 11:45:40 +00004567 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00004568
John McCall70aa5392010-01-06 05:24:50 +00004569 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00004570 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00004571 return OutputTypeRange;
4572
4573 IntRange SubRange
4574 = GetExprRange(C, CE->getSubExpr(),
4575 std::min(MaxWidth, OutputTypeRange.Width));
4576
4577 // Bail out if the subexpr's range is as wide as the cast type.
4578 if (SubRange.Width >= OutputTypeRange.Width)
4579 return OutputTypeRange;
4580
4581 // Otherwise, we take the smaller width, and we're non-negative if
4582 // either the output type or the subexpr is.
4583 return IntRange(SubRange.Width,
4584 SubRange.NonNegative || OutputTypeRange.NonNegative);
4585 }
4586
4587 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4588 // If we can fold the condition, just take that operand.
4589 bool CondResult;
4590 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4591 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4592 : CO->getFalseExpr(),
4593 MaxWidth);
4594
4595 // Otherwise, conservatively merge.
4596 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4597 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4598 return IntRange::join(L, R);
4599 }
4600
4601 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4602 switch (BO->getOpcode()) {
4603
4604 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00004605 case BO_LAnd:
4606 case BO_LOr:
4607 case BO_LT:
4608 case BO_GT:
4609 case BO_LE:
4610 case BO_GE:
4611 case BO_EQ:
4612 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00004613 return IntRange::forBoolType();
4614
John McCallc3688382011-07-13 06:35:24 +00004615 // The type of the assignments is the type of the LHS, so the RHS
4616 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00004617 case BO_MulAssign:
4618 case BO_DivAssign:
4619 case BO_RemAssign:
4620 case BO_AddAssign:
4621 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00004622 case BO_XorAssign:
4623 case BO_OrAssign:
4624 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00004625 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00004626
John McCallc3688382011-07-13 06:35:24 +00004627 // Simple assignments just pass through the RHS, which will have
4628 // been coerced to the LHS type.
4629 case BO_Assign:
4630 // TODO: bitfields?
4631 return GetExprRange(C, BO->getRHS(), MaxWidth);
4632
John McCall70aa5392010-01-06 05:24:50 +00004633 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004634 case BO_PtrMemD:
4635 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00004636 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004637
John McCall2ce81ad2010-01-06 22:07:33 +00004638 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00004639 case BO_And:
4640 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00004641 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4642 GetExprRange(C, BO->getRHS(), MaxWidth));
4643
John McCall70aa5392010-01-06 05:24:50 +00004644 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00004645 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00004646 // ...except that we want to treat '1 << (blah)' as logically
4647 // positive. It's an important idiom.
4648 if (IntegerLiteral *I
4649 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4650 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004651 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00004652 return IntRange(R.Width, /*NonNegative*/ true);
4653 }
4654 }
4655 // fallthrough
4656
John McCalle3027922010-08-25 11:45:40 +00004657 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00004658 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004659
John McCall2ce81ad2010-01-06 22:07:33 +00004660 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00004661 case BO_Shr:
4662 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00004663 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4664
4665 // If the shift amount is a positive constant, drop the width by
4666 // that much.
4667 llvm::APSInt shift;
4668 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4669 shift.isNonNegative()) {
4670 unsigned zext = shift.getZExtValue();
4671 if (zext >= L.Width)
4672 L.Width = (L.NonNegative ? 0 : 1);
4673 else
4674 L.Width -= zext;
4675 }
4676
4677 return L;
4678 }
4679
4680 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00004681 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00004682 return GetExprRange(C, BO->getRHS(), MaxWidth);
4683
John McCall2ce81ad2010-01-06 22:07:33 +00004684 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00004685 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00004686 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00004687 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004688 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004689
John McCall51431812011-07-14 22:39:48 +00004690 // The width of a division result is mostly determined by the size
4691 // of the LHS.
4692 case BO_Div: {
4693 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004694 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004695 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4696
4697 // If the divisor is constant, use that.
4698 llvm::APSInt divisor;
4699 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4700 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4701 if (log2 >= L.Width)
4702 L.Width = (L.NonNegative ? 0 : 1);
4703 else
4704 L.Width = std::min(L.Width - log2, MaxWidth);
4705 return L;
4706 }
4707
4708 // Otherwise, just use the LHS's width.
4709 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4710 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4711 }
4712
4713 // The result of a remainder can't be larger than the result of
4714 // either side.
4715 case BO_Rem: {
4716 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004717 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004718 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4719 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4720
4721 IntRange meet = IntRange::meet(L, R);
4722 meet.Width = std::min(meet.Width, MaxWidth);
4723 return meet;
4724 }
4725
4726 // The default behavior is okay for these.
4727 case BO_Mul:
4728 case BO_Add:
4729 case BO_Xor:
4730 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00004731 break;
4732 }
4733
John McCall51431812011-07-14 22:39:48 +00004734 // The default case is to treat the operation as if it were closed
4735 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00004736 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4737 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4738 return IntRange::join(L, R);
4739 }
4740
4741 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4742 switch (UO->getOpcode()) {
4743 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00004744 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00004745 return IntRange::forBoolType();
4746
4747 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004748 case UO_Deref:
4749 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00004750 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004751
4752 default:
4753 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4754 }
4755 }
4756
Ted Kremeneka553fbf2013-10-14 18:55:27 +00004757 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4758 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4759
John McCalld25db7e2013-05-06 21:39:12 +00004760 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00004761 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00004762 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00004763
Eli Friedmane6d33952013-07-08 20:20:06 +00004764 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004765}
John McCall263a48b2010-01-04 23:31:57 +00004766
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004767static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004768 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00004769}
4770
John McCall263a48b2010-01-04 23:31:57 +00004771/// Checks whether the given value, which currently has the given
4772/// source semantics, has the same value when coerced through the
4773/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004774static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4775 const llvm::fltSemantics &Src,
4776 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004777 llvm::APFloat truncated = value;
4778
4779 bool ignored;
4780 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4781 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4782
4783 return truncated.bitwiseIsEqual(value);
4784}
4785
4786/// Checks whether the given value, which currently has the given
4787/// source semantics, has the same value when coerced through the
4788/// target semantics.
4789///
4790/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004791static bool IsSameFloatAfterCast(const APValue &value,
4792 const llvm::fltSemantics &Src,
4793 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004794 if (value.isFloat())
4795 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4796
4797 if (value.isVector()) {
4798 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4799 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4800 return false;
4801 return true;
4802 }
4803
4804 assert(value.isComplexFloat());
4805 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4806 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4807}
4808
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004809static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004810
Ted Kremenek6274be42010-09-23 21:43:44 +00004811static bool IsZero(Sema &S, Expr *E) {
4812 // Suppress cases where we are comparing against an enum constant.
4813 if (const DeclRefExpr *DR =
4814 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4815 if (isa<EnumConstantDecl>(DR->getDecl()))
4816 return false;
4817
4818 // Suppress cases where the '0' value is expanded from a macro.
4819 if (E->getLocStart().isMacroID())
4820 return false;
4821
John McCallcc7e5bf2010-05-06 08:58:33 +00004822 llvm::APSInt Value;
4823 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4824}
4825
John McCall2551c1b2010-10-06 00:25:24 +00004826static bool HasEnumType(Expr *E) {
4827 // Strip off implicit integral promotions.
4828 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004829 if (ICE->getCastKind() != CK_IntegralCast &&
4830 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00004831 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004832 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00004833 }
4834
4835 return E->getType()->isEnumeralType();
4836}
4837
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004838static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00004839 // Disable warning in template instantiations.
4840 if (!S.ActiveTemplateInstantiations.empty())
4841 return;
4842
John McCalle3027922010-08-25 11:45:40 +00004843 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00004844 if (E->isValueDependent())
4845 return;
4846
John McCalle3027922010-08-25 11:45:40 +00004847 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004848 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004849 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004850 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004851 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004852 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004853 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004854 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004855 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004856 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004857 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004858 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004859 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004860 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004861 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004862 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4863 }
4864}
4865
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004866static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004867 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004868 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004869 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00004870 // Disable warning in template instantiations.
4871 if (!S.ActiveTemplateInstantiations.empty())
4872 return;
4873
Richard Trieu560910c2012-11-14 22:50:24 +00004874 // 0 values are handled later by CheckTrivialUnsignedComparison().
4875 if (Value == 0)
4876 return;
4877
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004878 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004879 QualType OtherT = Other->getType();
4880 QualType ConstantT = Constant->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00004881 QualType CommonT = E->getLHS()->getType();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004882 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004883 return;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004884 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004885 && "comparison with non-integer type");
Richard Trieu560910c2012-11-14 22:50:24 +00004886
4887 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu560910c2012-11-14 22:50:24 +00004888 bool CommonSigned = CommonT->isSignedIntegerType();
4889
4890 bool EqualityOnly = false;
4891
4892 // TODO: Investigate using GetExprRange() to get tighter bounds on
4893 // on the bit ranges.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004894 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu560910c2012-11-14 22:50:24 +00004895 unsigned OtherWidth = OtherRange.Width;
4896
4897 if (CommonSigned) {
4898 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedman5ac98752012-11-30 23:09:29 +00004899 if (!OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004900 // Check that the constant is representable in type OtherT.
4901 if (ConstantSigned) {
4902 if (OtherWidth >= Value.getMinSignedBits())
4903 return;
4904 } else { // !ConstantSigned
4905 if (OtherWidth >= Value.getActiveBits() + 1)
4906 return;
4907 }
4908 } else { // !OtherSigned
4909 // Check that the constant is representable in type OtherT.
4910 // Negative values are out of range.
4911 if (ConstantSigned) {
4912 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4913 return;
4914 } else { // !ConstantSigned
4915 if (OtherWidth >= Value.getActiveBits())
4916 return;
4917 }
4918 }
4919 } else { // !CommonSigned
Eli Friedman5ac98752012-11-30 23:09:29 +00004920 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004921 if (OtherWidth >= Value.getActiveBits())
4922 return;
Eli Friedman5ac98752012-11-30 23:09:29 +00004923 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu560910c2012-11-14 22:50:24 +00004924 // Check to see if the constant is representable in OtherT.
4925 if (OtherWidth > Value.getActiveBits())
4926 return;
4927 // Check to see if the constant is equivalent to a negative value
4928 // cast to CommonT.
4929 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu03c3a2f2012-11-15 03:43:50 +00004930 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu560910c2012-11-14 22:50:24 +00004931 return;
4932 // The constant value rests between values that OtherT can represent after
4933 // conversion. Relational comparison still works, but equality
4934 // comparisons will be tautological.
4935 EqualityOnly = true;
4936 } else { // OtherSigned && ConstantSigned
4937 assert(0 && "Two signed types converted to unsigned types.");
4938 }
4939 }
4940
4941 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4942
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004943 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00004944 if (op == BO_EQ || op == BO_NE) {
4945 IsTrue = op == BO_NE;
4946 } else if (EqualityOnly) {
4947 return;
4948 } else if (RhsConstant) {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004949 if (op == BO_GT || op == BO_GE)
Richard Trieu560910c2012-11-14 22:50:24 +00004950 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004951 else // op == BO_LT || op == BO_LE
Richard Trieu560910c2012-11-14 22:50:24 +00004952 IsTrue = PositiveConstant;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004953 } else {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004954 if (op == BO_LT || op == BO_LE)
Richard Trieu560910c2012-11-14 22:50:24 +00004955 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004956 else // op == BO_GT || op == BO_GE
Richard Trieu560910c2012-11-14 22:50:24 +00004957 IsTrue = PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004958 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00004959
4960 // If this is a comparison to an enum constant, include that
4961 // constant in the diagnostic.
4962 const EnumConstantDecl *ED = 0;
4963 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4964 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4965
4966 SmallString<64> PrettySourceValue;
4967 llvm::raw_svector_ostream OS(PrettySourceValue);
4968 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00004969 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00004970 else
4971 OS << Value;
4972
Richard Trieuc38786b2014-01-10 04:38:09 +00004973 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4974 S.PDiag(diag::warn_out_of_range_compare)
4975 << OS.str() << OtherT << IsTrue
4976 << E->getLHS()->getSourceRange()
4977 << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004978}
4979
John McCallcc7e5bf2010-05-06 08:58:33 +00004980/// Analyze the operands of the given comparison. Implements the
4981/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004982static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00004983 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4984 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00004985}
John McCall263a48b2010-01-04 23:31:57 +00004986
John McCallca01b222010-01-04 23:21:16 +00004987/// \brief Implements -Wsign-compare.
4988///
Richard Trieu82402a02011-09-15 21:56:47 +00004989/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004990static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004991 // The type the comparison is being performed in.
4992 QualType T = E->getLHS()->getType();
4993 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4994 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00004995 if (E->isValueDependent())
4996 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00004997
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004998 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4999 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005000
5001 bool IsComparisonConstant = false;
5002
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005003 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005004 // of 'true' or 'false'.
5005 if (T->isIntegralType(S.Context)) {
5006 llvm::APSInt RHSValue;
5007 bool IsRHSIntegralLiteral =
5008 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5009 llvm::APSInt LHSValue;
5010 bool IsLHSIntegralLiteral =
5011 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5012 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5013 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5014 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5015 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5016 else
5017 IsComparisonConstant =
5018 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005019 } else if (!T->hasUnsignedIntegerRepresentation())
5020 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005021
John McCallcc7e5bf2010-05-06 08:58:33 +00005022 // We don't do anything special if this isn't an unsigned integral
5023 // comparison: we're only interested in integral comparisons, and
5024 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005025 //
5026 // We also don't care about value-dependent expressions or expressions
5027 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005028 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005029 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005030
John McCallcc7e5bf2010-05-06 08:58:33 +00005031 // Check to see if one of the (unmodified) operands is of different
5032 // signedness.
5033 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005034 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5035 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005036 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005037 signedOperand = LHS;
5038 unsignedOperand = RHS;
5039 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5040 signedOperand = RHS;
5041 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005042 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005043 CheckTrivialUnsignedComparison(S, E);
5044 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005045 }
5046
John McCallcc7e5bf2010-05-06 08:58:33 +00005047 // Otherwise, calculate the effective range of the signed operand.
5048 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005049
John McCallcc7e5bf2010-05-06 08:58:33 +00005050 // Go ahead and analyze implicit conversions in the operands. Note
5051 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005052 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5053 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005054
John McCallcc7e5bf2010-05-06 08:58:33 +00005055 // If the signed range is non-negative, -Wsign-compare won't fire,
5056 // but we should still check for comparisons which are always true
5057 // or false.
5058 if (signedRange.NonNegative)
5059 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005060
5061 // For (in)equality comparisons, if the unsigned operand is a
5062 // constant which cannot collide with a overflowed signed operand,
5063 // then reinterpreting the signed operand as unsigned will not
5064 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005065 if (E->isEqualityOp()) {
5066 unsigned comparisonWidth = S.Context.getIntWidth(T);
5067 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005068
John McCallcc7e5bf2010-05-06 08:58:33 +00005069 // We should never be unable to prove that the unsigned operand is
5070 // non-negative.
5071 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5072
5073 if (unsignedRange.Width < comparisonWidth)
5074 return;
5075 }
5076
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005077 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5078 S.PDiag(diag::warn_mixed_sign_comparison)
5079 << LHS->getType() << RHS->getType()
5080 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005081}
5082
John McCall1f425642010-11-11 03:21:53 +00005083/// Analyzes an attempt to assign the given value to a bitfield.
5084///
5085/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005086static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5087 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005088 assert(Bitfield->isBitField());
5089 if (Bitfield->isInvalidDecl())
5090 return false;
5091
John McCalldeebbcf2010-11-11 05:33:51 +00005092 // White-list bool bitfields.
5093 if (Bitfield->getType()->isBooleanType())
5094 return false;
5095
Douglas Gregor789adec2011-02-04 13:09:01 +00005096 // Ignore value- or type-dependent expressions.
5097 if (Bitfield->getBitWidth()->isValueDependent() ||
5098 Bitfield->getBitWidth()->isTypeDependent() ||
5099 Init->isValueDependent() ||
5100 Init->isTypeDependent())
5101 return false;
5102
John McCall1f425642010-11-11 03:21:53 +00005103 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5104
Richard Smith5fab0c92011-12-28 19:48:30 +00005105 llvm::APSInt Value;
5106 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005107 return false;
5108
John McCall1f425642010-11-11 03:21:53 +00005109 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005110 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005111
5112 if (OriginalWidth <= FieldWidth)
5113 return false;
5114
Eli Friedmanc267a322012-01-26 23:11:39 +00005115 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005116 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005117 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005118
Eli Friedmanc267a322012-01-26 23:11:39 +00005119 // Check whether the stored value is equal to the original value.
5120 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005121 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005122 return false;
5123
Eli Friedmanc267a322012-01-26 23:11:39 +00005124 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005125 // therefore don't strictly fit into a signed bitfield of width 1.
5126 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005127 return false;
5128
John McCall1f425642010-11-11 03:21:53 +00005129 std::string PrettyValue = Value.toString(10);
5130 std::string PrettyTrunc = TruncatedValue.toString(10);
5131
5132 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5133 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5134 << Init->getSourceRange();
5135
5136 return true;
5137}
5138
John McCalld2a53122010-11-09 23:24:47 +00005139/// Analyze the given simple or compound assignment for warning-worthy
5140/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005141static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005142 // Just recurse on the LHS.
5143 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5144
5145 // We want to recurse on the RHS as normal unless we're assigning to
5146 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005147 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005148 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005149 E->getOperatorLoc())) {
5150 // Recurse, ignoring any implicit conversions on the RHS.
5151 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5152 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005153 }
5154 }
5155
5156 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5157}
5158
John McCall263a48b2010-01-04 23:31:57 +00005159/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005160static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005161 SourceLocation CContext, unsigned diag,
5162 bool pruneControlFlow = false) {
5163 if (pruneControlFlow) {
5164 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5165 S.PDiag(diag)
5166 << SourceType << T << E->getSourceRange()
5167 << SourceRange(CContext));
5168 return;
5169 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005170 S.Diag(E->getExprLoc(), diag)
5171 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5172}
5173
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005174/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005175static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005176 SourceLocation CContext, unsigned diag,
5177 bool pruneControlFlow = false) {
5178 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005179}
5180
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005181/// Diagnose an implicit cast from a literal expression. Does not warn when the
5182/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005183void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5184 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005185 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005186 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005187 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005188 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5189 T->hasUnsignedIntegerRepresentation());
5190 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005191 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005192 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005193 return;
5194
Eli Friedman07185912013-08-29 23:44:43 +00005195 // FIXME: Force the precision of the source value down so we don't print
5196 // digits which are usually useless (we don't really care here if we
5197 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5198 // would automatically print the shortest representation, but it's a bit
5199 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005200 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005201 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5202 precision = (precision * 59 + 195) / 196;
5203 Value.toString(PrettySourceValue, precision);
5204
David Blaikie9b88cc02012-05-15 17:18:27 +00005205 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005206 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5207 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5208 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005209 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005210
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005211 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005212 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5213 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005214}
5215
John McCall18a2c2c2010-11-09 22:22:12 +00005216std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5217 if (!Range.Width) return "0";
5218
5219 llvm::APSInt ValueInRange = Value;
5220 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005221 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005222 return ValueInRange.toString(10);
5223}
5224
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005225static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5226 if (!isa<ImplicitCastExpr>(Ex))
5227 return false;
5228
5229 Expr *InnerE = Ex->IgnoreParenImpCasts();
5230 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5231 const Type *Source =
5232 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5233 if (Target->isDependentType())
5234 return false;
5235
5236 const BuiltinType *FloatCandidateBT =
5237 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5238 const Type *BoolCandidateType = ToBool ? Target : Source;
5239
5240 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5241 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5242}
5243
5244void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5245 SourceLocation CC) {
5246 unsigned NumArgs = TheCall->getNumArgs();
5247 for (unsigned i = 0; i < NumArgs; ++i) {
5248 Expr *CurrA = TheCall->getArg(i);
5249 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5250 continue;
5251
5252 bool IsSwapped = ((i > 0) &&
5253 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5254 IsSwapped |= ((i < (NumArgs - 1)) &&
5255 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5256 if (IsSwapped) {
5257 // Warn on this floating-point to bool conversion.
5258 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5259 CurrA->getType(), CC,
5260 diag::warn_impcast_floating_point_to_bool);
5261 }
5262 }
5263}
5264
John McCallcc7e5bf2010-05-06 08:58:33 +00005265void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005266 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005267 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005268
John McCallcc7e5bf2010-05-06 08:58:33 +00005269 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5270 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5271 if (Source == Target) return;
5272 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005273
Chandler Carruthc22845a2011-07-26 05:40:03 +00005274 // If the conversion context location is invalid don't complain. We also
5275 // don't want to emit a warning if the issue occurs from the expansion of
5276 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5277 // delay this check as long as possible. Once we detect we are in that
5278 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005279 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005280 return;
5281
Richard Trieu021baa32011-09-23 20:10:00 +00005282 // Diagnose implicit casts to bool.
5283 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5284 if (isa<StringLiteral>(E))
5285 // Warn on string literal to bool. Checks for string literals in logical
Nico Weber0e6daef2013-12-26 23:38:39 +00005286 // expressions, for instances, assert(0 && "error here"), are prevented
Richard Trieu021baa32011-09-23 20:10:00 +00005287 // by a check in AnalyzeImplicitConversions().
5288 return DiagnoseImpCast(S, E, T, CC,
5289 diag::warn_impcast_string_literal_to_bool);
Lang Hamesdf5c1212011-12-05 20:49:50 +00005290 if (Source->isFunctionType()) {
5291 // Warn on function to bool. Checks free functions and static member
5292 // functions. Weakly imported functions are excluded from the check,
5293 // since it's common to test their value to check whether the linker
5294 // found a definition for them.
5295 ValueDecl *D = 0;
5296 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5297 D = R->getDecl();
5298 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5299 D = M->getMemberDecl();
5300 }
5301
5302 if (D && !D->isWeak()) {
Richard Trieu5f623222011-12-06 04:48:01 +00005303 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5304 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5305 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie10eb4b62011-12-09 21:42:37 +00005306 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5307 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5308 QualType ReturnType;
5309 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiee5323aa2013-06-21 23:54:45 +00005310 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie10eb4b62011-12-09 21:42:37 +00005311 if (!ReturnType.isNull()
5312 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5313 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5314 << FixItHint::CreateInsertion(
5315 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu5f623222011-12-06 04:48:01 +00005316 return;
5317 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00005318 }
5319 }
Richard Trieu021baa32011-09-23 20:10:00 +00005320 }
John McCall263a48b2010-01-04 23:31:57 +00005321
5322 // Strip vector types.
5323 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005324 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005325 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005326 return;
John McCallacf0ee52010-10-08 02:01:28 +00005327 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005328 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005329
5330 // If the vector cast is cast between two vectors of the same size, it is
5331 // a bitcast, not a conversion.
5332 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5333 return;
John McCall263a48b2010-01-04 23:31:57 +00005334
5335 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5336 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5337 }
5338
5339 // Strip complex types.
5340 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005341 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005342 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005343 return;
5344
John McCallacf0ee52010-10-08 02:01:28 +00005345 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005346 }
John McCall263a48b2010-01-04 23:31:57 +00005347
5348 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5349 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5350 }
5351
5352 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5353 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5354
5355 // If the source is floating point...
5356 if (SourceBT && SourceBT->isFloatingPoint()) {
5357 // ...and the target is floating point...
5358 if (TargetBT && TargetBT->isFloatingPoint()) {
5359 // ...then warn if we're dropping FP rank.
5360
5361 // Builtin FP kinds are ordered by increasing FP rank.
5362 if (SourceBT->getKind() > TargetBT->getKind()) {
5363 // Don't warn about float constants that are precisely
5364 // representable in the target type.
5365 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005366 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005367 // Value might be a float, a float vector, or a float complex.
5368 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005369 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5370 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005371 return;
5372 }
5373
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005374 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005375 return;
5376
John McCallacf0ee52010-10-08 02:01:28 +00005377 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005378 }
5379 return;
5380 }
5381
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005382 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005383 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005384 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005385 return;
5386
Chandler Carruth22c7a792011-02-17 11:05:49 +00005387 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005388 // We also want to warn on, e.g., "int i = -1.234"
5389 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5390 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5391 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5392
Chandler Carruth016ef402011-04-10 08:36:24 +00005393 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5394 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005395 } else {
5396 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5397 }
5398 }
John McCall263a48b2010-01-04 23:31:57 +00005399
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005400 // If the target is bool, warn if expr is a function or method call.
5401 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5402 isa<CallExpr>(E)) {
5403 // Check last argument of function call to see if it is an
5404 // implicit cast from a type matching the type the result
5405 // is being cast to.
5406 CallExpr *CEx = cast<CallExpr>(E);
5407 unsigned NumArgs = CEx->getNumArgs();
5408 if (NumArgs > 0) {
5409 Expr *LastA = CEx->getArg(NumArgs - 1);
5410 Expr *InnerE = LastA->IgnoreParenImpCasts();
5411 const Type *InnerType =
5412 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5413 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5414 // Warn on this floating-point to bool conversion
5415 DiagnoseImpCast(S, E, T, CC,
5416 diag::warn_impcast_floating_point_to_bool);
5417 }
5418 }
5419 }
John McCall263a48b2010-01-04 23:31:57 +00005420 return;
5421 }
5422
Richard Trieubeaf3452011-05-29 19:59:02 +00005423 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005424 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005425 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005426 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005427 SourceLocation Loc = E->getSourceRange().getBegin();
5428 if (Loc.isMacroID())
5429 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005430 if (!Loc.isMacroID() || CC.isMacroID())
5431 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5432 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005433 << FixItHint::CreateReplacement(Loc,
5434 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005435 }
5436
David Blaikie9366d2b2012-06-19 21:19:06 +00005437 if (!Source->isIntegerType() || !Target->isIntegerType())
5438 return;
5439
David Blaikie7555b6a2012-05-15 16:56:36 +00005440 // TODO: remove this early return once the false positives for constant->bool
5441 // in templates, macros, etc, are reduced or removed.
5442 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5443 return;
5444
John McCallcc7e5bf2010-05-06 08:58:33 +00005445 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005446 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005447
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005448 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005449 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005450 // TODO: this should happen for bitfield stores, too.
5451 llvm::APSInt Value(32);
5452 if (E->isIntegerConstantExpr(Value, S.Context)) {
5453 if (S.SourceMgr.isInSystemMacro(CC))
5454 return;
5455
John McCall18a2c2c2010-11-09 22:22:12 +00005456 std::string PrettySourceValue = Value.toString(10);
5457 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005458
Ted Kremenek33ba9952011-10-22 02:37:33 +00005459 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5460 S.PDiag(diag::warn_impcast_integer_precision_constant)
5461 << PrettySourceValue << PrettyTargetValue
5462 << E->getType() << T << E->getSourceRange()
5463 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005464 return;
5465 }
5466
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005467 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5468 if (S.SourceMgr.isInSystemMacro(CC))
5469 return;
5470
David Blaikie9455da02012-04-12 22:40:54 +00005471 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005472 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5473 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005474 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005475 }
5476
5477 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5478 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5479 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005480
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005481 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005482 return;
5483
John McCallcc7e5bf2010-05-06 08:58:33 +00005484 unsigned DiagID = diag::warn_impcast_integer_sign;
5485
5486 // Traditionally, gcc has warned about this under -Wsign-compare.
5487 // We also want to warn about it in -Wconversion.
5488 // So if -Wconversion is off, use a completely identical diagnostic
5489 // in the sign-compare group.
5490 // The conditional-checking code will
5491 if (ICContext) {
5492 DiagID = diag::warn_impcast_integer_sign_conditional;
5493 *ICContext = true;
5494 }
5495
John McCallacf0ee52010-10-08 02:01:28 +00005496 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005497 }
5498
Douglas Gregora78f1932011-02-22 02:45:07 +00005499 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005500 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5501 // type, to give us better diagnostics.
5502 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005503 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005504 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5505 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5506 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5507 SourceType = S.Context.getTypeDeclType(Enum);
5508 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5509 }
5510 }
5511
Douglas Gregora78f1932011-02-22 02:45:07 +00005512 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5513 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00005514 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5515 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005516 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005517 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005518 return;
5519
Douglas Gregor364f7db2011-03-12 00:14:31 +00005520 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00005521 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005522 }
Douglas Gregora78f1932011-02-22 02:45:07 +00005523
John McCall263a48b2010-01-04 23:31:57 +00005524 return;
5525}
5526
David Blaikie18e9ac72012-05-15 21:57:38 +00005527void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5528 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005529
5530void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00005531 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005532 E = E->IgnoreParenImpCasts();
5533
5534 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00005535 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005536
John McCallacf0ee52010-10-08 02:01:28 +00005537 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005538 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005539 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00005540 return;
5541}
5542
David Blaikie18e9ac72012-05-15 21:57:38 +00005543void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5544 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00005545 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005546
5547 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00005548 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5549 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005550
5551 // If -Wconversion would have warned about either of the candidates
5552 // for a signedness conversion to the context type...
5553 if (!Suspicious) return;
5554
5555 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005556 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5557 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00005558 return;
5559
John McCallcc7e5bf2010-05-06 08:58:33 +00005560 // ...then check whether it would have warned about either of the
5561 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00005562 if (E->getType() == T) return;
5563
5564 Suspicious = false;
5565 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5566 E->getType(), CC, &Suspicious);
5567 if (!Suspicious)
5568 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00005569 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005570}
5571
5572/// AnalyzeImplicitConversions - Find and report any interesting
5573/// implicit conversions in the given expression. There are a couple
5574/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005575void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005576 QualType T = OrigE->getType();
5577 Expr *E = OrigE->IgnoreParenImpCasts();
5578
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00005579 if (E->isTypeDependent() || E->isValueDependent())
5580 return;
5581
John McCallcc7e5bf2010-05-06 08:58:33 +00005582 // For conditional operators, we analyze the arguments as if they
5583 // were being fed directly into the output.
5584 if (isa<ConditionalOperator>(E)) {
5585 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00005586 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005587 return;
5588 }
5589
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005590 // Check implicit argument conversions for function calls.
5591 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5592 CheckImplicitArgumentConversions(S, Call, CC);
5593
John McCallcc7e5bf2010-05-06 08:58:33 +00005594 // Go ahead and check any implicit conversions we might have skipped.
5595 // The non-canonical typecheck is just an optimization;
5596 // CheckImplicitConversion will filter out dead implicit conversions.
5597 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005598 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005599
5600 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005601
5602 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005603 if (POE->getResultExpr())
5604 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005605 }
5606
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005607 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5608 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5609
John McCallcc7e5bf2010-05-06 08:58:33 +00005610 // Skip past explicit casts.
5611 if (isa<ExplicitCastExpr>(E)) {
5612 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00005613 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005614 }
5615
John McCalld2a53122010-11-09 23:24:47 +00005616 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5617 // Do a somewhat different check with comparison operators.
5618 if (BO->isComparisonOp())
5619 return AnalyzeComparison(S, BO);
5620
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005621 // And with simple assignments.
5622 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00005623 return AnalyzeAssignment(S, BO);
5624 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005625
5626 // These break the otherwise-useful invariant below. Fortunately,
5627 // we don't really need to recurse into them, because any internal
5628 // expressions should have been analyzed already when they were
5629 // built into statements.
5630 if (isa<StmtExpr>(E)) return;
5631
5632 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00005633 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00005634
5635 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00005636 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00005637 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5638 bool IsLogicalOperator = BO && BO->isLogicalOp();
5639 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00005640 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00005641 if (!ChildExpr)
5642 continue;
5643
Richard Trieu021baa32011-09-23 20:10:00 +00005644 if (IsLogicalOperator &&
5645 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5646 // Ignore checking string literals that are in logical operators.
5647 continue;
5648 AnalyzeImplicitConversions(S, ChildExpr, CC);
5649 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005650}
5651
5652} // end anonymous namespace
5653
5654/// Diagnoses "dangerous" implicit conversions within the given
5655/// expression (which is a full expression). Implements -Wconversion
5656/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005657///
5658/// \param CC the "context" location of the implicit conversion, i.e.
5659/// the most location of the syntactic entity requiring the implicit
5660/// conversion
5661void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005662 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00005663 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00005664 return;
5665
5666 // Don't diagnose for value- or type-dependent expressions.
5667 if (E->isTypeDependent() || E->isValueDependent())
5668 return;
5669
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005670 // Check for array bounds violations in cases where the check isn't triggered
5671 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5672 // ArraySubscriptExpr is on the RHS of a variable initialization.
5673 CheckArrayAccess(E);
5674
John McCallacf0ee52010-10-08 02:01:28 +00005675 // This is not the right CC for (e.g.) a variable initialization.
5676 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005677}
5678
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005679/// Diagnose when expression is an integer constant expression and its evaluation
5680/// results in integer overflow
5681void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00005682 if (isa<BinaryOperator>(E->IgnoreParens()))
5683 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005684}
5685
Richard Smithc406cb72013-01-17 01:17:56 +00005686namespace {
5687/// \brief Visitor for expressions which looks for unsequenced operations on the
5688/// same object.
5689class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00005690 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5691
Richard Smithc406cb72013-01-17 01:17:56 +00005692 /// \brief A tree of sequenced regions within an expression. Two regions are
5693 /// unsequenced if one is an ancestor or a descendent of the other. When we
5694 /// finish processing an expression with sequencing, such as a comma
5695 /// expression, we fold its tree nodes into its parent, since they are
5696 /// unsequenced with respect to nodes we will visit later.
5697 class SequenceTree {
5698 struct Value {
5699 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5700 unsigned Parent : 31;
5701 bool Merged : 1;
5702 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005703 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00005704
5705 public:
5706 /// \brief A region within an expression which may be sequenced with respect
5707 /// to some other region.
5708 class Seq {
5709 explicit Seq(unsigned N) : Index(N) {}
5710 unsigned Index;
5711 friend class SequenceTree;
5712 public:
5713 Seq() : Index(0) {}
5714 };
5715
5716 SequenceTree() { Values.push_back(Value(0)); }
5717 Seq root() const { return Seq(0); }
5718
5719 /// \brief Create a new sequence of operations, which is an unsequenced
5720 /// subset of \p Parent. This sequence of operations is sequenced with
5721 /// respect to other children of \p Parent.
5722 Seq allocate(Seq Parent) {
5723 Values.push_back(Value(Parent.Index));
5724 return Seq(Values.size() - 1);
5725 }
5726
5727 /// \brief Merge a sequence of operations into its parent.
5728 void merge(Seq S) {
5729 Values[S.Index].Merged = true;
5730 }
5731
5732 /// \brief Determine whether two operations are unsequenced. This operation
5733 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5734 /// should have been merged into its parent as appropriate.
5735 bool isUnsequenced(Seq Cur, Seq Old) {
5736 unsigned C = representative(Cur.Index);
5737 unsigned Target = representative(Old.Index);
5738 while (C >= Target) {
5739 if (C == Target)
5740 return true;
5741 C = Values[C].Parent;
5742 }
5743 return false;
5744 }
5745
5746 private:
5747 /// \brief Pick a representative for a sequence.
5748 unsigned representative(unsigned K) {
5749 if (Values[K].Merged)
5750 // Perform path compression as we go.
5751 return Values[K].Parent = representative(Values[K].Parent);
5752 return K;
5753 }
5754 };
5755
5756 /// An object for which we can track unsequenced uses.
5757 typedef NamedDecl *Object;
5758
5759 /// Different flavors of object usage which we track. We only track the
5760 /// least-sequenced usage of each kind.
5761 enum UsageKind {
5762 /// A read of an object. Multiple unsequenced reads are OK.
5763 UK_Use,
5764 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00005765 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00005766 UK_ModAsValue,
5767 /// A modification of an object which is not sequenced before the value
5768 /// computation of the expression, such as n++.
5769 UK_ModAsSideEffect,
5770
5771 UK_Count = UK_ModAsSideEffect + 1
5772 };
5773
5774 struct Usage {
5775 Usage() : Use(0), Seq() {}
5776 Expr *Use;
5777 SequenceTree::Seq Seq;
5778 };
5779
5780 struct UsageInfo {
5781 UsageInfo() : Diagnosed(false) {}
5782 Usage Uses[UK_Count];
5783 /// Have we issued a diagnostic for this variable already?
5784 bool Diagnosed;
5785 };
5786 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5787
5788 Sema &SemaRef;
5789 /// Sequenced regions within the expression.
5790 SequenceTree Tree;
5791 /// Declaration modifications and references which we have seen.
5792 UsageInfoMap UsageMap;
5793 /// The region we are currently within.
5794 SequenceTree::Seq Region;
5795 /// Filled in with declarations which were modified as a side-effect
5796 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005797 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00005798 /// Expressions to check later. We defer checking these to reduce
5799 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005800 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00005801
5802 /// RAII object wrapping the visitation of a sequenced subexpression of an
5803 /// expression. At the end of this process, the side-effects of the evaluation
5804 /// become sequenced with respect to the value computation of the result, so
5805 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5806 /// UK_ModAsValue.
5807 struct SequencedSubexpression {
5808 SequencedSubexpression(SequenceChecker &Self)
5809 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5810 Self.ModAsSideEffect = &ModAsSideEffect;
5811 }
5812 ~SequencedSubexpression() {
5813 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5814 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5815 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5816 Self.addUsage(U, ModAsSideEffect[I].first,
5817 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5818 }
5819 Self.ModAsSideEffect = OldModAsSideEffect;
5820 }
5821
5822 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005823 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5824 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00005825 };
5826
Richard Smith40238f02013-06-20 22:21:56 +00005827 /// RAII object wrapping the visitation of a subexpression which we might
5828 /// choose to evaluate as a constant. If any subexpression is evaluated and
5829 /// found to be non-constant, this allows us to suppress the evaluation of
5830 /// the outer expression.
5831 class EvaluationTracker {
5832 public:
5833 EvaluationTracker(SequenceChecker &Self)
5834 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5835 Self.EvalTracker = this;
5836 }
5837 ~EvaluationTracker() {
5838 Self.EvalTracker = Prev;
5839 if (Prev)
5840 Prev->EvalOK &= EvalOK;
5841 }
5842
5843 bool evaluate(const Expr *E, bool &Result) {
5844 if (!EvalOK || E->isValueDependent())
5845 return false;
5846 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5847 return EvalOK;
5848 }
5849
5850 private:
5851 SequenceChecker &Self;
5852 EvaluationTracker *Prev;
5853 bool EvalOK;
5854 } *EvalTracker;
5855
Richard Smithc406cb72013-01-17 01:17:56 +00005856 /// \brief Find the object which is produced by the specified expression,
5857 /// if any.
5858 Object getObject(Expr *E, bool Mod) const {
5859 E = E->IgnoreParenCasts();
5860 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5861 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5862 return getObject(UO->getSubExpr(), Mod);
5863 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5864 if (BO->getOpcode() == BO_Comma)
5865 return getObject(BO->getRHS(), Mod);
5866 if (Mod && BO->isAssignmentOp())
5867 return getObject(BO->getLHS(), Mod);
5868 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5869 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5870 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5871 return ME->getMemberDecl();
5872 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5873 // FIXME: If this is a reference, map through to its value.
5874 return DRE->getDecl();
5875 return 0;
5876 }
5877
5878 /// \brief Note that an object was modified or used by an expression.
5879 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5880 Usage &U = UI.Uses[UK];
5881 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5882 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5883 ModAsSideEffect->push_back(std::make_pair(O, U));
5884 U.Use = Ref;
5885 U.Seq = Region;
5886 }
5887 }
5888 /// \brief Check whether a modification or use conflicts with a prior usage.
5889 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5890 bool IsModMod) {
5891 if (UI.Diagnosed)
5892 return;
5893
5894 const Usage &U = UI.Uses[OtherKind];
5895 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5896 return;
5897
5898 Expr *Mod = U.Use;
5899 Expr *ModOrUse = Ref;
5900 if (OtherKind == UK_Use)
5901 std::swap(Mod, ModOrUse);
5902
5903 SemaRef.Diag(Mod->getExprLoc(),
5904 IsModMod ? diag::warn_unsequenced_mod_mod
5905 : diag::warn_unsequenced_mod_use)
5906 << O << SourceRange(ModOrUse->getExprLoc());
5907 UI.Diagnosed = true;
5908 }
5909
5910 void notePreUse(Object O, Expr *Use) {
5911 UsageInfo &U = UsageMap[O];
5912 // Uses conflict with other modifications.
5913 checkUsage(O, U, Use, UK_ModAsValue, false);
5914 }
5915 void notePostUse(Object O, Expr *Use) {
5916 UsageInfo &U = UsageMap[O];
5917 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5918 addUsage(U, O, Use, UK_Use);
5919 }
5920
5921 void notePreMod(Object O, Expr *Mod) {
5922 UsageInfo &U = UsageMap[O];
5923 // Modifications conflict with other modifications and with uses.
5924 checkUsage(O, U, Mod, UK_ModAsValue, true);
5925 checkUsage(O, U, Mod, UK_Use, false);
5926 }
5927 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5928 UsageInfo &U = UsageMap[O];
5929 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5930 addUsage(U, O, Use, UK);
5931 }
5932
5933public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005934 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5935 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5936 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00005937 Visit(E);
5938 }
5939
5940 void VisitStmt(Stmt *S) {
5941 // Skip all statements which aren't expressions for now.
5942 }
5943
5944 void VisitExpr(Expr *E) {
5945 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00005946 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00005947 }
5948
5949 void VisitCastExpr(CastExpr *E) {
5950 Object O = Object();
5951 if (E->getCastKind() == CK_LValueToRValue)
5952 O = getObject(E->getSubExpr(), false);
5953
5954 if (O)
5955 notePreUse(O, E);
5956 VisitExpr(E);
5957 if (O)
5958 notePostUse(O, E);
5959 }
5960
5961 void VisitBinComma(BinaryOperator *BO) {
5962 // C++11 [expr.comma]p1:
5963 // Every value computation and side effect associated with the left
5964 // expression is sequenced before every value computation and side
5965 // effect associated with the right expression.
5966 SequenceTree::Seq LHS = Tree.allocate(Region);
5967 SequenceTree::Seq RHS = Tree.allocate(Region);
5968 SequenceTree::Seq OldRegion = Region;
5969
5970 {
5971 SequencedSubexpression SeqLHS(*this);
5972 Region = LHS;
5973 Visit(BO->getLHS());
5974 }
5975
5976 Region = RHS;
5977 Visit(BO->getRHS());
5978
5979 Region = OldRegion;
5980
5981 // Forget that LHS and RHS are sequenced. They are both unsequenced
5982 // with respect to other stuff.
5983 Tree.merge(LHS);
5984 Tree.merge(RHS);
5985 }
5986
5987 void VisitBinAssign(BinaryOperator *BO) {
5988 // The modification is sequenced after the value computation of the LHS
5989 // and RHS, so check it before inspecting the operands and update the
5990 // map afterwards.
5991 Object O = getObject(BO->getLHS(), true);
5992 if (!O)
5993 return VisitExpr(BO);
5994
5995 notePreMod(O, BO);
5996
5997 // C++11 [expr.ass]p7:
5998 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5999 // only once.
6000 //
6001 // Therefore, for a compound assignment operator, O is considered used
6002 // everywhere except within the evaluation of E1 itself.
6003 if (isa<CompoundAssignOperator>(BO))
6004 notePreUse(O, BO);
6005
6006 Visit(BO->getLHS());
6007
6008 if (isa<CompoundAssignOperator>(BO))
6009 notePostUse(O, BO);
6010
6011 Visit(BO->getRHS());
6012
Richard Smith83e37bee2013-06-26 23:16:51 +00006013 // C++11 [expr.ass]p1:
6014 // the assignment is sequenced [...] before the value computation of the
6015 // assignment expression.
6016 // C11 6.5.16/3 has no such rule.
6017 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6018 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006019 }
6020 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6021 VisitBinAssign(CAO);
6022 }
6023
6024 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6025 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6026 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6027 Object O = getObject(UO->getSubExpr(), true);
6028 if (!O)
6029 return VisitExpr(UO);
6030
6031 notePreMod(O, UO);
6032 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006033 // C++11 [expr.pre.incr]p1:
6034 // the expression ++x is equivalent to x+=1
6035 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6036 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006037 }
6038
6039 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6040 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6041 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6042 Object O = getObject(UO->getSubExpr(), true);
6043 if (!O)
6044 return VisitExpr(UO);
6045
6046 notePreMod(O, UO);
6047 Visit(UO->getSubExpr());
6048 notePostMod(O, UO, UK_ModAsSideEffect);
6049 }
6050
6051 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6052 void VisitBinLOr(BinaryOperator *BO) {
6053 // The side-effects of the LHS of an '&&' are sequenced before the
6054 // value computation of the RHS, and hence before the value computation
6055 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6056 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006057 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006058 {
6059 SequencedSubexpression Sequenced(*this);
6060 Visit(BO->getLHS());
6061 }
6062
6063 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006064 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006065 if (!Result)
6066 Visit(BO->getRHS());
6067 } else {
6068 // Check for unsequenced operations in the RHS, treating it as an
6069 // entirely separate evaluation.
6070 //
6071 // FIXME: If there are operations in the RHS which are unsequenced
6072 // with respect to operations outside the RHS, and those operations
6073 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006074 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006075 }
Richard Smithc406cb72013-01-17 01:17:56 +00006076 }
6077 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006078 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006079 {
6080 SequencedSubexpression Sequenced(*this);
6081 Visit(BO->getLHS());
6082 }
6083
6084 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006085 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006086 if (Result)
6087 Visit(BO->getRHS());
6088 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006089 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006090 }
Richard Smithc406cb72013-01-17 01:17:56 +00006091 }
6092
6093 // Only visit the condition, unless we can be sure which subexpression will
6094 // be chosen.
6095 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006096 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006097 {
6098 SequencedSubexpression Sequenced(*this);
6099 Visit(CO->getCond());
6100 }
Richard Smithc406cb72013-01-17 01:17:56 +00006101
6102 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006103 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006104 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006105 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006106 WorkList.push_back(CO->getTrueExpr());
6107 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006108 }
Richard Smithc406cb72013-01-17 01:17:56 +00006109 }
6110
Richard Smithe3dbfe02013-06-30 10:40:20 +00006111 void VisitCallExpr(CallExpr *CE) {
6112 // C++11 [intro.execution]p15:
6113 // When calling a function [...], every value computation and side effect
6114 // associated with any argument expression, or with the postfix expression
6115 // designating the called function, is sequenced before execution of every
6116 // expression or statement in the body of the function [and thus before
6117 // the value computation of its result].
6118 SequencedSubexpression Sequenced(*this);
6119 Base::VisitCallExpr(CE);
6120
6121 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6122 }
6123
Richard Smithc406cb72013-01-17 01:17:56 +00006124 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006125 // This is a call, so all subexpressions are sequenced before the result.
6126 SequencedSubexpression Sequenced(*this);
6127
Richard Smithc406cb72013-01-17 01:17:56 +00006128 if (!CCE->isListInitialization())
6129 return VisitExpr(CCE);
6130
6131 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006132 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006133 SequenceTree::Seq Parent = Region;
6134 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6135 E = CCE->arg_end();
6136 I != E; ++I) {
6137 Region = Tree.allocate(Parent);
6138 Elts.push_back(Region);
6139 Visit(*I);
6140 }
6141
6142 // Forget that the initializers are sequenced.
6143 Region = Parent;
6144 for (unsigned I = 0; I < Elts.size(); ++I)
6145 Tree.merge(Elts[I]);
6146 }
6147
6148 void VisitInitListExpr(InitListExpr *ILE) {
6149 if (!SemaRef.getLangOpts().CPlusPlus11)
6150 return VisitExpr(ILE);
6151
6152 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006153 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006154 SequenceTree::Seq Parent = Region;
6155 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6156 Expr *E = ILE->getInit(I);
6157 if (!E) continue;
6158 Region = Tree.allocate(Parent);
6159 Elts.push_back(Region);
6160 Visit(E);
6161 }
6162
6163 // Forget that the initializers are sequenced.
6164 Region = Parent;
6165 for (unsigned I = 0; I < Elts.size(); ++I)
6166 Tree.merge(Elts[I]);
6167 }
6168};
6169}
6170
6171void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006172 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006173 WorkList.push_back(E);
6174 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006175 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006176 SequenceChecker(*this, Item, WorkList);
6177 }
Richard Smithc406cb72013-01-17 01:17:56 +00006178}
6179
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006180void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6181 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006182 CheckImplicitConversions(E, CheckLoc);
6183 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006184 if (!IsConstexpr && !E->isValueDependent())
6185 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006186}
6187
John McCall1f425642010-11-11 03:21:53 +00006188void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6189 FieldDecl *BitField,
6190 Expr *Init) {
6191 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6192}
6193
Mike Stump0c2ec772010-01-21 03:59:47 +00006194/// CheckParmsForFunctionDef - Check that the parameters of the given
6195/// function are appropriate for the definition of a function. This
6196/// takes care of any checks that cannot be performed on the
6197/// declaration itself, e.g., that the types of each of the function
6198/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006199bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6200 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006201 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006202 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006203 for (; P != PEnd; ++P) {
6204 ParmVarDecl *Param = *P;
6205
Mike Stump0c2ec772010-01-21 03:59:47 +00006206 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6207 // function declarator that is part of a function definition of
6208 // that function shall not have incomplete type.
6209 //
6210 // This is also C++ [dcl.fct]p6.
6211 if (!Param->isInvalidDecl() &&
6212 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006213 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006214 Param->setInvalidDecl();
6215 HasInvalidParm = true;
6216 }
6217
6218 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6219 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006220 if (CheckParameterNames &&
6221 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006222 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006223 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006224 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006225
6226 // C99 6.7.5.3p12:
6227 // If the function declarator is not part of a definition of that
6228 // function, parameters may have incomplete type and may use the [*]
6229 // notation in their sequences of declarator specifiers to specify
6230 // variable length array types.
6231 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006232 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006233 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006234 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006235 // information is added for it.
6236 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006237 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006238 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006239 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006240 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006241
6242 // MSVC destroys objects passed by value in the callee. Therefore a
6243 // function definition which takes such a parameter must be able to call the
6244 // object's destructor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006245 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6246 .getCXXABI()
6247 .areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006248 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6249 FinalizeVarWithDestructor(Param, RT);
6250 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006251 }
6252
6253 return HasInvalidParm;
6254}
John McCall2b5c1b22010-08-12 21:44:57 +00006255
6256/// CheckCastAlign - Implements -Wcast-align, which warns when a
6257/// pointer cast increases the alignment requirements.
6258void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6259 // This is actually a lot of work to potentially be doing on every
6260 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006261 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6262 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006263 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006264 return;
6265
6266 // Ignore dependent types.
6267 if (T->isDependentType() || Op->getType()->isDependentType())
6268 return;
6269
6270 // Require that the destination be a pointer type.
6271 const PointerType *DestPtr = T->getAs<PointerType>();
6272 if (!DestPtr) return;
6273
6274 // If the destination has alignment 1, we're done.
6275 QualType DestPointee = DestPtr->getPointeeType();
6276 if (DestPointee->isIncompleteType()) return;
6277 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6278 if (DestAlign.isOne()) return;
6279
6280 // Require that the source be a pointer type.
6281 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6282 if (!SrcPtr) return;
6283 QualType SrcPointee = SrcPtr->getPointeeType();
6284
6285 // Whitelist casts from cv void*. We already implicitly
6286 // whitelisted casts to cv void*, since they have alignment 1.
6287 // Also whitelist casts involving incomplete types, which implicitly
6288 // includes 'void'.
6289 if (SrcPointee->isIncompleteType()) return;
6290
6291 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6292 if (SrcAlign >= DestAlign) return;
6293
6294 Diag(TRange.getBegin(), diag::warn_cast_align)
6295 << Op->getType() << T
6296 << static_cast<unsigned>(SrcAlign.getQuantity())
6297 << static_cast<unsigned>(DestAlign.getQuantity())
6298 << TRange << Op->getSourceRange();
6299}
6300
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006301static const Type* getElementType(const Expr *BaseExpr) {
6302 const Type* EltType = BaseExpr->getType().getTypePtr();
6303 if (EltType->isAnyPointerType())
6304 return EltType->getPointeeType().getTypePtr();
6305 else if (EltType->isArrayType())
6306 return EltType->getBaseElementTypeUnsafe();
6307 return EltType;
6308}
6309
Chandler Carruth28389f02011-08-05 09:10:50 +00006310/// \brief Check whether this array fits the idiom of a size-one tail padded
6311/// array member of a struct.
6312///
6313/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6314/// commonly used to emulate flexible arrays in C89 code.
6315static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6316 const NamedDecl *ND) {
6317 if (Size != 1 || !ND) return false;
6318
6319 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6320 if (!FD) return false;
6321
6322 // Don't consider sizes resulting from macro expansions or template argument
6323 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006324
6325 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006326 while (TInfo) {
6327 TypeLoc TL = TInfo->getTypeLoc();
6328 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006329 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6330 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006331 TInfo = TDL->getTypeSourceInfo();
6332 continue;
6333 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006334 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6335 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006336 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6337 return false;
6338 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006339 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006340 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006341
6342 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006343 if (!RD) return false;
6344 if (RD->isUnion()) return false;
6345 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6346 if (!CRD->isStandardLayout()) return false;
6347 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006348
Benjamin Kramer8c543672011-08-06 03:04:42 +00006349 // See if this is the last field decl in the record.
6350 const Decl *D = FD;
6351 while ((D = D->getNextDeclInContext()))
6352 if (isa<FieldDecl>(D))
6353 return false;
6354 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006355}
6356
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006357void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006358 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006359 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006360 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006361 if (IndexExpr->isValueDependent())
6362 return;
6363
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006364 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006365 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006366 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006367 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006368 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006369 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006370
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006371 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006372 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006373 return;
Richard Smith13f67182011-12-16 19:31:14 +00006374 if (IndexNegated)
6375 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006376
Chandler Carruth126b1552011-08-05 08:07:29 +00006377 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00006378 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6379 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00006380 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00006381 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00006382
Ted Kremeneke4b316c2011-02-23 23:06:04 +00006383 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006384 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00006385 if (!size.isStrictlyPositive())
6386 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006387
6388 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00006389 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006390 // Make sure we're comparing apples to apples when comparing index to size
6391 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6392 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00006393 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00006394 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006395 if (ptrarith_typesize != array_typesize) {
6396 // There's a cast to a different size type involved
6397 uint64_t ratio = array_typesize / ptrarith_typesize;
6398 // TODO: Be smarter about handling cases where array_typesize is not a
6399 // multiple of ptrarith_typesize
6400 if (ptrarith_typesize * ratio == array_typesize)
6401 size *= llvm::APInt(size.getBitWidth(), ratio);
6402 }
6403 }
6404
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006405 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006406 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006407 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006408 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006409
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006410 // For array subscripting the index must be less than size, but for pointer
6411 // arithmetic also allow the index (offset) to be equal to size since
6412 // computing the next address after the end of the array is legal and
6413 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006414 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00006415 return;
6416
6417 // Also don't warn for arrays of size 1 which are members of some
6418 // structure. These are often used to approximate flexible arrays in C89
6419 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006420 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00006421 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006422
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006423 // Suppress the warning if the subscript expression (as identified by the
6424 // ']' location) and the index expression are both from macro expansions
6425 // within a system header.
6426 if (ASE) {
6427 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6428 ASE->getRBracketLoc());
6429 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6430 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6431 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00006432 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006433 return;
6434 }
6435 }
6436
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006437 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006438 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006439 DiagID = diag::warn_array_index_exceeds_bounds;
6440
6441 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6442 PDiag(DiagID) << index.toString(10, true)
6443 << size.toString(10, true)
6444 << (unsigned)size.getLimitedValue(~0U)
6445 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006446 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006447 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006448 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006449 DiagID = diag::warn_ptr_arith_precedes_bounds;
6450 if (index.isNegative()) index = -index;
6451 }
6452
6453 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6454 PDiag(DiagID) << index.toString(10, true)
6455 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00006456 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00006457
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00006458 if (!ND) {
6459 // Try harder to find a NamedDecl to point at in the note.
6460 while (const ArraySubscriptExpr *ASE =
6461 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6462 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6463 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6464 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6465 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6466 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6467 }
6468
Chandler Carruth1af88f12011-02-17 21:10:52 +00006469 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006470 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6471 PDiag(diag::note_array_index_out_of_bounds)
6472 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00006473}
6474
Ted Kremenekdf26df72011-03-01 18:41:00 +00006475void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006476 int AllowOnePastEnd = 0;
6477 while (expr) {
6478 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00006479 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006480 case Stmt::ArraySubscriptExprClass: {
6481 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006482 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006483 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00006484 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006485 }
6486 case Stmt::UnaryOperatorClass: {
6487 // Only unwrap the * and & unary operators
6488 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6489 expr = UO->getSubExpr();
6490 switch (UO->getOpcode()) {
6491 case UO_AddrOf:
6492 AllowOnePastEnd++;
6493 break;
6494 case UO_Deref:
6495 AllowOnePastEnd--;
6496 break;
6497 default:
6498 return;
6499 }
6500 break;
6501 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006502 case Stmt::ConditionalOperatorClass: {
6503 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6504 if (const Expr *lhs = cond->getLHS())
6505 CheckArrayAccess(lhs);
6506 if (const Expr *rhs = cond->getRHS())
6507 CheckArrayAccess(rhs);
6508 return;
6509 }
6510 default:
6511 return;
6512 }
Peter Collingbourne91147592011-04-15 00:35:48 +00006513 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006514}
John McCall31168b02011-06-15 23:02:42 +00006515
6516//===--- CHECK: Objective-C retain cycles ----------------------------------//
6517
6518namespace {
6519 struct RetainCycleOwner {
6520 RetainCycleOwner() : Variable(0), Indirect(false) {}
6521 VarDecl *Variable;
6522 SourceRange Range;
6523 SourceLocation Loc;
6524 bool Indirect;
6525
6526 void setLocsFrom(Expr *e) {
6527 Loc = e->getExprLoc();
6528 Range = e->getSourceRange();
6529 }
6530 };
6531}
6532
6533/// Consider whether capturing the given variable can possibly lead to
6534/// a retain cycle.
6535static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006536 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00006537 // lifetime. In MRR, it's captured strongly if the variable is
6538 // __block and has an appropriate type.
6539 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6540 return false;
6541
6542 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006543 if (ref)
6544 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00006545 return true;
6546}
6547
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006548static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00006549 while (true) {
6550 e = e->IgnoreParens();
6551 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6552 switch (cast->getCastKind()) {
6553 case CK_BitCast:
6554 case CK_LValueBitCast:
6555 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00006556 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00006557 e = cast->getSubExpr();
6558 continue;
6559
John McCall31168b02011-06-15 23:02:42 +00006560 default:
6561 return false;
6562 }
6563 }
6564
6565 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6566 ObjCIvarDecl *ivar = ref->getDecl();
6567 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6568 return false;
6569
6570 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006571 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00006572 return false;
6573
6574 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6575 owner.Indirect = true;
6576 return true;
6577 }
6578
6579 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6580 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6581 if (!var) return false;
6582 return considerVariable(var, ref, owner);
6583 }
6584
John McCall31168b02011-06-15 23:02:42 +00006585 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6586 if (member->isArrow()) return false;
6587
6588 // Don't count this as an indirect ownership.
6589 e = member->getBase();
6590 continue;
6591 }
6592
John McCallfe96e0b2011-11-06 09:01:30 +00006593 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6594 // Only pay attention to pseudo-objects on property references.
6595 ObjCPropertyRefExpr *pre
6596 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6597 ->IgnoreParens());
6598 if (!pre) return false;
6599 if (pre->isImplicitProperty()) return false;
6600 ObjCPropertyDecl *property = pre->getExplicitProperty();
6601 if (!property->isRetaining() &&
6602 !(property->getPropertyIvarDecl() &&
6603 property->getPropertyIvarDecl()->getType()
6604 .getObjCLifetime() == Qualifiers::OCL_Strong))
6605 return false;
6606
6607 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006608 if (pre->isSuperReceiver()) {
6609 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6610 if (!owner.Variable)
6611 return false;
6612 owner.Loc = pre->getLocation();
6613 owner.Range = pre->getSourceRange();
6614 return true;
6615 }
John McCallfe96e0b2011-11-06 09:01:30 +00006616 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6617 ->getSourceExpr());
6618 continue;
6619 }
6620
John McCall31168b02011-06-15 23:02:42 +00006621 // Array ivars?
6622
6623 return false;
6624 }
6625}
6626
6627namespace {
6628 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6629 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6630 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6631 Variable(variable), Capturer(0) {}
6632
6633 VarDecl *Variable;
6634 Expr *Capturer;
6635
6636 void VisitDeclRefExpr(DeclRefExpr *ref) {
6637 if (ref->getDecl() == Variable && !Capturer)
6638 Capturer = ref;
6639 }
6640
John McCall31168b02011-06-15 23:02:42 +00006641 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6642 if (Capturer) return;
6643 Visit(ref->getBase());
6644 if (Capturer && ref->isFreeIvar())
6645 Capturer = ref;
6646 }
6647
6648 void VisitBlockExpr(BlockExpr *block) {
6649 // Look inside nested blocks
6650 if (block->getBlockDecl()->capturesVariable(Variable))
6651 Visit(block->getBlockDecl()->getBody());
6652 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00006653
6654 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6655 if (Capturer) return;
6656 if (OVE->getSourceExpr())
6657 Visit(OVE->getSourceExpr());
6658 }
John McCall31168b02011-06-15 23:02:42 +00006659 };
6660}
6661
6662/// Check whether the given argument is a block which captures a
6663/// variable.
6664static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6665 assert(owner.Variable && owner.Loc.isValid());
6666
6667 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00006668
6669 // Look through [^{...} copy] and Block_copy(^{...}).
6670 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6671 Selector Cmd = ME->getSelector();
6672 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6673 e = ME->getInstanceReceiver();
6674 if (!e)
6675 return 0;
6676 e = e->IgnoreParenCasts();
6677 }
6678 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6679 if (CE->getNumArgs() == 1) {
6680 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00006681 if (Fn) {
6682 const IdentifierInfo *FnI = Fn->getIdentifier();
6683 if (FnI && FnI->isStr("_Block_copy")) {
6684 e = CE->getArg(0)->IgnoreParenCasts();
6685 }
6686 }
Jordan Rose67e887c2012-09-17 17:54:30 +00006687 }
6688 }
6689
John McCall31168b02011-06-15 23:02:42 +00006690 BlockExpr *block = dyn_cast<BlockExpr>(e);
6691 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6692 return 0;
6693
6694 FindCaptureVisitor visitor(S.Context, owner.Variable);
6695 visitor.Visit(block->getBlockDecl()->getBody());
6696 return visitor.Capturer;
6697}
6698
6699static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6700 RetainCycleOwner &owner) {
6701 assert(capturer);
6702 assert(owner.Variable && owner.Loc.isValid());
6703
6704 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6705 << owner.Variable << capturer->getSourceRange();
6706 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6707 << owner.Indirect << owner.Range;
6708}
6709
6710/// Check for a keyword selector that starts with the word 'add' or
6711/// 'set'.
6712static bool isSetterLikeSelector(Selector sel) {
6713 if (sel.isUnarySelector()) return false;
6714
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006715 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00006716 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006717 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00006718 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006719 else if (str.startswith("add")) {
6720 // Specially whitelist 'addOperationWithBlock:'.
6721 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6722 return false;
6723 str = str.substr(3);
6724 }
John McCall31168b02011-06-15 23:02:42 +00006725 else
6726 return false;
6727
6728 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00006729 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00006730}
6731
6732/// Check a message send to see if it's likely to cause a retain cycle.
6733void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6734 // Only check instance methods whose selector looks like a setter.
6735 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6736 return;
6737
6738 // Try to find a variable that the receiver is strongly owned by.
6739 RetainCycleOwner owner;
6740 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006741 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00006742 return;
6743 } else {
6744 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6745 owner.Variable = getCurMethodDecl()->getSelfDecl();
6746 owner.Loc = msg->getSuperLoc();
6747 owner.Range = msg->getSuperLoc();
6748 }
6749
6750 // Check whether the receiver is captured by any of the arguments.
6751 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6752 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6753 return diagnoseRetainCycle(*this, capturer, owner);
6754}
6755
6756/// Check a property assign to see if it's likely to cause a retain cycle.
6757void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6758 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006759 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00006760 return;
6761
6762 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6763 diagnoseRetainCycle(*this, capturer, owner);
6764}
6765
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006766void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6767 RetainCycleOwner Owner;
6768 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6769 return;
6770
6771 // Because we don't have an expression for the variable, we have to set the
6772 // location explicitly here.
6773 Owner.Loc = Var->getLocation();
6774 Owner.Range = Var->getSourceRange();
6775
6776 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6777 diagnoseRetainCycle(*this, Capturer, Owner);
6778}
6779
Ted Kremenek9304da92012-12-21 08:04:28 +00006780static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6781 Expr *RHS, bool isProperty) {
6782 // Check if RHS is an Objective-C object literal, which also can get
6783 // immediately zapped in a weak reference. Note that we explicitly
6784 // allow ObjCStringLiterals, since those are designed to never really die.
6785 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006786
Ted Kremenek64873352012-12-21 22:46:35 +00006787 // This enum needs to match with the 'select' in
6788 // warn_objc_arc_literal_assign (off-by-1).
6789 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6790 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6791 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006792
6793 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00006794 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00006795 << (isProperty ? 0 : 1)
6796 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006797
6798 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00006799}
6800
Ted Kremenekc1f014a2012-12-21 19:45:30 +00006801static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6802 Qualifiers::ObjCLifetime LT,
6803 Expr *RHS, bool isProperty) {
6804 // Strip off any implicit cast added to get to the one ARC-specific.
6805 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6806 if (cast->getCastKind() == CK_ARCConsumeObject) {
6807 S.Diag(Loc, diag::warn_arc_retained_assign)
6808 << (LT == Qualifiers::OCL_ExplicitNone)
6809 << (isProperty ? 0 : 1)
6810 << RHS->getSourceRange();
6811 return true;
6812 }
6813 RHS = cast->getSubExpr();
6814 }
6815
6816 if (LT == Qualifiers::OCL_Weak &&
6817 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6818 return true;
6819
6820 return false;
6821}
6822
Ted Kremenekb36234d2012-12-21 08:04:20 +00006823bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6824 QualType LHS, Expr *RHS) {
6825 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6826
6827 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6828 return false;
6829
6830 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6831 return true;
6832
6833 return false;
6834}
6835
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006836void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6837 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006838 QualType LHSType;
6839 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006840 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006841 ObjCPropertyRefExpr *PRE
6842 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6843 if (PRE && !PRE->isImplicitProperty()) {
6844 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6845 if (PD)
6846 LHSType = PD->getType();
6847 }
6848
6849 if (LHSType.isNull())
6850 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00006851
6852 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6853
6854 if (LT == Qualifiers::OCL_Weak) {
6855 DiagnosticsEngine::Level Level =
6856 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6857 if (Level != DiagnosticsEngine::Ignored)
6858 getCurFunction()->markSafeWeakUse(LHS);
6859 }
6860
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006861 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6862 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00006863
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006864 // FIXME. Check for other life times.
6865 if (LT != Qualifiers::OCL_None)
6866 return;
6867
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006868 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006869 if (PRE->isImplicitProperty())
6870 return;
6871 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6872 if (!PD)
6873 return;
6874
Bill Wendling44426052012-12-20 19:22:21 +00006875 unsigned Attributes = PD->getPropertyAttributes();
6876 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006877 // when 'assign' attribute was not explicitly specified
6878 // by user, ignore it and rely on property type itself
6879 // for lifetime info.
6880 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6881 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6882 LHSType->isObjCRetainableType())
6883 return;
6884
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006885 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00006886 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006887 Diag(Loc, diag::warn_arc_retained_property_assign)
6888 << RHS->getSourceRange();
6889 return;
6890 }
6891 RHS = cast->getSubExpr();
6892 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006893 }
Bill Wendling44426052012-12-20 19:22:21 +00006894 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00006895 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6896 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00006897 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006898 }
6899}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00006900
6901//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6902
6903namespace {
6904bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6905 SourceLocation StmtLoc,
6906 const NullStmt *Body) {
6907 // Do not warn if the body is a macro that expands to nothing, e.g:
6908 //
6909 // #define CALL(x)
6910 // if (condition)
6911 // CALL(0);
6912 //
6913 if (Body->hasLeadingEmptyMacro())
6914 return false;
6915
6916 // Get line numbers of statement and body.
6917 bool StmtLineInvalid;
6918 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6919 &StmtLineInvalid);
6920 if (StmtLineInvalid)
6921 return false;
6922
6923 bool BodyLineInvalid;
6924 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6925 &BodyLineInvalid);
6926 if (BodyLineInvalid)
6927 return false;
6928
6929 // Warn if null statement and body are on the same line.
6930 if (StmtLine != BodyLine)
6931 return false;
6932
6933 return true;
6934}
6935} // Unnamed namespace
6936
6937void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6938 const Stmt *Body,
6939 unsigned DiagID) {
6940 // Since this is a syntactic check, don't emit diagnostic for template
6941 // instantiations, this just adds noise.
6942 if (CurrentInstantiationScope)
6943 return;
6944
6945 // The body should be a null statement.
6946 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6947 if (!NBody)
6948 return;
6949
6950 // Do the usual checks.
6951 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6952 return;
6953
6954 Diag(NBody->getSemiLoc(), DiagID);
6955 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6956}
6957
6958void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6959 const Stmt *PossibleBody) {
6960 assert(!CurrentInstantiationScope); // Ensured by caller
6961
6962 SourceLocation StmtLoc;
6963 const Stmt *Body;
6964 unsigned DiagID;
6965 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6966 StmtLoc = FS->getRParenLoc();
6967 Body = FS->getBody();
6968 DiagID = diag::warn_empty_for_body;
6969 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6970 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6971 Body = WS->getBody();
6972 DiagID = diag::warn_empty_while_body;
6973 } else
6974 return; // Neither `for' nor `while'.
6975
6976 // The body should be a null statement.
6977 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6978 if (!NBody)
6979 return;
6980
6981 // Skip expensive checks if diagnostic is disabled.
6982 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6983 DiagnosticsEngine::Ignored)
6984 return;
6985
6986 // Do the usual checks.
6987 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6988 return;
6989
6990 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6991 // noise level low, emit diagnostics only if for/while is followed by a
6992 // CompoundStmt, e.g.:
6993 // for (int i = 0; i < n; i++);
6994 // {
6995 // a(i);
6996 // }
6997 // or if for/while is followed by a statement with more indentation
6998 // than for/while itself:
6999 // for (int i = 0; i < n; i++);
7000 // a(i);
7001 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7002 if (!ProbableTypo) {
7003 bool BodyColInvalid;
7004 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7005 PossibleBody->getLocStart(),
7006 &BodyColInvalid);
7007 if (BodyColInvalid)
7008 return;
7009
7010 bool StmtColInvalid;
7011 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7012 S->getLocStart(),
7013 &StmtColInvalid);
7014 if (StmtColInvalid)
7015 return;
7016
7017 if (BodyCol > StmtCol)
7018 ProbableTypo = true;
7019 }
7020
7021 if (ProbableTypo) {
7022 Diag(NBody->getSemiLoc(), DiagID);
7023 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7024 }
7025}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007026
7027//===--- Layout compatibility ----------------------------------------------//
7028
7029namespace {
7030
7031bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7032
7033/// \brief Check if two enumeration types are layout-compatible.
7034bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7035 // C++11 [dcl.enum] p8:
7036 // Two enumeration types are layout-compatible if they have the same
7037 // underlying type.
7038 return ED1->isComplete() && ED2->isComplete() &&
7039 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7040}
7041
7042/// \brief Check if two fields are layout-compatible.
7043bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7044 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7045 return false;
7046
7047 if (Field1->isBitField() != Field2->isBitField())
7048 return false;
7049
7050 if (Field1->isBitField()) {
7051 // Make sure that the bit-fields are the same length.
7052 unsigned Bits1 = Field1->getBitWidthValue(C);
7053 unsigned Bits2 = Field2->getBitWidthValue(C);
7054
7055 if (Bits1 != Bits2)
7056 return false;
7057 }
7058
7059 return true;
7060}
7061
7062/// \brief Check if two standard-layout structs are layout-compatible.
7063/// (C++11 [class.mem] p17)
7064bool isLayoutCompatibleStruct(ASTContext &C,
7065 RecordDecl *RD1,
7066 RecordDecl *RD2) {
7067 // If both records are C++ classes, check that base classes match.
7068 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7069 // If one of records is a CXXRecordDecl we are in C++ mode,
7070 // thus the other one is a CXXRecordDecl, too.
7071 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7072 // Check number of base classes.
7073 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7074 return false;
7075
7076 // Check the base classes.
7077 for (CXXRecordDecl::base_class_const_iterator
7078 Base1 = D1CXX->bases_begin(),
7079 BaseEnd1 = D1CXX->bases_end(),
7080 Base2 = D2CXX->bases_begin();
7081 Base1 != BaseEnd1;
7082 ++Base1, ++Base2) {
7083 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7084 return false;
7085 }
7086 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7087 // If only RD2 is a C++ class, it should have zero base classes.
7088 if (D2CXX->getNumBases() > 0)
7089 return false;
7090 }
7091
7092 // Check the fields.
7093 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7094 Field2End = RD2->field_end(),
7095 Field1 = RD1->field_begin(),
7096 Field1End = RD1->field_end();
7097 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7098 if (!isLayoutCompatible(C, *Field1, *Field2))
7099 return false;
7100 }
7101 if (Field1 != Field1End || Field2 != Field2End)
7102 return false;
7103
7104 return true;
7105}
7106
7107/// \brief Check if two standard-layout unions are layout-compatible.
7108/// (C++11 [class.mem] p18)
7109bool isLayoutCompatibleUnion(ASTContext &C,
7110 RecordDecl *RD1,
7111 RecordDecl *RD2) {
7112 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7113 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7114 Field2End = RD2->field_end();
7115 Field2 != Field2End; ++Field2) {
7116 UnmatchedFields.insert(*Field2);
7117 }
7118
7119 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7120 Field1End = RD1->field_end();
7121 Field1 != Field1End; ++Field1) {
7122 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7123 I = UnmatchedFields.begin(),
7124 E = UnmatchedFields.end();
7125
7126 for ( ; I != E; ++I) {
7127 if (isLayoutCompatible(C, *Field1, *I)) {
7128 bool Result = UnmatchedFields.erase(*I);
7129 (void) Result;
7130 assert(Result);
7131 break;
7132 }
7133 }
7134 if (I == E)
7135 return false;
7136 }
7137
7138 return UnmatchedFields.empty();
7139}
7140
7141bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7142 if (RD1->isUnion() != RD2->isUnion())
7143 return false;
7144
7145 if (RD1->isUnion())
7146 return isLayoutCompatibleUnion(C, RD1, RD2);
7147 else
7148 return isLayoutCompatibleStruct(C, RD1, RD2);
7149}
7150
7151/// \brief Check if two types are layout-compatible in C++11 sense.
7152bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7153 if (T1.isNull() || T2.isNull())
7154 return false;
7155
7156 // C++11 [basic.types] p11:
7157 // If two types T1 and T2 are the same type, then T1 and T2 are
7158 // layout-compatible types.
7159 if (C.hasSameType(T1, T2))
7160 return true;
7161
7162 T1 = T1.getCanonicalType().getUnqualifiedType();
7163 T2 = T2.getCanonicalType().getUnqualifiedType();
7164
7165 const Type::TypeClass TC1 = T1->getTypeClass();
7166 const Type::TypeClass TC2 = T2->getTypeClass();
7167
7168 if (TC1 != TC2)
7169 return false;
7170
7171 if (TC1 == Type::Enum) {
7172 return isLayoutCompatible(C,
7173 cast<EnumType>(T1)->getDecl(),
7174 cast<EnumType>(T2)->getDecl());
7175 } else if (TC1 == Type::Record) {
7176 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7177 return false;
7178
7179 return isLayoutCompatible(C,
7180 cast<RecordType>(T1)->getDecl(),
7181 cast<RecordType>(T2)->getDecl());
7182 }
7183
7184 return false;
7185}
7186}
7187
7188//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7189
7190namespace {
7191/// \brief Given a type tag expression find the type tag itself.
7192///
7193/// \param TypeExpr Type tag expression, as it appears in user's code.
7194///
7195/// \param VD Declaration of an identifier that appears in a type tag.
7196///
7197/// \param MagicValue Type tag magic value.
7198bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7199 const ValueDecl **VD, uint64_t *MagicValue) {
7200 while(true) {
7201 if (!TypeExpr)
7202 return false;
7203
7204 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7205
7206 switch (TypeExpr->getStmtClass()) {
7207 case Stmt::UnaryOperatorClass: {
7208 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7209 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7210 TypeExpr = UO->getSubExpr();
7211 continue;
7212 }
7213 return false;
7214 }
7215
7216 case Stmt::DeclRefExprClass: {
7217 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7218 *VD = DRE->getDecl();
7219 return true;
7220 }
7221
7222 case Stmt::IntegerLiteralClass: {
7223 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7224 llvm::APInt MagicValueAPInt = IL->getValue();
7225 if (MagicValueAPInt.getActiveBits() <= 64) {
7226 *MagicValue = MagicValueAPInt.getZExtValue();
7227 return true;
7228 } else
7229 return false;
7230 }
7231
7232 case Stmt::BinaryConditionalOperatorClass:
7233 case Stmt::ConditionalOperatorClass: {
7234 const AbstractConditionalOperator *ACO =
7235 cast<AbstractConditionalOperator>(TypeExpr);
7236 bool Result;
7237 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7238 if (Result)
7239 TypeExpr = ACO->getTrueExpr();
7240 else
7241 TypeExpr = ACO->getFalseExpr();
7242 continue;
7243 }
7244 return false;
7245 }
7246
7247 case Stmt::BinaryOperatorClass: {
7248 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7249 if (BO->getOpcode() == BO_Comma) {
7250 TypeExpr = BO->getRHS();
7251 continue;
7252 }
7253 return false;
7254 }
7255
7256 default:
7257 return false;
7258 }
7259 }
7260}
7261
7262/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7263///
7264/// \param TypeExpr Expression that specifies a type tag.
7265///
7266/// \param MagicValues Registered magic values.
7267///
7268/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7269/// kind.
7270///
7271/// \param TypeInfo Information about the corresponding C type.
7272///
7273/// \returns true if the corresponding C type was found.
7274bool GetMatchingCType(
7275 const IdentifierInfo *ArgumentKind,
7276 const Expr *TypeExpr, const ASTContext &Ctx,
7277 const llvm::DenseMap<Sema::TypeTagMagicValue,
7278 Sema::TypeTagData> *MagicValues,
7279 bool &FoundWrongKind,
7280 Sema::TypeTagData &TypeInfo) {
7281 FoundWrongKind = false;
7282
7283 // Variable declaration that has type_tag_for_datatype attribute.
7284 const ValueDecl *VD = NULL;
7285
7286 uint64_t MagicValue;
7287
7288 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7289 return false;
7290
7291 if (VD) {
7292 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7293 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7294 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7295 I != E; ++I) {
7296 if (I->getArgumentKind() != ArgumentKind) {
7297 FoundWrongKind = true;
7298 return false;
7299 }
7300 TypeInfo.Type = I->getMatchingCType();
7301 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7302 TypeInfo.MustBeNull = I->getMustBeNull();
7303 return true;
7304 }
7305 return false;
7306 }
7307
7308 if (!MagicValues)
7309 return false;
7310
7311 llvm::DenseMap<Sema::TypeTagMagicValue,
7312 Sema::TypeTagData>::const_iterator I =
7313 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7314 if (I == MagicValues->end())
7315 return false;
7316
7317 TypeInfo = I->second;
7318 return true;
7319}
7320} // unnamed namespace
7321
7322void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7323 uint64_t MagicValue, QualType Type,
7324 bool LayoutCompatible,
7325 bool MustBeNull) {
7326 if (!TypeTagForDatatypeMagicValues)
7327 TypeTagForDatatypeMagicValues.reset(
7328 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7329
7330 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7331 (*TypeTagForDatatypeMagicValues)[Magic] =
7332 TypeTagData(Type, LayoutCompatible, MustBeNull);
7333}
7334
7335namespace {
7336bool IsSameCharType(QualType T1, QualType T2) {
7337 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7338 if (!BT1)
7339 return false;
7340
7341 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7342 if (!BT2)
7343 return false;
7344
7345 BuiltinType::Kind T1Kind = BT1->getKind();
7346 BuiltinType::Kind T2Kind = BT2->getKind();
7347
7348 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7349 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7350 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7351 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7352}
7353} // unnamed namespace
7354
7355void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7356 const Expr * const *ExprArgs) {
7357 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7358 bool IsPointerAttr = Attr->getIsPointer();
7359
7360 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7361 bool FoundWrongKind;
7362 TypeTagData TypeInfo;
7363 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7364 TypeTagForDatatypeMagicValues.get(),
7365 FoundWrongKind, TypeInfo)) {
7366 if (FoundWrongKind)
7367 Diag(TypeTagExpr->getExprLoc(),
7368 diag::warn_type_tag_for_datatype_wrong_kind)
7369 << TypeTagExpr->getSourceRange();
7370 return;
7371 }
7372
7373 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7374 if (IsPointerAttr) {
7375 // Skip implicit cast of pointer to `void *' (as a function argument).
7376 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007377 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007378 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007379 ArgumentExpr = ICE->getSubExpr();
7380 }
7381 QualType ArgumentType = ArgumentExpr->getType();
7382
7383 // Passing a `void*' pointer shouldn't trigger a warning.
7384 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7385 return;
7386
7387 if (TypeInfo.MustBeNull) {
7388 // Type tag with matching void type requires a null pointer.
7389 if (!ArgumentExpr->isNullPointerConstant(Context,
7390 Expr::NPC_ValueDependentIsNotNull)) {
7391 Diag(ArgumentExpr->getExprLoc(),
7392 diag::warn_type_safety_null_pointer_required)
7393 << ArgumentKind->getName()
7394 << ArgumentExpr->getSourceRange()
7395 << TypeTagExpr->getSourceRange();
7396 }
7397 return;
7398 }
7399
7400 QualType RequiredType = TypeInfo.Type;
7401 if (IsPointerAttr)
7402 RequiredType = Context.getPointerType(RequiredType);
7403
7404 bool mismatch = false;
7405 if (!TypeInfo.LayoutCompatible) {
7406 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7407
7408 // C++11 [basic.fundamental] p1:
7409 // Plain char, signed char, and unsigned char are three distinct types.
7410 //
7411 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7412 // char' depending on the current char signedness mode.
7413 if (mismatch)
7414 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7415 RequiredType->getPointeeType())) ||
7416 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7417 mismatch = false;
7418 } else
7419 if (IsPointerAttr)
7420 mismatch = !isLayoutCompatible(Context,
7421 ArgumentType->getPointeeType(),
7422 RequiredType->getPointeeType());
7423 else
7424 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7425
7426 if (mismatch)
7427 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00007428 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007429 << TypeInfo.LayoutCompatible << RequiredType
7430 << ArgumentExpr->getSourceRange()
7431 << TypeTagExpr->getSourceRange();
7432}