blob: 916ce7d9855750b07eadd81328a5209111168a57 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCalldadc5752010-08-24 06:29:42 +0000114ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000116 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000117
Chris Lattner3be167f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000142 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Reid Kleckner597e81d2014-03-26 15:38:33 +0000145 case Builtin::BI__va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000146 if (SemaBuiltinVAStart(TheCall))
147 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000148 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000149 case Builtin::BI__builtin_isgreater:
150 case Builtin::BI__builtin_isgreaterequal:
151 case Builtin::BI__builtin_isless:
152 case Builtin::BI__builtin_islessequal:
153 case Builtin::BI__builtin_islessgreater:
154 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000155 if (SemaBuiltinUnorderedCompare(TheCall))
156 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000157 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000158 case Builtin::BI__builtin_fpclassify:
159 if (SemaBuiltinFPClassification(TheCall, 6))
160 return ExprError();
161 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000162 case Builtin::BI__builtin_isfinite:
163 case Builtin::BI__builtin_isinf:
164 case Builtin::BI__builtin_isinf_sign:
165 case Builtin::BI__builtin_isnan:
166 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000167 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000168 return ExprError();
169 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000170 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000171 return SemaBuiltinShuffleVector(TheCall);
172 // TheCall will be freed by the smart pointer here, but that's fine, since
173 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000174 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000175 if (SemaBuiltinPrefetch(TheCall))
176 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000177 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000178 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000179 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000180 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000181 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000182 case Builtin::BI__builtin_longjmp:
183 if (SemaBuiltinLongjmp(TheCall))
184 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000185 break;
John McCallbebede42011-02-26 05:39:39 +0000186
187 case Builtin::BI__builtin_classify_type:
188 if (checkArgCount(*this, TheCall, 1)) return true;
189 TheCall->setType(Context.IntTy);
190 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000191 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000192 if (checkArgCount(*this, TheCall, 1)) return true;
193 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000194 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000195 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000196 case Builtin::BI__sync_fetch_and_add_1:
197 case Builtin::BI__sync_fetch_and_add_2:
198 case Builtin::BI__sync_fetch_and_add_4:
199 case Builtin::BI__sync_fetch_and_add_8:
200 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000201 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000202 case Builtin::BI__sync_fetch_and_sub_1:
203 case Builtin::BI__sync_fetch_and_sub_2:
204 case Builtin::BI__sync_fetch_and_sub_4:
205 case Builtin::BI__sync_fetch_and_sub_8:
206 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000207 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000208 case Builtin::BI__sync_fetch_and_or_1:
209 case Builtin::BI__sync_fetch_and_or_2:
210 case Builtin::BI__sync_fetch_and_or_4:
211 case Builtin::BI__sync_fetch_and_or_8:
212 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000213 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000214 case Builtin::BI__sync_fetch_and_and_1:
215 case Builtin::BI__sync_fetch_and_and_2:
216 case Builtin::BI__sync_fetch_and_and_4:
217 case Builtin::BI__sync_fetch_and_and_8:
218 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000219 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000220 case Builtin::BI__sync_fetch_and_xor_1:
221 case Builtin::BI__sync_fetch_and_xor_2:
222 case Builtin::BI__sync_fetch_and_xor_4:
223 case Builtin::BI__sync_fetch_and_xor_8:
224 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000225 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000226 case Builtin::BI__sync_add_and_fetch_1:
227 case Builtin::BI__sync_add_and_fetch_2:
228 case Builtin::BI__sync_add_and_fetch_4:
229 case Builtin::BI__sync_add_and_fetch_8:
230 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000231 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000232 case Builtin::BI__sync_sub_and_fetch_1:
233 case Builtin::BI__sync_sub_and_fetch_2:
234 case Builtin::BI__sync_sub_and_fetch_4:
235 case Builtin::BI__sync_sub_and_fetch_8:
236 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000237 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000238 case Builtin::BI__sync_and_and_fetch_1:
239 case Builtin::BI__sync_and_and_fetch_2:
240 case Builtin::BI__sync_and_and_fetch_4:
241 case Builtin::BI__sync_and_and_fetch_8:
242 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000243 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000244 case Builtin::BI__sync_or_and_fetch_1:
245 case Builtin::BI__sync_or_and_fetch_2:
246 case Builtin::BI__sync_or_and_fetch_4:
247 case Builtin::BI__sync_or_and_fetch_8:
248 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000249 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000250 case Builtin::BI__sync_xor_and_fetch_1:
251 case Builtin::BI__sync_xor_and_fetch_2:
252 case Builtin::BI__sync_xor_and_fetch_4:
253 case Builtin::BI__sync_xor_and_fetch_8:
254 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000255 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000256 case Builtin::BI__sync_val_compare_and_swap_1:
257 case Builtin::BI__sync_val_compare_and_swap_2:
258 case Builtin::BI__sync_val_compare_and_swap_4:
259 case Builtin::BI__sync_val_compare_and_swap_8:
260 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000261 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000262 case Builtin::BI__sync_bool_compare_and_swap_1:
263 case Builtin::BI__sync_bool_compare_and_swap_2:
264 case Builtin::BI__sync_bool_compare_and_swap_4:
265 case Builtin::BI__sync_bool_compare_and_swap_8:
266 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000267 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000268 case Builtin::BI__sync_lock_test_and_set_1:
269 case Builtin::BI__sync_lock_test_and_set_2:
270 case Builtin::BI__sync_lock_test_and_set_4:
271 case Builtin::BI__sync_lock_test_and_set_8:
272 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000273 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000274 case Builtin::BI__sync_lock_release_1:
275 case Builtin::BI__sync_lock_release_2:
276 case Builtin::BI__sync_lock_release_4:
277 case Builtin::BI__sync_lock_release_8:
278 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000279 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000280 case Builtin::BI__sync_swap_1:
281 case Builtin::BI__sync_swap_2:
282 case Builtin::BI__sync_swap_4:
283 case Builtin::BI__sync_swap_8:
284 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000285 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000286#define BUILTIN(ID, TYPE, ATTRS)
287#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
288 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000289 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000290#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000291 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000292 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000293 return ExprError();
294 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000295 case Builtin::BI__builtin_addressof:
296 if (SemaBuiltinAddressof(*this, TheCall))
297 return ExprError();
298 break;
Richard Smith760520b2014-06-03 23:27:44 +0000299 case Builtin::BI__builtin_operator_new:
300 case Builtin::BI__builtin_operator_delete:
301 if (!getLangOpts().CPlusPlus) {
302 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
303 << (BuiltinID == Builtin::BI__builtin_operator_new
304 ? "__builtin_operator_new"
305 : "__builtin_operator_delete")
306 << "C++";
307 return ExprError();
308 }
309 // CodeGen assumes it can find the global new and delete to call,
310 // so ensure that they are declared.
311 DeclareGlobalNewDelete();
312 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000313 }
Richard Smith760520b2014-06-03 23:27:44 +0000314
Nate Begeman4904e322010-06-08 02:47:44 +0000315 // Since the target specific builtins for each arch overlap, only check those
316 // of the arch we are compiling for.
317 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000318 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000319 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000320 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000321 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000322 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000323 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
324 return ExprError();
325 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000326 case llvm::Triple::aarch64:
327 case llvm::Triple::aarch64_be:
Tim Northovera2ee4332014-03-29 15:09:45 +0000328 case llvm::Triple::arm64:
James Molloyfa403682014-04-30 10:11:40 +0000329 case llvm::Triple::arm64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000330 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000331 return ExprError();
332 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000333 case llvm::Triple::mips:
334 case llvm::Triple::mipsel:
335 case llvm::Triple::mips64:
336 case llvm::Triple::mips64el:
337 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
338 return ExprError();
339 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000340 case llvm::Triple::x86:
341 case llvm::Triple::x86_64:
342 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
343 return ExprError();
344 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000345 default:
346 break;
347 }
348 }
349
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000350 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000351}
352
Nate Begeman91e1fea2010-06-14 05:21:25 +0000353// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000354static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000355 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000356 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000357 switch (Type.getEltType()) {
358 case NeonTypeFlags::Int8:
359 case NeonTypeFlags::Poly8:
360 return shift ? 7 : (8 << IsQuad) - 1;
361 case NeonTypeFlags::Int16:
362 case NeonTypeFlags::Poly16:
363 return shift ? 15 : (4 << IsQuad) - 1;
364 case NeonTypeFlags::Int32:
365 return shift ? 31 : (2 << IsQuad) - 1;
366 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000367 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000368 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000369 case NeonTypeFlags::Poly128:
370 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000371 case NeonTypeFlags::Float16:
372 assert(!shift && "cannot shift float types!");
373 return (4 << IsQuad) - 1;
374 case NeonTypeFlags::Float32:
375 assert(!shift && "cannot shift float types!");
376 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000377 case NeonTypeFlags::Float64:
378 assert(!shift && "cannot shift float types!");
379 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000380 }
David Blaikie8a40f702012-01-17 06:56:22 +0000381 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000382}
383
Bob Wilsone4d77232011-11-08 05:04:11 +0000384/// getNeonEltType - Return the QualType corresponding to the elements of
385/// the vector type specified by the NeonTypeFlags. This is used to check
386/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000387static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000388 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000389 switch (Flags.getEltType()) {
390 case NeonTypeFlags::Int8:
391 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
392 case NeonTypeFlags::Int16:
393 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
394 case NeonTypeFlags::Int32:
395 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
396 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000397 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000398 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
399 else
400 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
401 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000402 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000403 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000404 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000405 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000406 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000407 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000408 case NeonTypeFlags::Poly128:
409 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000410 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000411 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000412 case NeonTypeFlags::Float32:
413 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000414 case NeonTypeFlags::Float64:
415 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000416 }
David Blaikie8a40f702012-01-17 06:56:22 +0000417 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000418}
419
Tim Northover12670412014-02-19 10:37:05 +0000420bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000421 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000422 uint64_t mask = 0;
423 unsigned TV = 0;
424 int PtrArgNum = -1;
425 bool HasConstPtr = false;
426 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000427#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000428#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000429#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000430 }
431
432 // For NEON intrinsics which are overloaded on vector element type, validate
433 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000434 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000435 if (mask) {
436 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
437 return true;
438
439 TV = Result.getLimitedValue(64);
440 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
441 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000442 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000443 }
444
445 if (PtrArgNum >= 0) {
446 // Check that pointer arguments have the specified type.
447 Expr *Arg = TheCall->getArg(PtrArgNum);
448 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
449 Arg = ICE->getSubExpr();
450 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
451 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000452
Tim Northovera2ee4332014-03-29 15:09:45 +0000453 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
454 bool IsPolyUnsigned =
455 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
456 bool IsInt64Long =
457 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
458 QualType EltTy =
459 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000460 if (HasConstPtr)
461 EltTy = EltTy.withConst();
462 QualType LHSTy = Context.getPointerType(EltTy);
463 AssignConvertType ConvTy;
464 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
465 if (RHS.isInvalid())
466 return true;
467 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
468 RHS.get(), AA_Assigning))
469 return true;
470 }
471
472 // For NEON intrinsics which take an immediate value as part of the
473 // instruction, range check them here.
474 unsigned i = 0, l = 0, u = 0;
475 switch (BuiltinID) {
476 default:
477 return false;
Tim Northover12670412014-02-19 10:37:05 +0000478#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000479#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000480#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000481 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000482
Richard Sandiford28940af2014-04-16 08:47:51 +0000483 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000484}
485
Tim Northovera2ee4332014-03-29 15:09:45 +0000486bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
487 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000488 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000489 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000490 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
491 BuiltinID == AArch64::BI__builtin_arm_strex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000492 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000493 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000494 BuiltinID == AArch64::BI__builtin_arm_ldrex;
Tim Northover6aacd492013-07-16 09:47:53 +0000495
496 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
497
498 // Ensure that we have the proper number of arguments.
499 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
500 return true;
501
502 // Inspect the pointer argument of the atomic builtin. This should always be
503 // a pointer type, whose element is an integral scalar or pointer type.
504 // Because it is a pointer type, we don't have to worry about any implicit
505 // casts here.
506 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
507 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
508 if (PointerArgRes.isInvalid())
509 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000510 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000511
512 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
513 if (!pointerType) {
514 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
515 << PointerArg->getType() << PointerArg->getSourceRange();
516 return true;
517 }
518
519 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
520 // task is to insert the appropriate casts into the AST. First work out just
521 // what the appropriate type is.
522 QualType ValType = pointerType->getPointeeType();
523 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
524 if (IsLdrex)
525 AddrType.addConst();
526
527 // Issue a warning if the cast is dodgy.
528 CastKind CastNeeded = CK_NoOp;
529 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
530 CastNeeded = CK_BitCast;
531 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
532 << PointerArg->getType()
533 << Context.getPointerType(AddrType)
534 << AA_Passing << PointerArg->getSourceRange();
535 }
536
537 // Finally, do the cast and replace the argument with the corrected version.
538 AddrType = Context.getPointerType(AddrType);
539 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
540 if (PointerArgRes.isInvalid())
541 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000542 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000543
544 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
545
546 // In general, we allow ints, floats and pointers to be loaded and stored.
547 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
548 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
549 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
550 << PointerArg->getType() << PointerArg->getSourceRange();
551 return true;
552 }
553
554 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000555 if (Context.getTypeSize(ValType) > MaxWidth) {
556 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000557 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
558 << PointerArg->getType() << PointerArg->getSourceRange();
559 return true;
560 }
561
562 switch (ValType.getObjCLifetime()) {
563 case Qualifiers::OCL_None:
564 case Qualifiers::OCL_ExplicitNone:
565 // okay
566 break;
567
568 case Qualifiers::OCL_Weak:
569 case Qualifiers::OCL_Strong:
570 case Qualifiers::OCL_Autoreleasing:
571 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
572 << ValType << PointerArg->getSourceRange();
573 return true;
574 }
575
576
577 if (IsLdrex) {
578 TheCall->setType(ValType);
579 return false;
580 }
581
582 // Initialize the argument to be stored.
583 ExprResult ValArg = TheCall->getArg(0);
584 InitializedEntity Entity = InitializedEntity::InitializeParameter(
585 Context, ValType, /*consume*/ false);
586 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
587 if (ValArg.isInvalid())
588 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000589 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000590
591 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
592 // but the custom checker bypasses all default analysis.
593 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000594 return false;
595}
596
Nate Begeman4904e322010-06-08 02:47:44 +0000597bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000598 llvm::APSInt Result;
599
Tim Northover6aacd492013-07-16 09:47:53 +0000600 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
601 BuiltinID == ARM::BI__builtin_arm_strex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000602 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000603 }
604
Tim Northover12670412014-02-19 10:37:05 +0000605 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
606 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000607
Bob Wilsond836d3d2014-03-09 23:02:27 +0000608 // For NEON intrinsics which take an immediate value as part of the
Nate Begemand773fe62010-06-13 04:47:52 +0000609 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000610 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000611 switch (BuiltinID) {
612 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000613 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
614 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000615 case ARM::BI__builtin_arm_vcvtr_f:
616 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000617 case ARM::BI__builtin_arm_dmb:
618 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000619 }
Nate Begemand773fe62010-06-13 04:47:52 +0000620
Nate Begemanf568b072010-08-03 21:32:34 +0000621 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000622 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000623}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000624
Tim Northover573cbee2014-05-24 12:52:07 +0000625bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000626 CallExpr *TheCall) {
627 llvm::APSInt Result;
628
Tim Northover573cbee2014-05-24 12:52:07 +0000629 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
630 BuiltinID == AArch64::BI__builtin_arm_strex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000631 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
632 }
633
634 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
635 return true;
636
637 return false;
638}
639
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000640bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
641 unsigned i = 0, l = 0, u = 0;
642 switch (BuiltinID) {
643 default: return false;
644 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
645 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000646 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
647 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
648 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
649 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
650 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000651 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000652
Richard Sandiford28940af2014-04-16 08:47:51 +0000653 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000654}
655
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000656bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
657 switch (BuiltinID) {
658 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000659 // This is declared to take (const char*, int)
660 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000661 }
662 return false;
663}
664
Richard Smith55ce3522012-06-25 20:30:08 +0000665/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
666/// parameter with the FormatAttr's correct format_idx and firstDataArg.
667/// Returns true when the format fits the function and the FormatStringInfo has
668/// been populated.
669bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
670 FormatStringInfo *FSI) {
671 FSI->HasVAListArg = Format->getFirstArg() == 0;
672 FSI->FormatIdx = Format->getFormatIdx() - 1;
673 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000674
Richard Smith55ce3522012-06-25 20:30:08 +0000675 // The way the format attribute works in GCC, the implicit this argument
676 // of member functions is counted. However, it doesn't appear in our own
677 // lists, so decrement format_idx in that case.
678 if (IsCXXMember) {
679 if(FSI->FormatIdx == 0)
680 return false;
681 --FSI->FormatIdx;
682 if (FSI->FirstDataArg != 0)
683 --FSI->FirstDataArg;
684 }
685 return true;
686}
Mike Stump11289f42009-09-09 15:08:12 +0000687
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000688/// Checks if a the given expression evaluates to null.
689///
690/// \brief Returns true if the value evaluates to null.
691static bool CheckNonNullExpr(Sema &S,
692 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000693 // As a special case, transparent unions initialized with zero are
694 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000695 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000696 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
697 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000698 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000699 if (const InitListExpr *ILE =
700 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000701 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000702 }
703
704 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000705 return (!Expr->isValueDependent() &&
706 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
707 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000708}
709
710static void CheckNonNullArgument(Sema &S,
711 const Expr *ArgExpr,
712 SourceLocation CallSiteLoc) {
713 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000714 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
715}
716
Ted Kremenek2bc73332014-01-17 06:24:43 +0000717static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000718 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000719 const Expr * const *ExprArgs,
720 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000721 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000722 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000723 for (const auto &Val : NonNull->args())
724 CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000725 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000726
727 // Check the attributes on the parameters.
728 ArrayRef<ParmVarDecl*> parms;
729 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
730 parms = FD->parameters();
731 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
732 parms = MD->parameters();
733
734 unsigned argIndex = 0;
735 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
736 I != E; ++I, ++argIndex) {
737 const ParmVarDecl *PVD = *I;
738 if (PVD->hasAttr<NonNullAttr>())
739 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
740 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000741}
742
Richard Smith55ce3522012-06-25 20:30:08 +0000743/// Handles the checks for format strings, non-POD arguments to vararg
744/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000745void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
746 unsigned NumParams, bool IsMemberFunction,
747 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000748 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000749 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000750 if (CurContext->isDependentContext())
751 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000752
Ted Kremenekb8176da2010-09-09 04:33:05 +0000753 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000754 llvm::SmallBitVector CheckedVarArgs;
755 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000756 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000757 // Only create vector if there are format attributes.
758 CheckedVarArgs.resize(Args.size());
759
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000760 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000761 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000762 }
Richard Smithd7293d72013-08-05 18:49:43 +0000763 }
Richard Smith55ce3522012-06-25 20:30:08 +0000764
765 // Refuse POD arguments that weren't caught by the format string
766 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000767 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000768 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000769 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000770 if (const Expr *Arg = Args[ArgIdx]) {
771 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
772 checkVariadicArgument(Arg, CallType);
773 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000774 }
Richard Smithd7293d72013-08-05 18:49:43 +0000775 }
Mike Stump11289f42009-09-09 15:08:12 +0000776
Richard Trieu41bc0992013-06-22 00:20:41 +0000777 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000778 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000779
Richard Trieu41bc0992013-06-22 00:20:41 +0000780 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000781 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
782 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000783 }
Richard Smith55ce3522012-06-25 20:30:08 +0000784}
785
786/// CheckConstructorCall - Check a constructor call for correctness and safety
787/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000788void Sema::CheckConstructorCall(FunctionDecl *FDecl,
789 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000790 const FunctionProtoType *Proto,
791 SourceLocation Loc) {
792 VariadicCallType CallType =
793 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000794 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000795 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
796}
797
798/// CheckFunctionCall - Check a direct function call for various correctness
799/// and safety properties not strictly enforced by the C type system.
800bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
801 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000802 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
803 isa<CXXMethodDecl>(FDecl);
804 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
805 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000806 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
807 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000808 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000809 Expr** Args = TheCall->getArgs();
810 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000811 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000812 // If this is a call to a member operator, hide the first argument
813 // from checkCall.
814 // FIXME: Our choice of AST representation here is less than ideal.
815 ++Args;
816 --NumArgs;
817 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000818 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000819 IsMemberFunction, TheCall->getRParenLoc(),
820 TheCall->getCallee()->getSourceRange(), CallType);
821
822 IdentifierInfo *FnInfo = FDecl->getIdentifier();
823 // None of the checks below are needed for functions that don't have
824 // simple names (e.g., C++ conversion functions).
825 if (!FnInfo)
826 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000827
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000828 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
829
Anna Zaks22122702012-01-17 00:37:07 +0000830 unsigned CMId = FDecl->getMemoryFunctionKind();
831 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000832 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000833
Anna Zaks201d4892012-01-13 21:52:01 +0000834 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000835 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000836 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000837 else if (CMId == Builtin::BIstrncat)
838 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000839 else
Anna Zaks22122702012-01-17 00:37:07 +0000840 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000841
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000842 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000843}
844
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000845bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000846 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000847 VariadicCallType CallType =
848 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000849
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000850 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000851 /*IsMemberFunction=*/false,
852 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000853
854 return false;
855}
856
Richard Trieu664c4c62013-06-20 21:03:13 +0000857bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
858 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000859 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
860 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000861 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000862
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000863 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000864 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000865 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000866
Richard Trieu664c4c62013-06-20 21:03:13 +0000867 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000868 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000869 CallType = VariadicDoesNotApply;
870 } else if (Ty->isBlockPointerType()) {
871 CallType = VariadicBlock;
872 } else { // Ty->isFunctionPointerType()
873 CallType = VariadicFunction;
874 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000875 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000876
Alp Toker9cacbab2014-01-20 20:26:09 +0000877 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
878 TheCall->getNumArgs()),
879 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000880 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000881
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000882 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000883}
884
Richard Trieu41bc0992013-06-22 00:20:41 +0000885/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
886/// such as function pointers returned from functions.
887bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000888 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +0000889 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000890 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000891
Craig Topperc3ec1492014-05-26 06:22:03 +0000892 checkCall(/*FDecl=*/nullptr,
893 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
894 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +0000895 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000896 TheCall->getCallee()->getSourceRange(), CallType);
897
898 return false;
899}
900
Tim Northovere94a34c2014-03-11 10:49:14 +0000901static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
902 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
903 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
904 return false;
905
906 switch (Op) {
907 case AtomicExpr::AO__c11_atomic_init:
908 llvm_unreachable("There is no ordering argument for an init");
909
910 case AtomicExpr::AO__c11_atomic_load:
911 case AtomicExpr::AO__atomic_load_n:
912 case AtomicExpr::AO__atomic_load:
913 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
914 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
915
916 case AtomicExpr::AO__c11_atomic_store:
917 case AtomicExpr::AO__atomic_store:
918 case AtomicExpr::AO__atomic_store_n:
919 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
920 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
921 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
922
923 default:
924 return true;
925 }
926}
927
Richard Smithfeea8832012-04-12 05:08:17 +0000928ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
929 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000930 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
931 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000932
Richard Smithfeea8832012-04-12 05:08:17 +0000933 // All these operations take one of the following forms:
934 enum {
935 // C __c11_atomic_init(A *, C)
936 Init,
937 // C __c11_atomic_load(A *, int)
938 Load,
939 // void __atomic_load(A *, CP, int)
940 Copy,
941 // C __c11_atomic_add(A *, M, int)
942 Arithmetic,
943 // C __atomic_exchange_n(A *, CP, int)
944 Xchg,
945 // void __atomic_exchange(A *, C *, CP, int)
946 GNUXchg,
947 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
948 C11CmpXchg,
949 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
950 GNUCmpXchg
951 } Form = Init;
952 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
953 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
954 // where:
955 // C is an appropriate type,
956 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
957 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
958 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
959 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000960
Richard Smithfeea8832012-04-12 05:08:17 +0000961 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
962 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
963 && "need to update code for modified C11 atomics");
964 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
965 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
966 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
967 Op == AtomicExpr::AO__atomic_store_n ||
968 Op == AtomicExpr::AO__atomic_exchange_n ||
969 Op == AtomicExpr::AO__atomic_compare_exchange_n;
970 bool IsAddSub = false;
971
972 switch (Op) {
973 case AtomicExpr::AO__c11_atomic_init:
974 Form = Init;
975 break;
976
977 case AtomicExpr::AO__c11_atomic_load:
978 case AtomicExpr::AO__atomic_load_n:
979 Form = Load;
980 break;
981
982 case AtomicExpr::AO__c11_atomic_store:
983 case AtomicExpr::AO__atomic_load:
984 case AtomicExpr::AO__atomic_store:
985 case AtomicExpr::AO__atomic_store_n:
986 Form = Copy;
987 break;
988
989 case AtomicExpr::AO__c11_atomic_fetch_add:
990 case AtomicExpr::AO__c11_atomic_fetch_sub:
991 case AtomicExpr::AO__atomic_fetch_add:
992 case AtomicExpr::AO__atomic_fetch_sub:
993 case AtomicExpr::AO__atomic_add_fetch:
994 case AtomicExpr::AO__atomic_sub_fetch:
995 IsAddSub = true;
996 // Fall through.
997 case AtomicExpr::AO__c11_atomic_fetch_and:
998 case AtomicExpr::AO__c11_atomic_fetch_or:
999 case AtomicExpr::AO__c11_atomic_fetch_xor:
1000 case AtomicExpr::AO__atomic_fetch_and:
1001 case AtomicExpr::AO__atomic_fetch_or:
1002 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001003 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001004 case AtomicExpr::AO__atomic_and_fetch:
1005 case AtomicExpr::AO__atomic_or_fetch:
1006 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001007 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001008 Form = Arithmetic;
1009 break;
1010
1011 case AtomicExpr::AO__c11_atomic_exchange:
1012 case AtomicExpr::AO__atomic_exchange_n:
1013 Form = Xchg;
1014 break;
1015
1016 case AtomicExpr::AO__atomic_exchange:
1017 Form = GNUXchg;
1018 break;
1019
1020 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1021 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1022 Form = C11CmpXchg;
1023 break;
1024
1025 case AtomicExpr::AO__atomic_compare_exchange:
1026 case AtomicExpr::AO__atomic_compare_exchange_n:
1027 Form = GNUCmpXchg;
1028 break;
1029 }
1030
1031 // Check we have the right number of arguments.
1032 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001033 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001034 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001035 << TheCall->getCallee()->getSourceRange();
1036 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001037 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1038 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001039 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001040 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001041 << TheCall->getCallee()->getSourceRange();
1042 return ExprError();
1043 }
1044
Richard Smithfeea8832012-04-12 05:08:17 +00001045 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001046 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001047 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1048 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1049 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001050 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001051 << Ptr->getType() << Ptr->getSourceRange();
1052 return ExprError();
1053 }
1054
Richard Smithfeea8832012-04-12 05:08:17 +00001055 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1056 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1057 QualType ValType = AtomTy; // 'C'
1058 if (IsC11) {
1059 if (!AtomTy->isAtomicType()) {
1060 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1061 << Ptr->getType() << Ptr->getSourceRange();
1062 return ExprError();
1063 }
Richard Smithe00921a2012-09-15 06:09:58 +00001064 if (AtomTy.isConstQualified()) {
1065 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1066 << Ptr->getType() << Ptr->getSourceRange();
1067 return ExprError();
1068 }
Richard Smithfeea8832012-04-12 05:08:17 +00001069 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001070 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001071
Richard Smithfeea8832012-04-12 05:08:17 +00001072 // For an arithmetic operation, the implied arithmetic must be well-formed.
1073 if (Form == Arithmetic) {
1074 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1075 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1076 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1077 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1078 return ExprError();
1079 }
1080 if (!IsAddSub && !ValType->isIntegerType()) {
1081 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1082 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1083 return ExprError();
1084 }
1085 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1086 // For __atomic_*_n operations, the value type must be a scalar integral or
1087 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001088 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001089 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1090 return ExprError();
1091 }
1092
Eli Friedmanaa769812013-09-11 03:49:34 +00001093 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1094 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001095 // For GNU atomics, require a trivially-copyable type. This is not part of
1096 // the GNU atomics specification, but we enforce it for sanity.
1097 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001098 << Ptr->getType() << Ptr->getSourceRange();
1099 return ExprError();
1100 }
1101
Richard Smithfeea8832012-04-12 05:08:17 +00001102 // FIXME: For any builtin other than a load, the ValType must not be
1103 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001104
1105 switch (ValType.getObjCLifetime()) {
1106 case Qualifiers::OCL_None:
1107 case Qualifiers::OCL_ExplicitNone:
1108 // okay
1109 break;
1110
1111 case Qualifiers::OCL_Weak:
1112 case Qualifiers::OCL_Strong:
1113 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001114 // FIXME: Can this happen? By this point, ValType should be known
1115 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001116 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1117 << ValType << Ptr->getSourceRange();
1118 return ExprError();
1119 }
1120
1121 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001122 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001123 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001124 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001125 ResultType = Context.BoolTy;
1126
Richard Smithfeea8832012-04-12 05:08:17 +00001127 // The type of a parameter passed 'by value'. In the GNU atomics, such
1128 // arguments are actually passed as pointers.
1129 QualType ByValType = ValType; // 'CP'
1130 if (!IsC11 && !IsN)
1131 ByValType = Ptr->getType();
1132
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001133 // The first argument --- the pointer --- has a fixed type; we
1134 // deduce the types of the rest of the arguments accordingly. Walk
1135 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001136 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001137 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001138 if (i < NumVals[Form] + 1) {
1139 switch (i) {
1140 case 1:
1141 // The second argument is the non-atomic operand. For arithmetic, this
1142 // is always passed by value, and for a compare_exchange it is always
1143 // passed by address. For the rest, GNU uses by-address and C11 uses
1144 // by-value.
1145 assert(Form != Load);
1146 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1147 Ty = ValType;
1148 else if (Form == Copy || Form == Xchg)
1149 Ty = ByValType;
1150 else if (Form == Arithmetic)
1151 Ty = Context.getPointerDiffType();
1152 else
1153 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1154 break;
1155 case 2:
1156 // The third argument to compare_exchange / GNU exchange is a
1157 // (pointer to a) desired value.
1158 Ty = ByValType;
1159 break;
1160 case 3:
1161 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1162 Ty = Context.BoolTy;
1163 break;
1164 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001165 } else {
1166 // The order(s) are always converted to int.
1167 Ty = Context.IntTy;
1168 }
Richard Smithfeea8832012-04-12 05:08:17 +00001169
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001170 InitializedEntity Entity =
1171 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001172 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001173 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1174 if (Arg.isInvalid())
1175 return true;
1176 TheCall->setArg(i, Arg.get());
1177 }
1178
Richard Smithfeea8832012-04-12 05:08:17 +00001179 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001180 SmallVector<Expr*, 5> SubExprs;
1181 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001182 switch (Form) {
1183 case Init:
1184 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001185 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001186 break;
1187 case Load:
1188 SubExprs.push_back(TheCall->getArg(1)); // Order
1189 break;
1190 case Copy:
1191 case Arithmetic:
1192 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001193 SubExprs.push_back(TheCall->getArg(2)); // Order
1194 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001195 break;
1196 case GNUXchg:
1197 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1198 SubExprs.push_back(TheCall->getArg(3)); // Order
1199 SubExprs.push_back(TheCall->getArg(1)); // Val1
1200 SubExprs.push_back(TheCall->getArg(2)); // Val2
1201 break;
1202 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001203 SubExprs.push_back(TheCall->getArg(3)); // Order
1204 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001205 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001206 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001207 break;
1208 case GNUCmpXchg:
1209 SubExprs.push_back(TheCall->getArg(4)); // Order
1210 SubExprs.push_back(TheCall->getArg(1)); // Val1
1211 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1212 SubExprs.push_back(TheCall->getArg(2)); // Val2
1213 SubExprs.push_back(TheCall->getArg(3)); // Weak
1214 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001215 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001216
1217 if (SubExprs.size() >= 2 && Form != Init) {
1218 llvm::APSInt Result(32);
1219 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1220 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001221 Diag(SubExprs[1]->getLocStart(),
1222 diag::warn_atomic_op_has_invalid_memory_order)
1223 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001224 }
1225
Fariborz Jahanian615de762013-05-28 17:37:39 +00001226 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1227 SubExprs, ResultType, Op,
1228 TheCall->getRParenLoc());
1229
1230 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1231 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1232 Context.AtomicUsesUnsupportedLibcall(AE))
1233 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1234 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001235
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001236 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001237}
1238
1239
John McCall29ad95b2011-08-27 01:09:30 +00001240/// checkBuiltinArgument - Given a call to a builtin function, perform
1241/// normal type-checking on the given argument, updating the call in
1242/// place. This is useful when a builtin function requires custom
1243/// type-checking for some of its arguments but not necessarily all of
1244/// them.
1245///
1246/// Returns true on error.
1247static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1248 FunctionDecl *Fn = E->getDirectCallee();
1249 assert(Fn && "builtin call without direct callee!");
1250
1251 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1252 InitializedEntity Entity =
1253 InitializedEntity::InitializeParameter(S.Context, Param);
1254
1255 ExprResult Arg = E->getArg(0);
1256 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1257 if (Arg.isInvalid())
1258 return true;
1259
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001260 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001261 return false;
1262}
1263
Chris Lattnerdc046542009-05-08 06:58:22 +00001264/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1265/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1266/// type of its first argument. The main ActOnCallExpr routines have already
1267/// promoted the types of arguments because all of these calls are prototyped as
1268/// void(...).
1269///
1270/// This function goes through and does final semantic checking for these
1271/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001272ExprResult
1273Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001274 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001275 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1276 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1277
1278 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001279 if (TheCall->getNumArgs() < 1) {
1280 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1281 << 0 << 1 << TheCall->getNumArgs()
1282 << TheCall->getCallee()->getSourceRange();
1283 return ExprError();
1284 }
Mike Stump11289f42009-09-09 15:08:12 +00001285
Chris Lattnerdc046542009-05-08 06:58:22 +00001286 // Inspect the first argument of the atomic builtin. This should always be
1287 // a pointer type, whose element is an integral scalar or pointer type.
1288 // Because it is a pointer type, we don't have to worry about any implicit
1289 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001290 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001291 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001292 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1293 if (FirstArgResult.isInvalid())
1294 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001295 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001296 TheCall->setArg(0, FirstArg);
1297
John McCall31168b02011-06-15 23:02:42 +00001298 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1299 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001300 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1301 << FirstArg->getType() << FirstArg->getSourceRange();
1302 return ExprError();
1303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
John McCall31168b02011-06-15 23:02:42 +00001305 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001306 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001307 !ValType->isBlockPointerType()) {
1308 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1309 << FirstArg->getType() << FirstArg->getSourceRange();
1310 return ExprError();
1311 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001312
John McCall31168b02011-06-15 23:02:42 +00001313 switch (ValType.getObjCLifetime()) {
1314 case Qualifiers::OCL_None:
1315 case Qualifiers::OCL_ExplicitNone:
1316 // okay
1317 break;
1318
1319 case Qualifiers::OCL_Weak:
1320 case Qualifiers::OCL_Strong:
1321 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001322 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001323 << ValType << FirstArg->getSourceRange();
1324 return ExprError();
1325 }
1326
John McCallb50451a2011-10-05 07:41:44 +00001327 // Strip any qualifiers off ValType.
1328 ValType = ValType.getUnqualifiedType();
1329
Chandler Carruth3973af72010-07-18 20:54:12 +00001330 // The majority of builtins return a value, but a few have special return
1331 // types, so allow them to override appropriately below.
1332 QualType ResultType = ValType;
1333
Chris Lattnerdc046542009-05-08 06:58:22 +00001334 // We need to figure out which concrete builtin this maps onto. For example,
1335 // __sync_fetch_and_add with a 2 byte object turns into
1336 // __sync_fetch_and_add_2.
1337#define BUILTIN_ROW(x) \
1338 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1339 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattnerdc046542009-05-08 06:58:22 +00001341 static const unsigned BuiltinIndices[][5] = {
1342 BUILTIN_ROW(__sync_fetch_and_add),
1343 BUILTIN_ROW(__sync_fetch_and_sub),
1344 BUILTIN_ROW(__sync_fetch_and_or),
1345 BUILTIN_ROW(__sync_fetch_and_and),
1346 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001347
Chris Lattnerdc046542009-05-08 06:58:22 +00001348 BUILTIN_ROW(__sync_add_and_fetch),
1349 BUILTIN_ROW(__sync_sub_and_fetch),
1350 BUILTIN_ROW(__sync_and_and_fetch),
1351 BUILTIN_ROW(__sync_or_and_fetch),
1352 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001353
Chris Lattnerdc046542009-05-08 06:58:22 +00001354 BUILTIN_ROW(__sync_val_compare_and_swap),
1355 BUILTIN_ROW(__sync_bool_compare_and_swap),
1356 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001357 BUILTIN_ROW(__sync_lock_release),
1358 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001359 };
Mike Stump11289f42009-09-09 15:08:12 +00001360#undef BUILTIN_ROW
1361
Chris Lattnerdc046542009-05-08 06:58:22 +00001362 // Determine the index of the size.
1363 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001364 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001365 case 1: SizeIndex = 0; break;
1366 case 2: SizeIndex = 1; break;
1367 case 4: SizeIndex = 2; break;
1368 case 8: SizeIndex = 3; break;
1369 case 16: SizeIndex = 4; break;
1370 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001371 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1372 << FirstArg->getType() << FirstArg->getSourceRange();
1373 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375
Chris Lattnerdc046542009-05-08 06:58:22 +00001376 // Each of these builtins has one pointer argument, followed by some number of
1377 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1378 // that we ignore. Find out which row of BuiltinIndices to read from as well
1379 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001380 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001381 unsigned BuiltinIndex, NumFixed = 1;
1382 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001383 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001384 case Builtin::BI__sync_fetch_and_add:
1385 case Builtin::BI__sync_fetch_and_add_1:
1386 case Builtin::BI__sync_fetch_and_add_2:
1387 case Builtin::BI__sync_fetch_and_add_4:
1388 case Builtin::BI__sync_fetch_and_add_8:
1389 case Builtin::BI__sync_fetch_and_add_16:
1390 BuiltinIndex = 0;
1391 break;
1392
1393 case Builtin::BI__sync_fetch_and_sub:
1394 case Builtin::BI__sync_fetch_and_sub_1:
1395 case Builtin::BI__sync_fetch_and_sub_2:
1396 case Builtin::BI__sync_fetch_and_sub_4:
1397 case Builtin::BI__sync_fetch_and_sub_8:
1398 case Builtin::BI__sync_fetch_and_sub_16:
1399 BuiltinIndex = 1;
1400 break;
1401
1402 case Builtin::BI__sync_fetch_and_or:
1403 case Builtin::BI__sync_fetch_and_or_1:
1404 case Builtin::BI__sync_fetch_and_or_2:
1405 case Builtin::BI__sync_fetch_and_or_4:
1406 case Builtin::BI__sync_fetch_and_or_8:
1407 case Builtin::BI__sync_fetch_and_or_16:
1408 BuiltinIndex = 2;
1409 break;
1410
1411 case Builtin::BI__sync_fetch_and_and:
1412 case Builtin::BI__sync_fetch_and_and_1:
1413 case Builtin::BI__sync_fetch_and_and_2:
1414 case Builtin::BI__sync_fetch_and_and_4:
1415 case Builtin::BI__sync_fetch_and_and_8:
1416 case Builtin::BI__sync_fetch_and_and_16:
1417 BuiltinIndex = 3;
1418 break;
Mike Stump11289f42009-09-09 15:08:12 +00001419
Douglas Gregor73722482011-11-28 16:30:08 +00001420 case Builtin::BI__sync_fetch_and_xor:
1421 case Builtin::BI__sync_fetch_and_xor_1:
1422 case Builtin::BI__sync_fetch_and_xor_2:
1423 case Builtin::BI__sync_fetch_and_xor_4:
1424 case Builtin::BI__sync_fetch_and_xor_8:
1425 case Builtin::BI__sync_fetch_and_xor_16:
1426 BuiltinIndex = 4;
1427 break;
1428
1429 case Builtin::BI__sync_add_and_fetch:
1430 case Builtin::BI__sync_add_and_fetch_1:
1431 case Builtin::BI__sync_add_and_fetch_2:
1432 case Builtin::BI__sync_add_and_fetch_4:
1433 case Builtin::BI__sync_add_and_fetch_8:
1434 case Builtin::BI__sync_add_and_fetch_16:
1435 BuiltinIndex = 5;
1436 break;
1437
1438 case Builtin::BI__sync_sub_and_fetch:
1439 case Builtin::BI__sync_sub_and_fetch_1:
1440 case Builtin::BI__sync_sub_and_fetch_2:
1441 case Builtin::BI__sync_sub_and_fetch_4:
1442 case Builtin::BI__sync_sub_and_fetch_8:
1443 case Builtin::BI__sync_sub_and_fetch_16:
1444 BuiltinIndex = 6;
1445 break;
1446
1447 case Builtin::BI__sync_and_and_fetch:
1448 case Builtin::BI__sync_and_and_fetch_1:
1449 case Builtin::BI__sync_and_and_fetch_2:
1450 case Builtin::BI__sync_and_and_fetch_4:
1451 case Builtin::BI__sync_and_and_fetch_8:
1452 case Builtin::BI__sync_and_and_fetch_16:
1453 BuiltinIndex = 7;
1454 break;
1455
1456 case Builtin::BI__sync_or_and_fetch:
1457 case Builtin::BI__sync_or_and_fetch_1:
1458 case Builtin::BI__sync_or_and_fetch_2:
1459 case Builtin::BI__sync_or_and_fetch_4:
1460 case Builtin::BI__sync_or_and_fetch_8:
1461 case Builtin::BI__sync_or_and_fetch_16:
1462 BuiltinIndex = 8;
1463 break;
1464
1465 case Builtin::BI__sync_xor_and_fetch:
1466 case Builtin::BI__sync_xor_and_fetch_1:
1467 case Builtin::BI__sync_xor_and_fetch_2:
1468 case Builtin::BI__sync_xor_and_fetch_4:
1469 case Builtin::BI__sync_xor_and_fetch_8:
1470 case Builtin::BI__sync_xor_and_fetch_16:
1471 BuiltinIndex = 9;
1472 break;
Mike Stump11289f42009-09-09 15:08:12 +00001473
Chris Lattnerdc046542009-05-08 06:58:22 +00001474 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001475 case Builtin::BI__sync_val_compare_and_swap_1:
1476 case Builtin::BI__sync_val_compare_and_swap_2:
1477 case Builtin::BI__sync_val_compare_and_swap_4:
1478 case Builtin::BI__sync_val_compare_and_swap_8:
1479 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001480 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001481 NumFixed = 2;
1482 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001483
Chris Lattnerdc046542009-05-08 06:58:22 +00001484 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001485 case Builtin::BI__sync_bool_compare_and_swap_1:
1486 case Builtin::BI__sync_bool_compare_and_swap_2:
1487 case Builtin::BI__sync_bool_compare_and_swap_4:
1488 case Builtin::BI__sync_bool_compare_and_swap_8:
1489 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001490 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001491 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001492 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001493 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001494
1495 case Builtin::BI__sync_lock_test_and_set:
1496 case Builtin::BI__sync_lock_test_and_set_1:
1497 case Builtin::BI__sync_lock_test_and_set_2:
1498 case Builtin::BI__sync_lock_test_and_set_4:
1499 case Builtin::BI__sync_lock_test_and_set_8:
1500 case Builtin::BI__sync_lock_test_and_set_16:
1501 BuiltinIndex = 12;
1502 break;
1503
Chris Lattnerdc046542009-05-08 06:58:22 +00001504 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001505 case Builtin::BI__sync_lock_release_1:
1506 case Builtin::BI__sync_lock_release_2:
1507 case Builtin::BI__sync_lock_release_4:
1508 case Builtin::BI__sync_lock_release_8:
1509 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001510 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001511 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001512 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001513 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001514
1515 case Builtin::BI__sync_swap:
1516 case Builtin::BI__sync_swap_1:
1517 case Builtin::BI__sync_swap_2:
1518 case Builtin::BI__sync_swap_4:
1519 case Builtin::BI__sync_swap_8:
1520 case Builtin::BI__sync_swap_16:
1521 BuiltinIndex = 14;
1522 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001523 }
Mike Stump11289f42009-09-09 15:08:12 +00001524
Chris Lattnerdc046542009-05-08 06:58:22 +00001525 // Now that we know how many fixed arguments we expect, first check that we
1526 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001527 if (TheCall->getNumArgs() < 1+NumFixed) {
1528 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1529 << 0 << 1+NumFixed << TheCall->getNumArgs()
1530 << TheCall->getCallee()->getSourceRange();
1531 return ExprError();
1532 }
Mike Stump11289f42009-09-09 15:08:12 +00001533
Chris Lattner5b9241b2009-05-08 15:36:58 +00001534 // Get the decl for the concrete builtin from this, we can tell what the
1535 // concrete integer type we should convert to is.
1536 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1537 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001538 FunctionDecl *NewBuiltinDecl;
1539 if (NewBuiltinID == BuiltinID)
1540 NewBuiltinDecl = FDecl;
1541 else {
1542 // Perform builtin lookup to avoid redeclaring it.
1543 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1544 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1545 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1546 assert(Res.getFoundDecl());
1547 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001548 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001549 return ExprError();
1550 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001551
John McCallcf142162010-08-07 06:22:56 +00001552 // The first argument --- the pointer --- has a fixed type; we
1553 // deduce the types of the rest of the arguments accordingly. Walk
1554 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001555 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001556 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001557
Chris Lattnerdc046542009-05-08 06:58:22 +00001558 // GCC does an implicit conversion to the pointer or integer ValType. This
1559 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001560 // Initialize the argument.
1561 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1562 ValType, /*consume*/ false);
1563 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001564 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001565 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001566
Chris Lattnerdc046542009-05-08 06:58:22 +00001567 // Okay, we have something that *can* be converted to the right type. Check
1568 // to see if there is a potentially weird extension going on here. This can
1569 // happen when you do an atomic operation on something like an char* and
1570 // pass in 42. The 42 gets converted to char. This is even more strange
1571 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001572 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001573 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001574 }
Mike Stump11289f42009-09-09 15:08:12 +00001575
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001576 ASTContext& Context = this->getASTContext();
1577
1578 // Create a new DeclRefExpr to refer to the new decl.
1579 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1580 Context,
1581 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001582 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001583 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001584 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001585 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001586 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001587 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001588
Chris Lattnerdc046542009-05-08 06:58:22 +00001589 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001590 // FIXME: This loses syntactic information.
1591 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1592 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1593 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001594 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001595
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001596 // Change the result type of the call to match the original value type. This
1597 // is arbitrary, but the codegen for these builtins ins design to handle it
1598 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001599 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001600
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001601 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001602}
1603
Chris Lattner6436fb62009-02-18 06:01:06 +00001604/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001605/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001606/// Note: It might also make sense to do the UTF-16 conversion here (would
1607/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001608bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001609 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001610 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1611
Douglas Gregorfb65e592011-07-27 05:40:30 +00001612 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001613 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1614 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001615 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001616 }
Mike Stump11289f42009-09-09 15:08:12 +00001617
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001618 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001619 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001620 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001621 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001622 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001623 UTF16 *ToPtr = &ToBuf[0];
1624
1625 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1626 &ToPtr, ToPtr + NumBytes,
1627 strictConversion);
1628 // Check for conversion failure.
1629 if (Result != conversionOK)
1630 Diag(Arg->getLocStart(),
1631 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1632 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001633 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001634}
1635
Chris Lattnere202e6a2007-12-20 00:05:45 +00001636/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1637/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001638bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1639 Expr *Fn = TheCall->getCallee();
1640 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001641 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001642 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001643 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1644 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001645 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001646 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001647 return true;
1648 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001649
1650 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001651 return Diag(TheCall->getLocEnd(),
1652 diag::err_typecheck_call_too_few_args_at_least)
1653 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001654 }
1655
John McCall29ad95b2011-08-27 01:09:30 +00001656 // Type-check the first argument normally.
1657 if (checkBuiltinArgument(*this, TheCall, 0))
1658 return true;
1659
Chris Lattnere202e6a2007-12-20 00:05:45 +00001660 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001661 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001662 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001663 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001664 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001665 else if (FunctionDecl *FD = getCurFunctionDecl())
1666 isVariadic = FD->isVariadic();
1667 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001668 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001669
Chris Lattnere202e6a2007-12-20 00:05:45 +00001670 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001671 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1672 return true;
1673 }
Mike Stump11289f42009-09-09 15:08:12 +00001674
Chris Lattner43be2e62007-12-19 23:59:04 +00001675 // Verify that the second argument to the builtin is the last argument of the
1676 // current function or method.
1677 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001678 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001679
Nico Weber9eea7642013-05-24 23:31:57 +00001680 // These are valid if SecondArgIsLastNamedArgument is false after the next
1681 // block.
1682 QualType Type;
1683 SourceLocation ParamLoc;
1684
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001685 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1686 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001687 // FIXME: This isn't correct for methods (results in bogus warning).
1688 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001689 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001690 if (CurBlock)
1691 LastArg = *(CurBlock->TheDecl->param_end()-1);
1692 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001693 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001694 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001695 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001696 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001697
1698 Type = PV->getType();
1699 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001700 }
1701 }
Mike Stump11289f42009-09-09 15:08:12 +00001702
Chris Lattner43be2e62007-12-19 23:59:04 +00001703 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001704 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001705 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001706 else if (Type->isReferenceType()) {
1707 Diag(Arg->getLocStart(),
1708 diag::warn_va_start_of_reference_type_is_undefined);
1709 Diag(ParamLoc, diag::note_parameter_type) << Type;
1710 }
1711
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001712 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001713 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001714}
Chris Lattner43be2e62007-12-19 23:59:04 +00001715
Chris Lattner2da14fb2007-12-20 00:26:33 +00001716/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1717/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001718bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1719 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001720 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001721 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001722 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001723 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001724 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001725 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001726 << SourceRange(TheCall->getArg(2)->getLocStart(),
1727 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001728
John Wiegley01296292011-04-08 18:41:53 +00001729 ExprResult OrigArg0 = TheCall->getArg(0);
1730 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001731
Chris Lattner2da14fb2007-12-20 00:26:33 +00001732 // Do standard promotions between the two arguments, returning their common
1733 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001734 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001735 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1736 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001737
1738 // Make sure any conversions are pushed back into the call; this is
1739 // type safe since unordered compare builtins are declared as "_Bool
1740 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001741 TheCall->setArg(0, OrigArg0.get());
1742 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001743
John Wiegley01296292011-04-08 18:41:53 +00001744 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001745 return false;
1746
Chris Lattner2da14fb2007-12-20 00:26:33 +00001747 // If the common type isn't a real floating type, then the arguments were
1748 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001749 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001750 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001751 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001752 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1753 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001754
Chris Lattner2da14fb2007-12-20 00:26:33 +00001755 return false;
1756}
1757
Benjamin Kramer634fc102010-02-15 22:42:31 +00001758/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1759/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001760/// to check everything. We expect the last argument to be a floating point
1761/// value.
1762bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1763 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001764 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001765 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001766 if (TheCall->getNumArgs() > NumArgs)
1767 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001768 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001769 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001770 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001771 (*(TheCall->arg_end()-1))->getLocEnd());
1772
Benjamin Kramer64aae502010-02-16 10:07:31 +00001773 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001774
Eli Friedman7e4faac2009-08-31 20:06:00 +00001775 if (OrigArg->isTypeDependent())
1776 return false;
1777
Chris Lattner68784ef2010-05-06 05:50:07 +00001778 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001779 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001780 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001781 diag::err_typecheck_call_invalid_unary_fp)
1782 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001783
Chris Lattner68784ef2010-05-06 05:50:07 +00001784 // If this is an implicit conversion from float -> double, remove it.
1785 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1786 Expr *CastArg = Cast->getSubExpr();
1787 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1788 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1789 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00001790 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00001791 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001792 }
1793 }
1794
Eli Friedman7e4faac2009-08-31 20:06:00 +00001795 return false;
1796}
1797
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001798/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1799// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001800ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001801 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001802 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001803 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001804 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1805 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001806
Nate Begemana0110022010-06-08 00:16:34 +00001807 // Determine which of the following types of shufflevector we're checking:
1808 // 1) unary, vector mask: (lhs, mask)
1809 // 2) binary, vector mask: (lhs, rhs, mask)
1810 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1811 QualType resType = TheCall->getArg(0)->getType();
1812 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001813
Douglas Gregorc25f7662009-05-19 22:10:17 +00001814 if (!TheCall->getArg(0)->isTypeDependent() &&
1815 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001816 QualType LHSType = TheCall->getArg(0)->getType();
1817 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001818
Craig Topperbaca3892013-07-29 06:47:04 +00001819 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1820 return ExprError(Diag(TheCall->getLocStart(),
1821 diag::err_shufflevector_non_vector)
1822 << SourceRange(TheCall->getArg(0)->getLocStart(),
1823 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001824
Nate Begemana0110022010-06-08 00:16:34 +00001825 numElements = LHSType->getAs<VectorType>()->getNumElements();
1826 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001827
Nate Begemana0110022010-06-08 00:16:34 +00001828 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1829 // with mask. If so, verify that RHS is an integer vector type with the
1830 // same number of elts as lhs.
1831 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001832 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001833 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001834 return ExprError(Diag(TheCall->getLocStart(),
1835 diag::err_shufflevector_incompatible_vector)
1836 << SourceRange(TheCall->getArg(1)->getLocStart(),
1837 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001838 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001839 return ExprError(Diag(TheCall->getLocStart(),
1840 diag::err_shufflevector_incompatible_vector)
1841 << SourceRange(TheCall->getArg(0)->getLocStart(),
1842 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001843 } else if (numElements != numResElements) {
1844 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001845 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001846 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001847 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001848 }
1849
1850 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001851 if (TheCall->getArg(i)->isTypeDependent() ||
1852 TheCall->getArg(i)->isValueDependent())
1853 continue;
1854
Nate Begemana0110022010-06-08 00:16:34 +00001855 llvm::APSInt Result(32);
1856 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1857 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001858 diag::err_shufflevector_nonconstant_argument)
1859 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001860
Craig Topper50ad5b72013-08-03 17:40:38 +00001861 // Allow -1 which will be translated to undef in the IR.
1862 if (Result.isSigned() && Result.isAllOnesValue())
1863 continue;
1864
Chris Lattner7ab824e2008-08-10 02:05:13 +00001865 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001866 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001867 diag::err_shufflevector_argument_too_large)
1868 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001869 }
1870
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001871 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001872
Chris Lattner7ab824e2008-08-10 02:05:13 +00001873 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001874 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00001875 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001876 }
1877
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001878 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
1879 TheCall->getCallee()->getLocStart(),
1880 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001881}
Chris Lattner43be2e62007-12-19 23:59:04 +00001882
Hal Finkelc4d7c822013-09-18 03:29:45 +00001883/// SemaConvertVectorExpr - Handle __builtin_convertvector
1884ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1885 SourceLocation BuiltinLoc,
1886 SourceLocation RParenLoc) {
1887 ExprValueKind VK = VK_RValue;
1888 ExprObjectKind OK = OK_Ordinary;
1889 QualType DstTy = TInfo->getType();
1890 QualType SrcTy = E->getType();
1891
1892 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1893 return ExprError(Diag(BuiltinLoc,
1894 diag::err_convertvector_non_vector)
1895 << E->getSourceRange());
1896 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1897 return ExprError(Diag(BuiltinLoc,
1898 diag::err_convertvector_non_vector_type));
1899
1900 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1901 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1902 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1903 if (SrcElts != DstElts)
1904 return ExprError(Diag(BuiltinLoc,
1905 diag::err_convertvector_incompatible_vector)
1906 << E->getSourceRange());
1907 }
1908
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001909 return new (Context)
1910 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00001911}
1912
Daniel Dunbarb7257262008-07-21 22:59:13 +00001913/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1914// This is declared to take (const void*, ...) and can take two
1915// optional constant int args.
1916bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001917 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001918
Chris Lattner3b054132008-11-19 05:08:23 +00001919 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001920 return Diag(TheCall->getLocEnd(),
1921 diag::err_typecheck_call_too_many_args_at_most)
1922 << 0 /*function call*/ << 3 << NumArgs
1923 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001924
1925 // Argument 0 is checked for us and the remaining arguments must be
1926 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00001927 for (unsigned i = 1; i != NumArgs; ++i)
1928 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001929 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001930
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001931 return false;
1932}
1933
Eric Christopher8d0c6212010-04-17 02:26:23 +00001934/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1935/// TheCall is a constant expression.
1936bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1937 llvm::APSInt &Result) {
1938 Expr *Arg = TheCall->getArg(ArgNum);
1939 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1940 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1941
1942 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1943
1944 if (!Arg->isIntegerConstantExpr(Result, Context))
1945 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001946 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001947
Chris Lattnerd545ad12009-09-23 06:06:36 +00001948 return false;
1949}
1950
Richard Sandiford28940af2014-04-16 08:47:51 +00001951/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
1952/// TheCall is a constant expression in the range [Low, High].
1953bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
1954 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001955 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001956
1957 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00001958 Expr *Arg = TheCall->getArg(ArgNum);
1959 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001960 return false;
1961
Eric Christopher8d0c6212010-04-17 02:26:23 +00001962 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00001963 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001964 return true;
1965
Richard Sandiford28940af2014-04-16 08:47:51 +00001966 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00001967 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00001968 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001969
1970 return false;
1971}
1972
Eli Friedmanc97d0142009-05-03 06:04:26 +00001973/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001974/// This checks that val is a constant 1.
1975bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1976 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001977 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001978
Eric Christopher8d0c6212010-04-17 02:26:23 +00001979 // TODO: This is less than ideal. Overload this to take a value.
1980 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1981 return true;
1982
1983 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001984 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1985 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1986
1987 return false;
1988}
1989
Richard Smithd7293d72013-08-05 18:49:43 +00001990namespace {
1991enum StringLiteralCheckType {
1992 SLCT_NotALiteral,
1993 SLCT_UncheckedLiteral,
1994 SLCT_CheckedLiteral
1995};
1996}
1997
Richard Smith55ce3522012-06-25 20:30:08 +00001998// Determine if an expression is a string literal or constant string.
1999// If this function returns false on the arguments to a function expecting a
2000// format string, we will usually need to emit a warning.
2001// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002002static StringLiteralCheckType
2003checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2004 bool HasVAListArg, unsigned format_idx,
2005 unsigned firstDataArg, Sema::FormatStringType Type,
2006 Sema::VariadicCallType CallType, bool InFunctionCall,
2007 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002008 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002009 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002010 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002011
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002012 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002013
Richard Smithd7293d72013-08-05 18:49:43 +00002014 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002015 // Technically -Wformat-nonliteral does not warn about this case.
2016 // The behavior of printf and friends in this case is implementation
2017 // dependent. Ideally if the format string cannot be null then
2018 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002019 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002020
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002021 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002022 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002023 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002024 // The expression is a literal if both sub-expressions were, and it was
2025 // completely checked only if both sub-expressions were checked.
2026 const AbstractConditionalOperator *C =
2027 cast<AbstractConditionalOperator>(E);
2028 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002029 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002030 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002031 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002032 if (Left == SLCT_NotALiteral)
2033 return SLCT_NotALiteral;
2034 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002035 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002036 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002037 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002038 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002039 }
2040
2041 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002042 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2043 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002044 }
2045
John McCallc07a0c72011-02-17 10:25:35 +00002046 case Stmt::OpaqueValueExprClass:
2047 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2048 E = src;
2049 goto tryAgain;
2050 }
Richard Smith55ce3522012-06-25 20:30:08 +00002051 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002052
Ted Kremeneka8890832011-02-24 23:03:04 +00002053 case Stmt::PredefinedExprClass:
2054 // While __func__, etc., are technically not string literals, they
2055 // cannot contain format specifiers and thus are not a security
2056 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002057 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002058
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002059 case Stmt::DeclRefExprClass: {
2060 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002061
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002062 // As an exception, do not flag errors for variables binding to
2063 // const string literals.
2064 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2065 bool isConstant = false;
2066 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002067
Richard Smithd7293d72013-08-05 18:49:43 +00002068 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2069 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002070 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002071 isConstant = T.isConstant(S.Context) &&
2072 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002073 } else if (T->isObjCObjectPointerType()) {
2074 // In ObjC, there is usually no "const ObjectPointer" type,
2075 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002076 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002077 }
Mike Stump11289f42009-09-09 15:08:12 +00002078
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002079 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002080 if (const Expr *Init = VD->getAnyInitializer()) {
2081 // Look through initializers like const char c[] = { "foo" }
2082 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2083 if (InitList->isStringLiteralInit())
2084 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2085 }
Richard Smithd7293d72013-08-05 18:49:43 +00002086 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002087 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002088 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002089 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002090 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002091 }
Mike Stump11289f42009-09-09 15:08:12 +00002092
Anders Carlssonb012ca92009-06-28 19:55:58 +00002093 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2094 // special check to see if the format string is a function parameter
2095 // of the function calling the printf function. If the function
2096 // has an attribute indicating it is a printf-like function, then we
2097 // should suppress warnings concerning non-literals being used in a call
2098 // to a vprintf function. For example:
2099 //
2100 // void
2101 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2102 // va_list ap;
2103 // va_start(ap, fmt);
2104 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2105 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002106 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002107 if (HasVAListArg) {
2108 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2109 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2110 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002111 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002112 // adjust for implicit parameter
2113 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2114 if (MD->isInstance())
2115 ++PVIndex;
2116 // We also check if the formats are compatible.
2117 // We can't pass a 'scanf' string to a 'printf' function.
2118 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002119 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002120 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002121 }
2122 }
2123 }
2124 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002125 }
Mike Stump11289f42009-09-09 15:08:12 +00002126
Richard Smith55ce3522012-06-25 20:30:08 +00002127 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002128 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002129
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002130 case Stmt::CallExprClass:
2131 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002132 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002133 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2134 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2135 unsigned ArgIndex = FA->getFormatIdx();
2136 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2137 if (MD->isInstance())
2138 --ArgIndex;
2139 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002140
Richard Smithd7293d72013-08-05 18:49:43 +00002141 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002142 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002143 Type, CallType, InFunctionCall,
2144 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002145 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2146 unsigned BuiltinID = FD->getBuiltinID();
2147 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2148 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2149 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002150 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002151 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002152 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002153 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002154 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002155 }
2156 }
Mike Stump11289f42009-09-09 15:08:12 +00002157
Richard Smith55ce3522012-06-25 20:30:08 +00002158 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002159 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002160 case Stmt::ObjCStringLiteralClass:
2161 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002162 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002163
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002164 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002165 StrE = ObjCFExpr->getString();
2166 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002167 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002168
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002169 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002170 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2171 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002172 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002173 }
Mike Stump11289f42009-09-09 15:08:12 +00002174
Richard Smith55ce3522012-06-25 20:30:08 +00002175 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002176 }
Mike Stump11289f42009-09-09 15:08:12 +00002177
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002178 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002179 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002180 }
2181}
2182
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002183Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002184 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002185 .Case("scanf", FST_Scanf)
2186 .Cases("printf", "printf0", FST_Printf)
2187 .Cases("NSString", "CFString", FST_NSString)
2188 .Case("strftime", FST_Strftime)
2189 .Case("strfmon", FST_Strfmon)
2190 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2191 .Default(FST_Unknown);
2192}
2193
Jordan Rose3e0ec582012-07-19 18:10:23 +00002194/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002195/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002196/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002197bool Sema::CheckFormatArguments(const FormatAttr *Format,
2198 ArrayRef<const Expr *> Args,
2199 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002200 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002201 SourceLocation Loc, SourceRange Range,
2202 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002203 FormatStringInfo FSI;
2204 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002205 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002206 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002207 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002208 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002209}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002210
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002211bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002212 bool HasVAListArg, unsigned format_idx,
2213 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002214 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002215 SourceLocation Loc, SourceRange Range,
2216 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002217 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002218 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002219 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002220 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002221 }
Mike Stump11289f42009-09-09 15:08:12 +00002222
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002223 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002224
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002225 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002226 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002227 // Dynamically generated format strings are difficult to
2228 // automatically vet at compile time. Requiring that format strings
2229 // are string literals: (1) permits the checking of format strings by
2230 // the compiler and thereby (2) can practically remove the source of
2231 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002232
Mike Stump11289f42009-09-09 15:08:12 +00002233 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002234 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002235 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002236 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002237 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002238 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2239 format_idx, firstDataArg, Type, CallType,
2240 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002241 if (CT != SLCT_NotALiteral)
2242 // Literal format string found, check done!
2243 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002244
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002245 // Strftime is particular as it always uses a single 'time' argument,
2246 // so it is safe to pass a non-literal string.
2247 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002248 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002249
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002250 // Do not emit diag when the string param is a macro expansion and the
2251 // format is either NSString or CFString. This is a hack to prevent
2252 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2253 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002254 if (Type == FST_NSString &&
2255 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002256 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002257
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002258 // If there are no arguments specified, warn with -Wformat-security, otherwise
2259 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002260 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002261 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002262 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002263 << OrigFormatExpr->getSourceRange();
2264 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002265 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002266 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002267 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002268 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002269}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002270
Ted Kremenekab278de2010-01-28 23:39:18 +00002271namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002272class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2273protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002274 Sema &S;
2275 const StringLiteral *FExpr;
2276 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002277 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002278 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002279 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002280 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002281 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002282 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002283 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002284 bool usesPositionalArgs;
2285 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002286 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002287 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002288 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002289public:
Ted Kremenek02087932010-07-16 02:11:22 +00002290 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002291 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002292 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002293 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002294 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002295 Sema::VariadicCallType callType,
2296 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002297 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002298 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2299 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002300 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002301 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002302 inFunctionCall(inFunctionCall), CallType(callType),
2303 CheckedVarArgs(CheckedVarArgs) {
2304 CoveredArgs.resize(numDataArgs);
2305 CoveredArgs.reset();
2306 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002307
Ted Kremenek019d2242010-01-29 01:50:07 +00002308 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002309
Ted Kremenek02087932010-07-16 02:11:22 +00002310 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002311 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002312
Jordan Rose92303592012-09-08 04:00:03 +00002313 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002314 const analyze_format_string::FormatSpecifier &FS,
2315 const analyze_format_string::ConversionSpecifier &CS,
2316 const char *startSpecifier, unsigned specifierLen,
2317 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002318
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002319 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002320 const analyze_format_string::FormatSpecifier &FS,
2321 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002322
2323 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002324 const analyze_format_string::ConversionSpecifier &CS,
2325 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002326
Craig Toppere14c0f82014-03-12 04:55:44 +00002327 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002328
Craig Toppere14c0f82014-03-12 04:55:44 +00002329 void HandleInvalidPosition(const char *startSpecifier,
2330 unsigned specifierLen,
2331 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002332
Craig Toppere14c0f82014-03-12 04:55:44 +00002333 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002334
Craig Toppere14c0f82014-03-12 04:55:44 +00002335 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002336
Richard Trieu03cf7b72011-10-28 00:41:25 +00002337 template <typename Range>
2338 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2339 const Expr *ArgumentExpr,
2340 PartialDiagnostic PDiag,
2341 SourceLocation StringLoc,
2342 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002343 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002344
Ted Kremenek02087932010-07-16 02:11:22 +00002345protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002346 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2347 const char *startSpec,
2348 unsigned specifierLen,
2349 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002350
2351 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2352 const char *startSpec,
2353 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002354
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002355 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002356 CharSourceRange getSpecifierRange(const char *startSpecifier,
2357 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002358 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002359
Ted Kremenek5739de72010-01-29 01:06:55 +00002360 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002361
2362 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2363 const analyze_format_string::ConversionSpecifier &CS,
2364 const char *startSpecifier, unsigned specifierLen,
2365 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002366
2367 template <typename Range>
2368 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2369 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002370 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002371};
2372}
2373
Ted Kremenek02087932010-07-16 02:11:22 +00002374SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002375 return OrigFormatExpr->getSourceRange();
2376}
2377
Ted Kremenek02087932010-07-16 02:11:22 +00002378CharSourceRange CheckFormatHandler::
2379getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002380 SourceLocation Start = getLocationOfByte(startSpecifier);
2381 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2382
2383 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002384 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002385
2386 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002387}
2388
Ted Kremenek02087932010-07-16 02:11:22 +00002389SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002390 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002391}
2392
Ted Kremenek02087932010-07-16 02:11:22 +00002393void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2394 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002395 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2396 getLocationOfByte(startSpecifier),
2397 /*IsStringLocation*/true,
2398 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002399}
2400
Jordan Rose92303592012-09-08 04:00:03 +00002401void CheckFormatHandler::HandleInvalidLengthModifier(
2402 const analyze_format_string::FormatSpecifier &FS,
2403 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002404 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002405 using namespace analyze_format_string;
2406
2407 const LengthModifier &LM = FS.getLengthModifier();
2408 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2409
2410 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002411 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002412 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002413 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002414 getLocationOfByte(LM.getStart()),
2415 /*IsStringLocation*/true,
2416 getSpecifierRange(startSpecifier, specifierLen));
2417
2418 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2419 << FixedLM->toString()
2420 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2421
2422 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002423 FixItHint Hint;
2424 if (DiagID == diag::warn_format_nonsensical_length)
2425 Hint = FixItHint::CreateRemoval(LMRange);
2426
2427 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002428 getLocationOfByte(LM.getStart()),
2429 /*IsStringLocation*/true,
2430 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002431 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002432 }
2433}
2434
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002435void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002436 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002437 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002438 using namespace analyze_format_string;
2439
2440 const LengthModifier &LM = FS.getLengthModifier();
2441 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2442
2443 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002444 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002445 if (FixedLM) {
2446 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2447 << LM.toString() << 0,
2448 getLocationOfByte(LM.getStart()),
2449 /*IsStringLocation*/true,
2450 getSpecifierRange(startSpecifier, specifierLen));
2451
2452 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2453 << FixedLM->toString()
2454 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2455
2456 } else {
2457 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2458 << LM.toString() << 0,
2459 getLocationOfByte(LM.getStart()),
2460 /*IsStringLocation*/true,
2461 getSpecifierRange(startSpecifier, specifierLen));
2462 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002463}
2464
2465void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2466 const analyze_format_string::ConversionSpecifier &CS,
2467 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002468 using namespace analyze_format_string;
2469
2470 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002471 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002472 if (FixedCS) {
2473 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2474 << CS.toString() << /*conversion specifier*/1,
2475 getLocationOfByte(CS.getStart()),
2476 /*IsStringLocation*/true,
2477 getSpecifierRange(startSpecifier, specifierLen));
2478
2479 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2480 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2481 << FixedCS->toString()
2482 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2483 } else {
2484 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2485 << CS.toString() << /*conversion specifier*/1,
2486 getLocationOfByte(CS.getStart()),
2487 /*IsStringLocation*/true,
2488 getSpecifierRange(startSpecifier, specifierLen));
2489 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002490}
2491
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002492void CheckFormatHandler::HandlePosition(const char *startPos,
2493 unsigned posLen) {
2494 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2495 getLocationOfByte(startPos),
2496 /*IsStringLocation*/true,
2497 getSpecifierRange(startPos, posLen));
2498}
2499
Ted Kremenekd1668192010-02-27 01:41:03 +00002500void
Ted Kremenek02087932010-07-16 02:11:22 +00002501CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2502 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002503 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2504 << (unsigned) p,
2505 getLocationOfByte(startPos), /*IsStringLocation*/true,
2506 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002507}
2508
Ted Kremenek02087932010-07-16 02:11:22 +00002509void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002510 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002511 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2512 getLocationOfByte(startPos),
2513 /*IsStringLocation*/true,
2514 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002515}
2516
Ted Kremenek02087932010-07-16 02:11:22 +00002517void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002518 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002519 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002520 EmitFormatDiagnostic(
2521 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2522 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2523 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002524 }
Ted Kremenek02087932010-07-16 02:11:22 +00002525}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002526
Jordan Rose58bbe422012-07-19 18:10:08 +00002527// Note that this may return NULL if there was an error parsing or building
2528// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002529const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002530 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002531}
2532
2533void CheckFormatHandler::DoneProcessing() {
2534 // Does the number of data arguments exceed the number of
2535 // format conversions in the format string?
2536 if (!HasVAListArg) {
2537 // Find any arguments that weren't covered.
2538 CoveredArgs.flip();
2539 signed notCoveredArg = CoveredArgs.find_first();
2540 if (notCoveredArg >= 0) {
2541 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002542 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2543 SourceLocation Loc = E->getLocStart();
2544 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2545 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2546 Loc, /*IsStringLocation*/false,
2547 getFormatStringRange());
2548 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002549 }
Ted Kremenek02087932010-07-16 02:11:22 +00002550 }
2551 }
2552}
2553
Ted Kremenekce815422010-07-19 21:25:57 +00002554bool
2555CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2556 SourceLocation Loc,
2557 const char *startSpec,
2558 unsigned specifierLen,
2559 const char *csStart,
2560 unsigned csLen) {
2561
2562 bool keepGoing = true;
2563 if (argIndex < NumDataArgs) {
2564 // Consider the argument coverered, even though the specifier doesn't
2565 // make sense.
2566 CoveredArgs.set(argIndex);
2567 }
2568 else {
2569 // If argIndex exceeds the number of data arguments we
2570 // don't issue a warning because that is just a cascade of warnings (and
2571 // they may have intended '%%' anyway). We don't want to continue processing
2572 // the format string after this point, however, as we will like just get
2573 // gibberish when trying to match arguments.
2574 keepGoing = false;
2575 }
2576
Richard Trieu03cf7b72011-10-28 00:41:25 +00002577 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2578 << StringRef(csStart, csLen),
2579 Loc, /*IsStringLocation*/true,
2580 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002581
2582 return keepGoing;
2583}
2584
Richard Trieu03cf7b72011-10-28 00:41:25 +00002585void
2586CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2587 const char *startSpec,
2588 unsigned specifierLen) {
2589 EmitFormatDiagnostic(
2590 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2591 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2592}
2593
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002594bool
2595CheckFormatHandler::CheckNumArgs(
2596 const analyze_format_string::FormatSpecifier &FS,
2597 const analyze_format_string::ConversionSpecifier &CS,
2598 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2599
2600 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002601 PartialDiagnostic PDiag = FS.usesPositionalArg()
2602 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2603 << (argIndex+1) << NumDataArgs)
2604 : S.PDiag(diag::warn_printf_insufficient_data_args);
2605 EmitFormatDiagnostic(
2606 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2607 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002608 return false;
2609 }
2610 return true;
2611}
2612
Richard Trieu03cf7b72011-10-28 00:41:25 +00002613template<typename Range>
2614void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2615 SourceLocation Loc,
2616 bool IsStringLocation,
2617 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002618 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002619 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002620 Loc, IsStringLocation, StringRange, FixIt);
2621}
2622
2623/// \brief If the format string is not within the funcion call, emit a note
2624/// so that the function call and string are in diagnostic messages.
2625///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002626/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002627/// call and only one diagnostic message will be produced. Otherwise, an
2628/// extra note will be emitted pointing to location of the format string.
2629///
2630/// \param ArgumentExpr the expression that is passed as the format string
2631/// argument in the function call. Used for getting locations when two
2632/// diagnostics are emitted.
2633///
2634/// \param PDiag the callee should already have provided any strings for the
2635/// diagnostic message. This function only adds locations and fixits
2636/// to diagnostics.
2637///
2638/// \param Loc primary location for diagnostic. If two diagnostics are
2639/// required, one will be at Loc and a new SourceLocation will be created for
2640/// the other one.
2641///
2642/// \param IsStringLocation if true, Loc points to the format string should be
2643/// used for the note. Otherwise, Loc points to the argument list and will
2644/// be used with PDiag.
2645///
2646/// \param StringRange some or all of the string to highlight. This is
2647/// templated so it can accept either a CharSourceRange or a SourceRange.
2648///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002649/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002650template<typename Range>
2651void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2652 const Expr *ArgumentExpr,
2653 PartialDiagnostic PDiag,
2654 SourceLocation Loc,
2655 bool IsStringLocation,
2656 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002657 ArrayRef<FixItHint> FixIt) {
2658 if (InFunctionCall) {
2659 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2660 D << StringRange;
2661 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2662 I != E; ++I) {
2663 D << *I;
2664 }
2665 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002666 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2667 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002668
2669 const Sema::SemaDiagnosticBuilder &Note =
2670 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2671 diag::note_format_string_defined);
2672
2673 Note << StringRange;
2674 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2675 I != E; ++I) {
2676 Note << *I;
2677 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002678 }
2679}
2680
Ted Kremenek02087932010-07-16 02:11:22 +00002681//===--- CHECK: Printf format string checking ------------------------------===//
2682
2683namespace {
2684class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002685 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002686public:
2687 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2688 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002689 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002690 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002691 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002692 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002693 Sema::VariadicCallType CallType,
2694 llvm::SmallBitVector &CheckedVarArgs)
2695 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2696 numDataArgs, beg, hasVAListArg, Args,
2697 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2698 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002699 {}
2700
Craig Toppere14c0f82014-03-12 04:55:44 +00002701
Ted Kremenek02087932010-07-16 02:11:22 +00002702 bool HandleInvalidPrintfConversionSpecifier(
2703 const analyze_printf::PrintfSpecifier &FS,
2704 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002705 unsigned specifierLen) override;
2706
Ted Kremenek02087932010-07-16 02:11:22 +00002707 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2708 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002709 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002710 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2711 const char *StartSpecifier,
2712 unsigned SpecifierLen,
2713 const Expr *E);
2714
Ted Kremenek02087932010-07-16 02:11:22 +00002715 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2716 const char *startSpecifier, unsigned specifierLen);
2717 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2718 const analyze_printf::OptionalAmount &Amt,
2719 unsigned type,
2720 const char *startSpecifier, unsigned specifierLen);
2721 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2722 const analyze_printf::OptionalFlag &flag,
2723 const char *startSpecifier, unsigned specifierLen);
2724 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2725 const analyze_printf::OptionalFlag &ignoredFlag,
2726 const analyze_printf::OptionalFlag &flag,
2727 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002728 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002729 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002730
Ted Kremenek02087932010-07-16 02:11:22 +00002731};
2732}
2733
2734bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2735 const analyze_printf::PrintfSpecifier &FS,
2736 const char *startSpecifier,
2737 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002738 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002739 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002740
Ted Kremenekce815422010-07-19 21:25:57 +00002741 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2742 getLocationOfByte(CS.getStart()),
2743 startSpecifier, specifierLen,
2744 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002745}
2746
Ted Kremenek02087932010-07-16 02:11:22 +00002747bool CheckPrintfHandler::HandleAmount(
2748 const analyze_format_string::OptionalAmount &Amt,
2749 unsigned k, const char *startSpecifier,
2750 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002751
2752 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002753 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002754 unsigned argIndex = Amt.getArgIndex();
2755 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002756 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2757 << k,
2758 getLocationOfByte(Amt.getStart()),
2759 /*IsStringLocation*/true,
2760 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002761 // Don't do any more checking. We will just emit
2762 // spurious errors.
2763 return false;
2764 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002765
Ted Kremenek5739de72010-01-29 01:06:55 +00002766 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002767 // Although not in conformance with C99, we also allow the argument to be
2768 // an 'unsigned int' as that is a reasonably safe case. GCC also
2769 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002770 CoveredArgs.set(argIndex);
2771 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002772 if (!Arg)
2773 return false;
2774
Ted Kremenek5739de72010-01-29 01:06:55 +00002775 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002776
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002777 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2778 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002779
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002780 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002781 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002782 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002783 << T << Arg->getSourceRange(),
2784 getLocationOfByte(Amt.getStart()),
2785 /*IsStringLocation*/true,
2786 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002787 // Don't do any more checking. We will just emit
2788 // spurious errors.
2789 return false;
2790 }
2791 }
2792 }
2793 return true;
2794}
Ted Kremenek5739de72010-01-29 01:06:55 +00002795
Tom Careb49ec692010-06-17 19:00:27 +00002796void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002797 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002798 const analyze_printf::OptionalAmount &Amt,
2799 unsigned type,
2800 const char *startSpecifier,
2801 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002802 const analyze_printf::PrintfConversionSpecifier &CS =
2803 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002804
Richard Trieu03cf7b72011-10-28 00:41:25 +00002805 FixItHint fixit =
2806 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2807 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2808 Amt.getConstantLength()))
2809 : FixItHint();
2810
2811 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2812 << type << CS.toString(),
2813 getLocationOfByte(Amt.getStart()),
2814 /*IsStringLocation*/true,
2815 getSpecifierRange(startSpecifier, specifierLen),
2816 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002817}
2818
Ted Kremenek02087932010-07-16 02:11:22 +00002819void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002820 const analyze_printf::OptionalFlag &flag,
2821 const char *startSpecifier,
2822 unsigned specifierLen) {
2823 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002824 const analyze_printf::PrintfConversionSpecifier &CS =
2825 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002826 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2827 << flag.toString() << CS.toString(),
2828 getLocationOfByte(flag.getPosition()),
2829 /*IsStringLocation*/true,
2830 getSpecifierRange(startSpecifier, specifierLen),
2831 FixItHint::CreateRemoval(
2832 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002833}
2834
2835void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002836 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002837 const analyze_printf::OptionalFlag &ignoredFlag,
2838 const analyze_printf::OptionalFlag &flag,
2839 const char *startSpecifier,
2840 unsigned specifierLen) {
2841 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2843 << ignoredFlag.toString() << flag.toString(),
2844 getLocationOfByte(ignoredFlag.getPosition()),
2845 /*IsStringLocation*/true,
2846 getSpecifierRange(startSpecifier, specifierLen),
2847 FixItHint::CreateRemoval(
2848 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002849}
2850
Richard Smith55ce3522012-06-25 20:30:08 +00002851// Determines if the specified is a C++ class or struct containing
2852// a member with the specified name and kind (e.g. a CXXMethodDecl named
2853// "c_str()").
2854template<typename MemberKind>
2855static llvm::SmallPtrSet<MemberKind*, 1>
2856CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2857 const RecordType *RT = Ty->getAs<RecordType>();
2858 llvm::SmallPtrSet<MemberKind*, 1> Results;
2859
2860 if (!RT)
2861 return Results;
2862 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002863 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002864 return Results;
2865
Alp Tokerb6cc5922014-05-03 03:45:55 +00002866 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00002867 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002868 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002869
2870 // We just need to include all members of the right kind turned up by the
2871 // filter, at this point.
2872 if (S.LookupQualifiedName(R, RT->getDecl()))
2873 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2874 NamedDecl *decl = (*I)->getUnderlyingDecl();
2875 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2876 Results.insert(FK);
2877 }
2878 return Results;
2879}
2880
Richard Smith2868a732014-02-28 01:36:39 +00002881/// Check if we could call '.c_str()' on an object.
2882///
2883/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2884/// allow the call, or if it would be ambiguous).
2885bool Sema::hasCStrMethod(const Expr *E) {
2886 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2887 MethodSet Results =
2888 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2889 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2890 MI != ME; ++MI)
2891 if ((*MI)->getMinRequiredArguments() == 0)
2892 return true;
2893 return false;
2894}
2895
Richard Smith55ce3522012-06-25 20:30:08 +00002896// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002897// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002898// Returns true when a c_str() conversion method is found.
2899bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002900 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002901 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2902
2903 MethodSet Results =
2904 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2905
2906 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2907 MI != ME; ++MI) {
2908 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002909 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002910 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002911 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00002912 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00002913 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2914 << "c_str()"
2915 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2916 return true;
2917 }
2918 }
2919
2920 return false;
2921}
2922
Ted Kremenekab278de2010-01-28 23:39:18 +00002923bool
Ted Kremenek02087932010-07-16 02:11:22 +00002924CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002925 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002926 const char *startSpecifier,
2927 unsigned specifierLen) {
2928
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002929 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002930 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002931 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002932
Ted Kremenek6cd69422010-07-19 22:01:06 +00002933 if (FS.consumesDataArgument()) {
2934 if (atFirstArg) {
2935 atFirstArg = false;
2936 usesPositionalArgs = FS.usesPositionalArg();
2937 }
2938 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002939 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2940 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002941 return false;
2942 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002943 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002944
Ted Kremenekd1668192010-02-27 01:41:03 +00002945 // First check if the field width, precision, and conversion specifier
2946 // have matching data arguments.
2947 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2948 startSpecifier, specifierLen)) {
2949 return false;
2950 }
2951
2952 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2953 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002954 return false;
2955 }
2956
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002957 if (!CS.consumesDataArgument()) {
2958 // FIXME: Technically specifying a precision or field width here
2959 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002960 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002961 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002962
Ted Kremenek4a49d982010-02-26 19:18:41 +00002963 // Consume the argument.
2964 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002965 if (argIndex < NumDataArgs) {
2966 // The check to see if the argIndex is valid will come later.
2967 // We set the bit here because we may exit early from this
2968 // function if we encounter some other error.
2969 CoveredArgs.set(argIndex);
2970 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002971
2972 // Check for using an Objective-C specific conversion specifier
2973 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002974 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002975 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2976 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00002977 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002978
Tom Careb49ec692010-06-17 19:00:27 +00002979 // Check for invalid use of field width
2980 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00002981 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00002982 startSpecifier, specifierLen);
2983 }
2984
2985 // Check for invalid use of precision
2986 if (!FS.hasValidPrecision()) {
2987 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2988 startSpecifier, specifierLen);
2989 }
2990
2991 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00002992 if (!FS.hasValidThousandsGroupingPrefix())
2993 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002994 if (!FS.hasValidLeadingZeros())
2995 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2996 if (!FS.hasValidPlusPrefix())
2997 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00002998 if (!FS.hasValidSpacePrefix())
2999 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003000 if (!FS.hasValidAlternativeForm())
3001 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3002 if (!FS.hasValidLeftJustified())
3003 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3004
3005 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003006 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3007 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3008 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003009 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3010 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3011 startSpecifier, specifierLen);
3012
3013 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003014 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003015 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3016 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003017 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003018 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003019 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003020 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3021 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003022
Jordan Rose92303592012-09-08 04:00:03 +00003023 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3024 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3025
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003026 // The remaining checks depend on the data arguments.
3027 if (HasVAListArg)
3028 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003029
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003030 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003031 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003032
Jordan Rose58bbe422012-07-19 18:10:08 +00003033 const Expr *Arg = getDataArg(argIndex);
3034 if (!Arg)
3035 return true;
3036
3037 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003038}
3039
Jordan Roseaee34382012-09-05 22:56:26 +00003040static bool requiresParensToAddCast(const Expr *E) {
3041 // FIXME: We should have a general way to reason about operator
3042 // precedence and whether parens are actually needed here.
3043 // Take care of a few common cases where they aren't.
3044 const Expr *Inside = E->IgnoreImpCasts();
3045 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3046 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3047
3048 switch (Inside->getStmtClass()) {
3049 case Stmt::ArraySubscriptExprClass:
3050 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003051 case Stmt::CharacterLiteralClass:
3052 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003053 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003054 case Stmt::FloatingLiteralClass:
3055 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003056 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003057 case Stmt::ObjCArrayLiteralClass:
3058 case Stmt::ObjCBoolLiteralExprClass:
3059 case Stmt::ObjCBoxedExprClass:
3060 case Stmt::ObjCDictionaryLiteralClass:
3061 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003062 case Stmt::ObjCIvarRefExprClass:
3063 case Stmt::ObjCMessageExprClass:
3064 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003065 case Stmt::ObjCStringLiteralClass:
3066 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003067 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003068 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003069 case Stmt::UnaryOperatorClass:
3070 return false;
3071 default:
3072 return true;
3073 }
3074}
3075
Richard Smith55ce3522012-06-25 20:30:08 +00003076bool
3077CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3078 const char *StartSpecifier,
3079 unsigned SpecifierLen,
3080 const Expr *E) {
3081 using namespace analyze_format_string;
3082 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003083 // Now type check the data expression that matches the
3084 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003085 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3086 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003087 if (!AT.isValid())
3088 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003089
Jordan Rose598ec092012-12-05 18:44:40 +00003090 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003091 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3092 ExprTy = TET->getUnderlyingExpr()->getType();
3093 }
3094
Jordan Rose598ec092012-12-05 18:44:40 +00003095 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003096 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003097
Jordan Rose22b74712012-09-05 22:56:19 +00003098 // Look through argument promotions for our error message's reported type.
3099 // This includes the integral and floating promotions, but excludes array
3100 // and function pointer decay; seeing that an argument intended to be a
3101 // string has type 'char [6]' is probably more confusing than 'char *'.
3102 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3103 if (ICE->getCastKind() == CK_IntegralCast ||
3104 ICE->getCastKind() == CK_FloatingCast) {
3105 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003106 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003107
3108 // Check if we didn't match because of an implicit cast from a 'char'
3109 // or 'short' to an 'int'. This is done because printf is a varargs
3110 // function.
3111 if (ICE->getType() == S.Context.IntTy ||
3112 ICE->getType() == S.Context.UnsignedIntTy) {
3113 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003114 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003115 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003116 }
Jordan Rose98709982012-06-04 22:48:57 +00003117 }
Jordan Rose598ec092012-12-05 18:44:40 +00003118 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3119 // Special case for 'a', which has type 'int' in C.
3120 // Note, however, that we do /not/ want to treat multibyte constants like
3121 // 'MooV' as characters! This form is deprecated but still exists.
3122 if (ExprTy == S.Context.IntTy)
3123 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3124 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003125 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003126
Jordan Rosebc53ed12014-05-31 04:12:14 +00003127 // Look through enums to their underlying type.
3128 bool IsEnum = false;
3129 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3130 ExprTy = EnumTy->getDecl()->getIntegerType();
3131 IsEnum = true;
3132 }
3133
Jordan Rose0e5badd2012-12-05 18:44:49 +00003134 // %C in an Objective-C context prints a unichar, not a wchar_t.
3135 // If the argument is an integer of some kind, believe the %C and suggest
3136 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003137 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003138 if (ObjCContext &&
3139 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3140 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3141 !ExprTy->isCharType()) {
3142 // 'unichar' is defined as a typedef of unsigned short, but we should
3143 // prefer using the typedef if it is visible.
3144 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003145
3146 // While we are here, check if the value is an IntegerLiteral that happens
3147 // to be within the valid range.
3148 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3149 const llvm::APInt &V = IL->getValue();
3150 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3151 return true;
3152 }
3153
Jordan Rose0e5badd2012-12-05 18:44:49 +00003154 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3155 Sema::LookupOrdinaryName);
3156 if (S.LookupName(Result, S.getCurScope())) {
3157 NamedDecl *ND = Result.getFoundDecl();
3158 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3159 if (TD->getUnderlyingType() == IntendedTy)
3160 IntendedTy = S.Context.getTypedefType(TD);
3161 }
3162 }
3163 }
3164
3165 // Special-case some of Darwin's platform-independence types by suggesting
3166 // casts to primitive types that are known to be large enough.
3167 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003168 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003169 // Use a 'while' to peel off layers of typedefs.
3170 QualType TyTy = IntendedTy;
3171 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003172 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003173 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003174 .Case("NSInteger", S.Context.LongTy)
3175 .Case("NSUInteger", S.Context.UnsignedLongTy)
3176 .Case("SInt32", S.Context.IntTy)
3177 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003178 .Default(QualType());
3179
3180 if (!CastTy.isNull()) {
3181 ShouldNotPrintDirectly = true;
3182 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003183 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003184 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003185 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003186 }
3187 }
3188
Jordan Rose22b74712012-09-05 22:56:19 +00003189 // We may be able to offer a FixItHint if it is a supported type.
3190 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003191 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003192 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003193
Jordan Rose22b74712012-09-05 22:56:19 +00003194 if (success) {
3195 // Get the fix string from the fixed format specifier
3196 SmallString<16> buf;
3197 llvm::raw_svector_ostream os(buf);
3198 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003199
Jordan Roseaee34382012-09-05 22:56:26 +00003200 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3201
Jordan Rose0e5badd2012-12-05 18:44:49 +00003202 if (IntendedTy == ExprTy) {
3203 // In this case, the specifier is wrong and should be changed to match
3204 // the argument.
3205 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003206 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3207 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003208 << E->getSourceRange(),
3209 E->getLocStart(),
3210 /*IsStringLocation*/false,
3211 SpecRange,
3212 FixItHint::CreateReplacement(SpecRange, os.str()));
3213
3214 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003215 // The canonical type for formatting this value is different from the
3216 // actual type of the expression. (This occurs, for example, with Darwin's
3217 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3218 // should be printed as 'long' for 64-bit compatibility.)
3219 // Rather than emitting a normal format/argument mismatch, we want to
3220 // add a cast to the recommended type (and correct the format string
3221 // if necessary).
3222 SmallString<16> CastBuf;
3223 llvm::raw_svector_ostream CastFix(CastBuf);
3224 CastFix << "(";
3225 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3226 CastFix << ")";
3227
3228 SmallVector<FixItHint,4> Hints;
3229 if (!AT.matchesType(S.Context, IntendedTy))
3230 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3231
3232 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3233 // If there's already a cast present, just replace it.
3234 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3235 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3236
3237 } else if (!requiresParensToAddCast(E)) {
3238 // If the expression has high enough precedence,
3239 // just write the C-style cast.
3240 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3241 CastFix.str()));
3242 } else {
3243 // Otherwise, add parens around the expression as well as the cast.
3244 CastFix << "(";
3245 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3246 CastFix.str()));
3247
Alp Tokerb6cc5922014-05-03 03:45:55 +00003248 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003249 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3250 }
3251
Jordan Rose0e5badd2012-12-05 18:44:49 +00003252 if (ShouldNotPrintDirectly) {
3253 // The expression has a type that should not be printed directly.
3254 // We extract the name from the typedef because we don't want to show
3255 // the underlying type in the diagnostic.
3256 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003257
Jordan Rose0e5badd2012-12-05 18:44:49 +00003258 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003259 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003260 << E->getSourceRange(),
3261 E->getLocStart(), /*IsStringLocation=*/false,
3262 SpecRange, Hints);
3263 } else {
3264 // In this case, the expression could be printed using a different
3265 // specifier, but we've decided that the specifier is probably correct
3266 // and we should cast instead. Just use the normal warning message.
3267 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003268 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3269 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003270 << E->getSourceRange(),
3271 E->getLocStart(), /*IsStringLocation*/false,
3272 SpecRange, Hints);
3273 }
Jordan Roseaee34382012-09-05 22:56:26 +00003274 }
Jordan Rose22b74712012-09-05 22:56:19 +00003275 } else {
3276 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3277 SpecifierLen);
3278 // Since the warning for passing non-POD types to variadic functions
3279 // was deferred until now, we emit a warning for non-POD
3280 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003281 switch (S.isValidVarArgType(ExprTy)) {
3282 case Sema::VAK_Valid:
3283 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003284 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003285 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3286 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003287 << CSR
3288 << E->getSourceRange(),
3289 E->getLocStart(), /*IsStringLocation*/false, CSR);
3290 break;
3291
3292 case Sema::VAK_Undefined:
3293 EmitFormatDiagnostic(
3294 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003295 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003296 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003297 << CallType
3298 << AT.getRepresentativeTypeName(S.Context)
3299 << CSR
3300 << E->getSourceRange(),
3301 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003302 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003303 break;
3304
3305 case Sema::VAK_Invalid:
3306 if (ExprTy->isObjCObjectType())
3307 EmitFormatDiagnostic(
3308 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3309 << S.getLangOpts().CPlusPlus11
3310 << ExprTy
3311 << CallType
3312 << AT.getRepresentativeTypeName(S.Context)
3313 << CSR
3314 << E->getSourceRange(),
3315 E->getLocStart(), /*IsStringLocation*/false, CSR);
3316 else
3317 // FIXME: If this is an initializer list, suggest removing the braces
3318 // or inserting a cast to the target type.
3319 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3320 << isa<InitListExpr>(E) << ExprTy << CallType
3321 << AT.getRepresentativeTypeName(S.Context)
3322 << E->getSourceRange();
3323 break;
3324 }
3325
3326 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3327 "format string specifier index out of range");
3328 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003329 }
3330
Ted Kremenekab278de2010-01-28 23:39:18 +00003331 return true;
3332}
3333
Ted Kremenek02087932010-07-16 02:11:22 +00003334//===--- CHECK: Scanf format string checking ------------------------------===//
3335
3336namespace {
3337class CheckScanfHandler : public CheckFormatHandler {
3338public:
3339 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3340 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003341 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003342 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003343 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003344 Sema::VariadicCallType CallType,
3345 llvm::SmallBitVector &CheckedVarArgs)
3346 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3347 numDataArgs, beg, hasVAListArg,
3348 Args, formatIdx, inFunctionCall, CallType,
3349 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003350 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003351
3352 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3353 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003354 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003355
3356 bool HandleInvalidScanfConversionSpecifier(
3357 const analyze_scanf::ScanfSpecifier &FS,
3358 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003359 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003360
Craig Toppere14c0f82014-03-12 04:55:44 +00003361 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003362};
Ted Kremenek019d2242010-01-29 01:50:07 +00003363}
Ted Kremenekab278de2010-01-28 23:39:18 +00003364
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003365void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3366 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003367 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3368 getLocationOfByte(end), /*IsStringLocation*/true,
3369 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003370}
3371
Ted Kremenekce815422010-07-19 21:25:57 +00003372bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3373 const analyze_scanf::ScanfSpecifier &FS,
3374 const char *startSpecifier,
3375 unsigned specifierLen) {
3376
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003377 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003378 FS.getConversionSpecifier();
3379
3380 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3381 getLocationOfByte(CS.getStart()),
3382 startSpecifier, specifierLen,
3383 CS.getStart(), CS.getLength());
3384}
3385
Ted Kremenek02087932010-07-16 02:11:22 +00003386bool CheckScanfHandler::HandleScanfSpecifier(
3387 const analyze_scanf::ScanfSpecifier &FS,
3388 const char *startSpecifier,
3389 unsigned specifierLen) {
3390
3391 using namespace analyze_scanf;
3392 using namespace analyze_format_string;
3393
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003394 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003395
Ted Kremenek6cd69422010-07-19 22:01:06 +00003396 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3397 // be used to decide if we are using positional arguments consistently.
3398 if (FS.consumesDataArgument()) {
3399 if (atFirstArg) {
3400 atFirstArg = false;
3401 usesPositionalArgs = FS.usesPositionalArg();
3402 }
3403 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003404 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3405 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003406 return false;
3407 }
Ted Kremenek02087932010-07-16 02:11:22 +00003408 }
3409
3410 // Check if the field with is non-zero.
3411 const OptionalAmount &Amt = FS.getFieldWidth();
3412 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3413 if (Amt.getConstantAmount() == 0) {
3414 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3415 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003416 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3417 getLocationOfByte(Amt.getStart()),
3418 /*IsStringLocation*/true, R,
3419 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003420 }
3421 }
3422
3423 if (!FS.consumesDataArgument()) {
3424 // FIXME: Technically specifying a precision or field width here
3425 // makes no sense. Worth issuing a warning at some point.
3426 return true;
3427 }
3428
3429 // Consume the argument.
3430 unsigned argIndex = FS.getArgIndex();
3431 if (argIndex < NumDataArgs) {
3432 // The check to see if the argIndex is valid will come later.
3433 // We set the bit here because we may exit early from this
3434 // function if we encounter some other error.
3435 CoveredArgs.set(argIndex);
3436 }
3437
Ted Kremenek4407ea42010-07-20 20:04:47 +00003438 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003439 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003440 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3441 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003442 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003443 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003444 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003445 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3446 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003447
Jordan Rose92303592012-09-08 04:00:03 +00003448 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3449 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3450
Ted Kremenek02087932010-07-16 02:11:22 +00003451 // The remaining checks depend on the data arguments.
3452 if (HasVAListArg)
3453 return true;
3454
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003455 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003456 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003457
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003458 // Check that the argument type matches the format specifier.
3459 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003460 if (!Ex)
3461 return true;
3462
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003463 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3464 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003465 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003466 bool success = fixedFS.fixType(Ex->getType(),
3467 Ex->IgnoreImpCasts()->getType(),
3468 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003469
3470 if (success) {
3471 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003472 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003473 llvm::raw_svector_ostream os(buf);
3474 fixedFS.toString(os);
3475
3476 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003477 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3478 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003479 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003480 Ex->getLocStart(),
3481 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003482 getSpecifierRange(startSpecifier, specifierLen),
3483 FixItHint::CreateReplacement(
3484 getSpecifierRange(startSpecifier, specifierLen),
3485 os.str()));
3486 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003487 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003488 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3489 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003490 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003491 Ex->getLocStart(),
3492 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003493 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003494 }
3495 }
3496
Ted Kremenek02087932010-07-16 02:11:22 +00003497 return true;
3498}
3499
3500void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003501 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003502 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003503 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003504 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003505 bool inFunctionCall, VariadicCallType CallType,
3506 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003507
Ted Kremenekab278de2010-01-28 23:39:18 +00003508 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003509 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003510 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003511 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003512 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3513 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003514 return;
3515 }
Ted Kremenek02087932010-07-16 02:11:22 +00003516
Ted Kremenekab278de2010-01-28 23:39:18 +00003517 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003518 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003519 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003520 // Account for cases where the string literal is truncated in a declaration.
3521 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3522 assert(T && "String literal not of constant array type!");
3523 size_t TypeSize = T->getSize().getZExtValue();
3524 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003525 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003526
3527 // Emit a warning if the string literal is truncated and does not contain an
3528 // embedded null character.
3529 if (TypeSize <= StrRef.size() &&
3530 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3531 CheckFormatHandler::EmitFormatDiagnostic(
3532 *this, inFunctionCall, Args[format_idx],
3533 PDiag(diag::warn_printf_format_string_not_null_terminated),
3534 FExpr->getLocStart(),
3535 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3536 return;
3537 }
3538
Ted Kremenekab278de2010-01-28 23:39:18 +00003539 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003540 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003541 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003542 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003543 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3544 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003545 return;
3546 }
Ted Kremenek02087932010-07-16 02:11:22 +00003547
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003548 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003549 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003550 numDataArgs, (Type == FST_NSString),
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::ParsePrintfString(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 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003559 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003560 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003561 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003562
Hans Wennborg23926bd2011-12-15 10:25:47 +00003563 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003564 getLangOpts(),
3565 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003566 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003567 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003568}
3569
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003570//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3571
3572// Returns the related absolute value function that is larger, of 0 if one
3573// does not exist.
3574static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3575 switch (AbsFunction) {
3576 default:
3577 return 0;
3578
3579 case Builtin::BI__builtin_abs:
3580 return Builtin::BI__builtin_labs;
3581 case Builtin::BI__builtin_labs:
3582 return Builtin::BI__builtin_llabs;
3583 case Builtin::BI__builtin_llabs:
3584 return 0;
3585
3586 case Builtin::BI__builtin_fabsf:
3587 return Builtin::BI__builtin_fabs;
3588 case Builtin::BI__builtin_fabs:
3589 return Builtin::BI__builtin_fabsl;
3590 case Builtin::BI__builtin_fabsl:
3591 return 0;
3592
3593 case Builtin::BI__builtin_cabsf:
3594 return Builtin::BI__builtin_cabs;
3595 case Builtin::BI__builtin_cabs:
3596 return Builtin::BI__builtin_cabsl;
3597 case Builtin::BI__builtin_cabsl:
3598 return 0;
3599
3600 case Builtin::BIabs:
3601 return Builtin::BIlabs;
3602 case Builtin::BIlabs:
3603 return Builtin::BIllabs;
3604 case Builtin::BIllabs:
3605 return 0;
3606
3607 case Builtin::BIfabsf:
3608 return Builtin::BIfabs;
3609 case Builtin::BIfabs:
3610 return Builtin::BIfabsl;
3611 case Builtin::BIfabsl:
3612 return 0;
3613
3614 case Builtin::BIcabsf:
3615 return Builtin::BIcabs;
3616 case Builtin::BIcabs:
3617 return Builtin::BIcabsl;
3618 case Builtin::BIcabsl:
3619 return 0;
3620 }
3621}
3622
3623// Returns the argument type of the absolute value function.
3624static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3625 unsigned AbsType) {
3626 if (AbsType == 0)
3627 return QualType();
3628
3629 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3630 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3631 if (Error != ASTContext::GE_None)
3632 return QualType();
3633
3634 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3635 if (!FT)
3636 return QualType();
3637
3638 if (FT->getNumParams() != 1)
3639 return QualType();
3640
3641 return FT->getParamType(0);
3642}
3643
3644// Returns the best absolute value function, or zero, based on type and
3645// current absolute value function.
3646static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3647 unsigned AbsFunctionKind) {
3648 unsigned BestKind = 0;
3649 uint64_t ArgSize = Context.getTypeSize(ArgType);
3650 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3651 Kind = getLargerAbsoluteValueFunction(Kind)) {
3652 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3653 if (Context.getTypeSize(ParamType) >= ArgSize) {
3654 if (BestKind == 0)
3655 BestKind = Kind;
3656 else if (Context.hasSameType(ParamType, ArgType)) {
3657 BestKind = Kind;
3658 break;
3659 }
3660 }
3661 }
3662 return BestKind;
3663}
3664
3665enum AbsoluteValueKind {
3666 AVK_Integer,
3667 AVK_Floating,
3668 AVK_Complex
3669};
3670
3671static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3672 if (T->isIntegralOrEnumerationType())
3673 return AVK_Integer;
3674 if (T->isRealFloatingType())
3675 return AVK_Floating;
3676 if (T->isAnyComplexType())
3677 return AVK_Complex;
3678
3679 llvm_unreachable("Type not integer, floating, or complex");
3680}
3681
3682// Changes the absolute value function to a different type. Preserves whether
3683// the function is a builtin.
3684static unsigned changeAbsFunction(unsigned AbsKind,
3685 AbsoluteValueKind ValueKind) {
3686 switch (ValueKind) {
3687 case AVK_Integer:
3688 switch (AbsKind) {
3689 default:
3690 return 0;
3691 case Builtin::BI__builtin_fabsf:
3692 case Builtin::BI__builtin_fabs:
3693 case Builtin::BI__builtin_fabsl:
3694 case Builtin::BI__builtin_cabsf:
3695 case Builtin::BI__builtin_cabs:
3696 case Builtin::BI__builtin_cabsl:
3697 return Builtin::BI__builtin_abs;
3698 case Builtin::BIfabsf:
3699 case Builtin::BIfabs:
3700 case Builtin::BIfabsl:
3701 case Builtin::BIcabsf:
3702 case Builtin::BIcabs:
3703 case Builtin::BIcabsl:
3704 return Builtin::BIabs;
3705 }
3706 case AVK_Floating:
3707 switch (AbsKind) {
3708 default:
3709 return 0;
3710 case Builtin::BI__builtin_abs:
3711 case Builtin::BI__builtin_labs:
3712 case Builtin::BI__builtin_llabs:
3713 case Builtin::BI__builtin_cabsf:
3714 case Builtin::BI__builtin_cabs:
3715 case Builtin::BI__builtin_cabsl:
3716 return Builtin::BI__builtin_fabsf;
3717 case Builtin::BIabs:
3718 case Builtin::BIlabs:
3719 case Builtin::BIllabs:
3720 case Builtin::BIcabsf:
3721 case Builtin::BIcabs:
3722 case Builtin::BIcabsl:
3723 return Builtin::BIfabsf;
3724 }
3725 case AVK_Complex:
3726 switch (AbsKind) {
3727 default:
3728 return 0;
3729 case Builtin::BI__builtin_abs:
3730 case Builtin::BI__builtin_labs:
3731 case Builtin::BI__builtin_llabs:
3732 case Builtin::BI__builtin_fabsf:
3733 case Builtin::BI__builtin_fabs:
3734 case Builtin::BI__builtin_fabsl:
3735 return Builtin::BI__builtin_cabsf;
3736 case Builtin::BIabs:
3737 case Builtin::BIlabs:
3738 case Builtin::BIllabs:
3739 case Builtin::BIfabsf:
3740 case Builtin::BIfabs:
3741 case Builtin::BIfabsl:
3742 return Builtin::BIcabsf;
3743 }
3744 }
3745 llvm_unreachable("Unable to convert function");
3746}
3747
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003748static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003749 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3750 if (!FnInfo)
3751 return 0;
3752
3753 switch (FDecl->getBuiltinID()) {
3754 default:
3755 return 0;
3756 case Builtin::BI__builtin_abs:
3757 case Builtin::BI__builtin_fabs:
3758 case Builtin::BI__builtin_fabsf:
3759 case Builtin::BI__builtin_fabsl:
3760 case Builtin::BI__builtin_labs:
3761 case Builtin::BI__builtin_llabs:
3762 case Builtin::BI__builtin_cabs:
3763 case Builtin::BI__builtin_cabsf:
3764 case Builtin::BI__builtin_cabsl:
3765 case Builtin::BIabs:
3766 case Builtin::BIlabs:
3767 case Builtin::BIllabs:
3768 case Builtin::BIfabs:
3769 case Builtin::BIfabsf:
3770 case Builtin::BIfabsl:
3771 case Builtin::BIcabs:
3772 case Builtin::BIcabsf:
3773 case Builtin::BIcabsl:
3774 return FDecl->getBuiltinID();
3775 }
3776 llvm_unreachable("Unknown Builtin type");
3777}
3778
3779// If the replacement is valid, emit a note with replacement function.
3780// Additionally, suggest including the proper header if not already included.
3781static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00003782 unsigned AbsKind, QualType ArgType) {
3783 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003784 const char *HeaderName = nullptr;
3785 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003786 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3787 FunctionName = "std::abs";
3788 if (ArgType->isIntegralOrEnumerationType()) {
3789 HeaderName = "cstdlib";
3790 } else if (ArgType->isRealFloatingType()) {
3791 HeaderName = "cmath";
3792 } else {
3793 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003794 }
Richard Trieubeffb832014-04-15 23:47:53 +00003795
3796 // Lookup all std::abs
3797 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00003798 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00003799 R.suppressDiagnostics();
3800 S.LookupQualifiedName(R, Std);
3801
3802 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003803 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003804 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3805 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3806 } else {
3807 FDecl = dyn_cast<FunctionDecl>(I);
3808 }
3809 if (!FDecl)
3810 continue;
3811
3812 // Found std::abs(), check that they are the right ones.
3813 if (FDecl->getNumParams() != 1)
3814 continue;
3815
3816 // Check that the parameter type can handle the argument.
3817 QualType ParamType = FDecl->getParamDecl(0)->getType();
3818 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3819 S.Context.getTypeSize(ArgType) <=
3820 S.Context.getTypeSize(ParamType)) {
3821 // Found a function, don't need the header hint.
3822 EmitHeaderHint = false;
3823 break;
3824 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003825 }
Richard Trieubeffb832014-04-15 23:47:53 +00003826 }
3827 } else {
3828 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3829 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3830
3831 if (HeaderName) {
3832 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3833 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3834 R.suppressDiagnostics();
3835 S.LookupName(R, S.getCurScope());
3836
3837 if (R.isSingleResult()) {
3838 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3839 if (FD && FD->getBuiltinID() == AbsKind) {
3840 EmitHeaderHint = false;
3841 } else {
3842 return;
3843 }
3844 } else if (!R.empty()) {
3845 return;
3846 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003847 }
3848 }
3849
3850 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00003851 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003852
Richard Trieubeffb832014-04-15 23:47:53 +00003853 if (!HeaderName)
3854 return;
3855
3856 if (!EmitHeaderHint)
3857 return;
3858
3859 S.Diag(Loc, diag::note_please_include_header) << HeaderName << FunctionName;
3860}
3861
3862static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3863 if (!FDecl)
3864 return false;
3865
3866 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
3867 return false;
3868
3869 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
3870
3871 while (ND && ND->isInlineNamespace()) {
3872 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003873 }
Richard Trieubeffb832014-04-15 23:47:53 +00003874
3875 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
3876 return false;
3877
3878 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
3879 return false;
3880
3881 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003882}
3883
3884// Warn when using the wrong abs() function.
3885void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3886 const FunctionDecl *FDecl,
3887 IdentifierInfo *FnInfo) {
3888 if (Call->getNumArgs() != 1)
3889 return;
3890
3891 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00003892 bool IsStdAbs = IsFunctionStdAbs(FDecl);
3893 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003894 return;
3895
3896 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3897 QualType ParamType = Call->getArg(0)->getType();
3898
3899 // Unsigned types can not be negative. Suggest to drop the absolute value
3900 // function.
3901 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00003902 const char *FunctionName =
3903 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003904 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3905 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00003906 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003907 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3908 return;
3909 }
3910
Richard Trieubeffb832014-04-15 23:47:53 +00003911 // std::abs has overloads which prevent most of the absolute value problems
3912 // from occurring.
3913 if (IsStdAbs)
3914 return;
3915
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003916 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3917 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3918
3919 // The argument and parameter are the same kind. Check if they are the right
3920 // size.
3921 if (ArgValueKind == ParamValueKind) {
3922 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3923 return;
3924
3925 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3926 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3927 << FDecl << ArgType << ParamType;
3928
3929 if (NewAbsKind == 0)
3930 return;
3931
3932 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003933 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003934 return;
3935 }
3936
3937 // ArgValueKind != ParamValueKind
3938 // The wrong type of absolute value function was used. Attempt to find the
3939 // proper one.
3940 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3941 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3942 if (NewAbsKind == 0)
3943 return;
3944
3945 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3946 << FDecl << ParamValueKind << ArgValueKind;
3947
3948 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003949 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003950 return;
3951}
3952
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003953//===--- CHECK: Standard memory functions ---------------------------------===//
3954
Nico Weber0e6daef2013-12-26 23:38:39 +00003955/// \brief Takes the expression passed to the size_t parameter of functions
3956/// such as memcmp, strncat, etc and warns if it's a comparison.
3957///
3958/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3959static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3960 IdentifierInfo *FnName,
3961 SourceLocation FnLoc,
3962 SourceLocation RParenLoc) {
3963 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3964 if (!Size)
3965 return false;
3966
3967 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3968 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3969 return false;
3970
Nico Weber0e6daef2013-12-26 23:38:39 +00003971 SourceRange SizeRange = Size->getSourceRange();
3972 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3973 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00003974 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00003975 << FnName << FixItHint::CreateInsertion(
3976 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00003977 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00003978 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00003979 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00003980 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
3981 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00003982
3983 return true;
3984}
3985
Douglas Gregora74926b2011-05-03 20:05:22 +00003986/// \brief Determine whether the given type is a dynamic class type (e.g.,
3987/// whether it has a vtable).
3988static bool isDynamicClassType(QualType T) {
3989 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3990 if (CXXRecordDecl *Definition = Record->getDefinition())
3991 if (Definition->isDynamicClass())
3992 return true;
3993
3994 return false;
3995}
3996
Chandler Carruth889ed862011-06-21 23:04:20 +00003997/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003998/// otherwise returns NULL.
3999static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004000 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004001 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4002 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4003 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004004
Craig Topperc3ec1492014-05-26 06:22:03 +00004005 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004006}
4007
Chandler Carruth889ed862011-06-21 23:04:20 +00004008/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004009static QualType getSizeOfArgType(const Expr* E) {
4010 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4011 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4012 if (SizeOf->getKind() == clang::UETT_SizeOf)
4013 return SizeOf->getTypeOfArgument();
4014
4015 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004016}
4017
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004018/// \brief Check for dangerous or invalid arguments to memset().
4019///
Chandler Carruthac687262011-06-03 06:23:57 +00004020/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004021/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4022/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004023///
4024/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004025void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004026 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004027 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004028 assert(BId != 0);
4029
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004030 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004031 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004032 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004033 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004034 return;
4035
Anna Zaks22122702012-01-17 00:37:07 +00004036 unsigned LastArg = (BId == Builtin::BImemset ||
4037 BId == Builtin::BIstrndup ? 1 : 2);
4038 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004039 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004040
Nico Weber0e6daef2013-12-26 23:38:39 +00004041 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4042 Call->getLocStart(), Call->getRParenLoc()))
4043 return;
4044
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004045 // We have special checking when the length is a sizeof expression.
4046 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4047 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4048 llvm::FoldingSetNodeID SizeOfArgID;
4049
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004050 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4051 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004052 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004053
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004054 QualType DestTy = Dest->getType();
4055 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4056 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004057
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004058 // Never warn about void type pointers. This can be used to suppress
4059 // false positives.
4060 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004061 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004062
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004063 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4064 // actually comparing the expressions for equality. Because computing the
4065 // expression IDs can be expensive, we only do this if the diagnostic is
4066 // enabled.
4067 if (SizeOfArg &&
4068 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4069 SizeOfArg->getExprLoc())) {
4070 // We only compute IDs for expressions if the warning is enabled, and
4071 // cache the sizeof arg's ID.
4072 if (SizeOfArgID == llvm::FoldingSetNodeID())
4073 SizeOfArg->Profile(SizeOfArgID, Context, true);
4074 llvm::FoldingSetNodeID DestID;
4075 Dest->Profile(DestID, Context, true);
4076 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004077 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4078 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004079 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004080 StringRef ReadableName = FnName->getName();
4081
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004082 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004083 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004084 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004085 if (!PointeeTy->isIncompleteType() &&
4086 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004087 ActionIdx = 2; // If the pointee's size is sizeof(char),
4088 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004089
4090 // If the function is defined as a builtin macro, do not show macro
4091 // expansion.
4092 SourceLocation SL = SizeOfArg->getExprLoc();
4093 SourceRange DSR = Dest->getSourceRange();
4094 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004095 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004096
4097 if (SM.isMacroArgExpansion(SL)) {
4098 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4099 SL = SM.getSpellingLoc(SL);
4100 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4101 SM.getSpellingLoc(DSR.getEnd()));
4102 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4103 SM.getSpellingLoc(SSR.getEnd()));
4104 }
4105
Anna Zaksd08d9152012-05-30 23:14:52 +00004106 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004107 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004108 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004109 << PointeeTy
4110 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004111 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004112 << SSR);
4113 DiagRuntimeBehavior(SL, SizeOfArg,
4114 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4115 << ActionIdx
4116 << SSR);
4117
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004118 break;
4119 }
4120 }
4121
4122 // Also check for cases where the sizeof argument is the exact same
4123 // type as the memory argument, and where it points to a user-defined
4124 // record type.
4125 if (SizeOfArgTy != QualType()) {
4126 if (PointeeTy->isRecordType() &&
4127 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4128 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4129 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4130 << FnName << SizeOfArgTy << ArgIdx
4131 << PointeeTy << Dest->getSourceRange()
4132 << LenExpr->getSourceRange());
4133 break;
4134 }
Nico Weberc5e73862011-06-14 16:14:58 +00004135 }
4136
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004137 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00004138 if (isDynamicClassType(PointeeTy)) {
4139
4140 unsigned OperationType = 0;
4141 // "overwritten" if we're warning about the destination for any call
4142 // but memcmp; otherwise a verb appropriate to the call.
4143 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4144 if (BId == Builtin::BImemcpy)
4145 OperationType = 1;
4146 else if(BId == Builtin::BImemmove)
4147 OperationType = 2;
4148 else if (BId == Builtin::BImemcmp)
4149 OperationType = 3;
4150 }
4151
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004152 DiagRuntimeBehavior(
4153 Dest->getExprLoc(), Dest,
4154 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004155 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00004156 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00004157 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004158 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004159 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4160 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004161 DiagRuntimeBehavior(
4162 Dest->getExprLoc(), Dest,
4163 PDiag(diag::warn_arc_object_memaccess)
4164 << ArgIdx << FnName << PointeeTy
4165 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004166 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004167 continue;
John McCall31168b02011-06-15 23:02:42 +00004168
4169 DiagRuntimeBehavior(
4170 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004171 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004172 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4173 break;
4174 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004175 }
4176}
4177
Ted Kremenek6865f772011-08-18 20:55:45 +00004178// A little helper routine: ignore addition and subtraction of integer literals.
4179// This intentionally does not ignore all integer constant expressions because
4180// we don't want to remove sizeof().
4181static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4182 Ex = Ex->IgnoreParenCasts();
4183
4184 for (;;) {
4185 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4186 if (!BO || !BO->isAdditiveOp())
4187 break;
4188
4189 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4190 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4191
4192 if (isa<IntegerLiteral>(RHS))
4193 Ex = LHS;
4194 else if (isa<IntegerLiteral>(LHS))
4195 Ex = RHS;
4196 else
4197 break;
4198 }
4199
4200 return Ex;
4201}
4202
Anna Zaks13b08572012-08-08 21:42:23 +00004203static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4204 ASTContext &Context) {
4205 // Only handle constant-sized or VLAs, but not flexible members.
4206 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4207 // Only issue the FIXIT for arrays of size > 1.
4208 if (CAT->getSize().getSExtValue() <= 1)
4209 return false;
4210 } else if (!Ty->isVariableArrayType()) {
4211 return false;
4212 }
4213 return true;
4214}
4215
Ted Kremenek6865f772011-08-18 20:55:45 +00004216// Warn if the user has made the 'size' argument to strlcpy or strlcat
4217// be the size of the source, instead of the destination.
4218void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4219 IdentifierInfo *FnName) {
4220
4221 // Don't crash if the user has the wrong number of arguments
4222 if (Call->getNumArgs() != 3)
4223 return;
4224
4225 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4226 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004227 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004228
4229 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4230 Call->getLocStart(), Call->getRParenLoc()))
4231 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004232
4233 // Look for 'strlcpy(dst, x, sizeof(x))'
4234 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4235 CompareWithSrc = Ex;
4236 else {
4237 // Look for 'strlcpy(dst, x, strlen(x))'
4238 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004239 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4240 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004241 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4242 }
4243 }
4244
4245 if (!CompareWithSrc)
4246 return;
4247
4248 // Determine if the argument to sizeof/strlen is equal to the source
4249 // argument. In principle there's all kinds of things you could do
4250 // here, for instance creating an == expression and evaluating it with
4251 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4252 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4253 if (!SrcArgDRE)
4254 return;
4255
4256 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4257 if (!CompareWithSrcDRE ||
4258 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4259 return;
4260
4261 const Expr *OriginalSizeArg = Call->getArg(2);
4262 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4263 << OriginalSizeArg->getSourceRange() << FnName;
4264
4265 // Output a FIXIT hint if the destination is an array (rather than a
4266 // pointer to an array). This could be enhanced to handle some
4267 // pointers if we know the actual size, like if DstArg is 'array+2'
4268 // we could say 'sizeof(array)-2'.
4269 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004270 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004271 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004272
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004273 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004274 llvm::raw_svector_ostream OS(sizeString);
4275 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004276 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004277 OS << ")";
4278
4279 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4280 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4281 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004282}
4283
Anna Zaks314cd092012-02-01 19:08:57 +00004284/// Check if two expressions refer to the same declaration.
4285static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4286 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4287 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4288 return D1->getDecl() == D2->getDecl();
4289 return false;
4290}
4291
4292static const Expr *getStrlenExprArg(const Expr *E) {
4293 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4294 const FunctionDecl *FD = CE->getDirectCallee();
4295 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004296 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004297 return CE->getArg(0)->IgnoreParenCasts();
4298 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004299 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004300}
4301
4302// Warn on anti-patterns as the 'size' argument to strncat.
4303// The correct size argument should look like following:
4304// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4305void Sema::CheckStrncatArguments(const CallExpr *CE,
4306 IdentifierInfo *FnName) {
4307 // Don't crash if the user has the wrong number of arguments.
4308 if (CE->getNumArgs() < 3)
4309 return;
4310 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4311 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4312 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4313
Nico Weber0e6daef2013-12-26 23:38:39 +00004314 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4315 CE->getRParenLoc()))
4316 return;
4317
Anna Zaks314cd092012-02-01 19:08:57 +00004318 // Identify common expressions, which are wrongly used as the size argument
4319 // to strncat and may lead to buffer overflows.
4320 unsigned PatternType = 0;
4321 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4322 // - sizeof(dst)
4323 if (referToTheSameDecl(SizeOfArg, DstArg))
4324 PatternType = 1;
4325 // - sizeof(src)
4326 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4327 PatternType = 2;
4328 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4329 if (BE->getOpcode() == BO_Sub) {
4330 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4331 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4332 // - sizeof(dst) - strlen(dst)
4333 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4334 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4335 PatternType = 1;
4336 // - sizeof(src) - (anything)
4337 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4338 PatternType = 2;
4339 }
4340 }
4341
4342 if (PatternType == 0)
4343 return;
4344
Anna Zaks5069aa32012-02-03 01:27:37 +00004345 // Generate the diagnostic.
4346 SourceLocation SL = LenArg->getLocStart();
4347 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004348 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004349
4350 // If the function is defined as a builtin macro, do not show macro expansion.
4351 if (SM.isMacroArgExpansion(SL)) {
4352 SL = SM.getSpellingLoc(SL);
4353 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4354 SM.getSpellingLoc(SR.getEnd()));
4355 }
4356
Anna Zaks13b08572012-08-08 21:42:23 +00004357 // Check if the destination is an array (rather than a pointer to an array).
4358 QualType DstTy = DstArg->getType();
4359 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4360 Context);
4361 if (!isKnownSizeArray) {
4362 if (PatternType == 1)
4363 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4364 else
4365 Diag(SL, diag::warn_strncat_src_size) << SR;
4366 return;
4367 }
4368
Anna Zaks314cd092012-02-01 19:08:57 +00004369 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004370 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004371 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004372 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004373
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004374 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004375 llvm::raw_svector_ostream OS(sizeString);
4376 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004377 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004378 OS << ") - ";
4379 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004380 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004381 OS << ") - 1";
4382
Anna Zaks5069aa32012-02-03 01:27:37 +00004383 Diag(SL, diag::note_strncat_wrong_size)
4384 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004385}
4386
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004387//===--- CHECK: Return Address of Stack Variable --------------------------===//
4388
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004389static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4390 Decl *ParentDecl);
4391static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4392 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004393
4394/// CheckReturnStackAddr - Check if a return statement returns the address
4395/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004396static void
4397CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4398 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004399
Craig Topperc3ec1492014-05-26 06:22:03 +00004400 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004401 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004402
4403 // Perform checking for returned stack addresses, local blocks,
4404 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004405 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004406 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004407 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004408 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004409 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004410 }
4411
Craig Topperc3ec1492014-05-26 06:22:03 +00004412 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004413 return; // Nothing suspicious was found.
4414
4415 SourceLocation diagLoc;
4416 SourceRange diagRange;
4417 if (refVars.empty()) {
4418 diagLoc = stackE->getLocStart();
4419 diagRange = stackE->getSourceRange();
4420 } else {
4421 // We followed through a reference variable. 'stackE' contains the
4422 // problematic expression but we will warn at the return statement pointing
4423 // at the reference variable. We will later display the "trail" of
4424 // reference variables using notes.
4425 diagLoc = refVars[0]->getLocStart();
4426 diagRange = refVars[0]->getSourceRange();
4427 }
4428
4429 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004430 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004431 : diag::warn_ret_stack_addr)
4432 << DR->getDecl()->getDeclName() << diagRange;
4433 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004434 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004435 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004436 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004437 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004438 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4439 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004440 << diagRange;
4441 }
4442
4443 // Display the "trail" of reference variables that we followed until we
4444 // found the problematic expression using notes.
4445 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4446 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4447 // If this var binds to another reference var, show the range of the next
4448 // var, otherwise the var binds to the problematic expression, in which case
4449 // show the range of the expression.
4450 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4451 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004452 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4453 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004454 }
4455}
4456
4457/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4458/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004459/// to a location on the stack, a local block, an address of a label, or a
4460/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004461/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004462/// encounter a subexpression that (1) clearly does not lead to one of the
4463/// above problematic expressions (2) is something we cannot determine leads to
4464/// a problematic expression based on such local checking.
4465///
4466/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4467/// the expression that they point to. Such variables are added to the
4468/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004469///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004470/// EvalAddr processes expressions that are pointers that are used as
4471/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004472/// At the base case of the recursion is a check for the above problematic
4473/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004474///
4475/// This implementation handles:
4476///
4477/// * pointer-to-pointer casts
4478/// * implicit conversions from array references to pointers
4479/// * taking the address of fields
4480/// * arbitrary interplay between "&" and "*" operators
4481/// * pointer arithmetic from an address of a stack variable
4482/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004483static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4484 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004485 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004486 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004487
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004488 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004489 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004490 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004491 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004492 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004493
Peter Collingbourne91147592011-04-15 00:35:48 +00004494 E = E->IgnoreParens();
4495
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004496 // Our "symbolic interpreter" is just a dispatch off the currently
4497 // viewed AST node. We then recursively traverse the AST by calling
4498 // EvalAddr and EvalVal appropriately.
4499 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004500 case Stmt::DeclRefExprClass: {
4501 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4502
Richard Smith40f08eb2014-01-30 22:05:38 +00004503 // If we leave the immediate function, the lifetime isn't about to end.
4504 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004505 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004506
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004507 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4508 // If this is a reference variable, follow through to the expression that
4509 // it points to.
4510 if (V->hasLocalStorage() &&
4511 V->getType()->isReferenceType() && V->hasInit()) {
4512 // Add the reference variable to the "trail".
4513 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004514 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004515 }
4516
Craig Topperc3ec1492014-05-26 06:22:03 +00004517 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004518 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004519
Chris Lattner934edb22007-12-28 05:31:15 +00004520 case Stmt::UnaryOperatorClass: {
4521 // The only unary operator that make sense to handle here
4522 // is AddrOf. All others don't make sense as pointers.
4523 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004524
John McCalle3027922010-08-25 11:45:40 +00004525 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004526 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004527 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004528 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004529 }
Mike Stump11289f42009-09-09 15:08:12 +00004530
Chris Lattner934edb22007-12-28 05:31:15 +00004531 case Stmt::BinaryOperatorClass: {
4532 // Handle pointer arithmetic. All other binary operators are not valid
4533 // in this context.
4534 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004535 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004536
John McCalle3027922010-08-25 11:45:40 +00004537 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004538 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004539
Chris Lattner934edb22007-12-28 05:31:15 +00004540 Expr *Base = B->getLHS();
4541
4542 // Determine which argument is the real pointer base. It could be
4543 // the RHS argument instead of the LHS.
4544 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004545
Chris Lattner934edb22007-12-28 05:31:15 +00004546 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004547 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004548 }
Steve Naroff2752a172008-09-10 19:17:48 +00004549
Chris Lattner934edb22007-12-28 05:31:15 +00004550 // For conditional operators we need to see if either the LHS or RHS are
4551 // valid DeclRefExpr*s. If one of them is valid, we return it.
4552 case Stmt::ConditionalOperatorClass: {
4553 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004554
Chris Lattner934edb22007-12-28 05:31:15 +00004555 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004556 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4557 if (Expr *LHSExpr = C->getLHS()) {
4558 // In C++, we can have a throw-expression, which has 'void' type.
4559 if (!LHSExpr->getType()->isVoidType())
4560 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004561 return LHS;
4562 }
Chris Lattner934edb22007-12-28 05:31:15 +00004563
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004564 // In C++, we can have a throw-expression, which has 'void' type.
4565 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004566 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004567
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004568 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004569 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004570
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004571 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004572 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004573 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004574 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004575
4576 case Stmt::AddrLabelExprClass:
4577 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004578
John McCall28fc7092011-11-10 05:35:25 +00004579 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004580 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4581 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004582
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004583 // For casts, we need to handle conversions from arrays to
4584 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004585 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004586 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004587 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004588 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004589 case Stmt::CXXStaticCastExprClass:
4590 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004591 case Stmt::CXXConstCastExprClass:
4592 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004593 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4594 switch (cast<CastExpr>(E)->getCastKind()) {
4595 case CK_BitCast:
4596 case CK_LValueToRValue:
4597 case CK_NoOp:
4598 case CK_BaseToDerived:
4599 case CK_DerivedToBase:
4600 case CK_UncheckedDerivedToBase:
4601 case CK_Dynamic:
4602 case CK_CPointerToObjCPointerCast:
4603 case CK_BlockPointerToObjCPointerCast:
4604 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004605 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004606
4607 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004608 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004609
4610 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004611 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004612 }
Chris Lattner934edb22007-12-28 05:31:15 +00004613 }
Mike Stump11289f42009-09-09 15:08:12 +00004614
Douglas Gregorfe314812011-06-21 17:03:29 +00004615 case Stmt::MaterializeTemporaryExprClass:
4616 if (Expr *Result = EvalAddr(
4617 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004618 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004619 return Result;
4620
4621 return E;
4622
Chris Lattner934edb22007-12-28 05:31:15 +00004623 // Everything else: we simply don't reason about them.
4624 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004625 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004626 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004627}
Mike Stump11289f42009-09-09 15:08:12 +00004628
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004629
4630/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4631/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004632static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4633 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004634do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004635 // We should only be called for evaluating non-pointer expressions, or
4636 // expressions with a pointer type that are not used as references but instead
4637 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004638
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004639 // Our "symbolic interpreter" is just a dispatch off the currently
4640 // viewed AST node. We then recursively traverse the AST by calling
4641 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004642
4643 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004644 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004645 case Stmt::ImplicitCastExprClass: {
4646 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004647 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004648 E = IE->getSubExpr();
4649 continue;
4650 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004651 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004652 }
4653
John McCall28fc7092011-11-10 05:35:25 +00004654 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004655 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004656
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004657 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004658 // When we hit a DeclRefExpr we are looking at code that refers to a
4659 // variable's name. If it's not a reference variable we check if it has
4660 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004661 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004662
Richard Smith40f08eb2014-01-30 22:05:38 +00004663 // If we leave the immediate function, the lifetime isn't about to end.
4664 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004665 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004666
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004667 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4668 // Check if it refers to itself, e.g. "int& i = i;".
4669 if (V == ParentDecl)
4670 return DR;
4671
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004672 if (V->hasLocalStorage()) {
4673 if (!V->getType()->isReferenceType())
4674 return DR;
4675
4676 // Reference variable, follow through to the expression that
4677 // it points to.
4678 if (V->hasInit()) {
4679 // Add the reference variable to the "trail".
4680 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004681 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004682 }
4683 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004684 }
Mike Stump11289f42009-09-09 15:08:12 +00004685
Craig Topperc3ec1492014-05-26 06:22:03 +00004686 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004687 }
Mike Stump11289f42009-09-09 15:08:12 +00004688
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004689 case Stmt::UnaryOperatorClass: {
4690 // The only unary operator that make sense to handle here
4691 // is Deref. All others don't resolve to a "name." This includes
4692 // handling all sorts of rvalues passed to a unary operator.
4693 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004694
John McCalle3027922010-08-25 11:45:40 +00004695 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004696 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004697
Craig Topperc3ec1492014-05-26 06:22:03 +00004698 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004699 }
Mike Stump11289f42009-09-09 15:08:12 +00004700
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004701 case Stmt::ArraySubscriptExprClass: {
4702 // Array subscripts are potential references to data on the stack. We
4703 // retrieve the DeclRefExpr* for the array variable if it indeed
4704 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004705 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004706 }
Mike Stump11289f42009-09-09 15:08:12 +00004707
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004708 case Stmt::ConditionalOperatorClass: {
4709 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004710 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004711 ConditionalOperator *C = cast<ConditionalOperator>(E);
4712
Anders Carlsson801c5c72007-11-30 19:04:31 +00004713 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004714 if (Expr *LHSExpr = C->getLHS()) {
4715 // In C++, we can have a throw-expression, which has 'void' type.
4716 if (!LHSExpr->getType()->isVoidType())
4717 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4718 return LHS;
4719 }
4720
4721 // In C++, we can have a throw-expression, which has 'void' type.
4722 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004723 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004724
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004725 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004726 }
Mike Stump11289f42009-09-09 15:08:12 +00004727
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004728 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004729 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004730 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004731
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004732 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004733 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00004734 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004735
4736 // Check whether the member type is itself a reference, in which case
4737 // we're not going to refer to the member, but to what the member refers to.
4738 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004739 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004740
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004741 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004742 }
Mike Stump11289f42009-09-09 15:08:12 +00004743
Douglas Gregorfe314812011-06-21 17:03:29 +00004744 case Stmt::MaterializeTemporaryExprClass:
4745 if (Expr *Result = EvalVal(
4746 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004747 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004748 return Result;
4749
4750 return E;
4751
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004752 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004753 // Check that we don't return or take the address of a reference to a
4754 // temporary. This is only useful in C++.
4755 if (!E->isTypeDependent() && E->isRValue())
4756 return E;
4757
4758 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00004759 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004760 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004761} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004762}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004763
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004764void
4765Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4766 SourceLocation ReturnLoc,
4767 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004768 const AttrVec *Attrs,
4769 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004770 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4771
4772 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004773 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4774 CheckNonNullExpr(*this, RetValExp))
4775 Diag(ReturnLoc, diag::warn_null_ret)
4776 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004777
4778 // C++11 [basic.stc.dynamic.allocation]p4:
4779 // If an allocation function declared with a non-throwing
4780 // exception-specification fails to allocate storage, it shall return
4781 // a null pointer. Any other allocation function that fails to allocate
4782 // storage shall indicate failure only by throwing an exception [...]
4783 if (FD) {
4784 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4785 if (Op == OO_New || Op == OO_Array_New) {
4786 const FunctionProtoType *Proto
4787 = FD->getType()->castAs<FunctionProtoType>();
4788 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4789 CheckNonNullExpr(*this, RetValExp))
4790 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4791 << FD << getLangOpts().CPlusPlus11;
4792 }
4793 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004794}
4795
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004796//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4797
4798/// Check for comparisons of floating point operands using != and ==.
4799/// Issue a warning if these are no self-comparisons, as they are not likely
4800/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004801void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004802 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4803 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004804
4805 // Special case: check for x == x (which is OK).
4806 // Do not emit warnings for such cases.
4807 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4808 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4809 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004810 return;
Mike Stump11289f42009-09-09 15:08:12 +00004811
4812
Ted Kremenekeda40e22007-11-29 00:59:04 +00004813 // Special case: check for comparisons against literals that can be exactly
4814 // represented by APFloat. In such cases, do not emit a warning. This
4815 // is a heuristic: often comparison against such literals are used to
4816 // detect if a value in a variable has not changed. This clearly can
4817 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004818 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4819 if (FLL->isExact())
4820 return;
4821 } else
4822 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4823 if (FLR->isExact())
4824 return;
Mike Stump11289f42009-09-09 15:08:12 +00004825
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004826 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004827 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004828 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004829 return;
Mike Stump11289f42009-09-09 15:08:12 +00004830
David Blaikie1f4ff152012-07-16 20:47:22 +00004831 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004832 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004833 return;
Mike Stump11289f42009-09-09 15:08:12 +00004834
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004835 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004836 Diag(Loc, diag::warn_floatingpoint_eq)
4837 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004838}
John McCallca01b222010-01-04 23:21:16 +00004839
John McCall70aa5392010-01-06 05:24:50 +00004840//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4841//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004842
John McCall70aa5392010-01-06 05:24:50 +00004843namespace {
John McCallca01b222010-01-04 23:21:16 +00004844
John McCall70aa5392010-01-06 05:24:50 +00004845/// Structure recording the 'active' range of an integer-valued
4846/// expression.
4847struct IntRange {
4848 /// The number of bits active in the int.
4849 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004850
John McCall70aa5392010-01-06 05:24:50 +00004851 /// True if the int is known not to have negative values.
4852 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004853
John McCall70aa5392010-01-06 05:24:50 +00004854 IntRange(unsigned Width, bool NonNegative)
4855 : Width(Width), NonNegative(NonNegative)
4856 {}
John McCallca01b222010-01-04 23:21:16 +00004857
John McCall817d4af2010-11-10 23:38:19 +00004858 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004859 static IntRange forBoolType() {
4860 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004861 }
4862
John McCall817d4af2010-11-10 23:38:19 +00004863 /// Returns the range of an opaque value of the given integral type.
4864 static IntRange forValueOfType(ASTContext &C, QualType T) {
4865 return forValueOfCanonicalType(C,
4866 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004867 }
4868
John McCall817d4af2010-11-10 23:38:19 +00004869 /// Returns the range of an opaque value of a canonical integral type.
4870 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004871 assert(T->isCanonicalUnqualified());
4872
4873 if (const VectorType *VT = dyn_cast<VectorType>(T))
4874 T = VT->getElementType().getTypePtr();
4875 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4876 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004877
David Majnemer6a426652013-06-07 22:07:20 +00004878 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004879 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004880 EnumDecl *Enum = ET->getDecl();
4881 if (!Enum->isCompleteDefinition())
4882 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004883
David Majnemer6a426652013-06-07 22:07:20 +00004884 unsigned NumPositive = Enum->getNumPositiveBits();
4885 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004886
David Majnemer6a426652013-06-07 22:07:20 +00004887 if (NumNegative == 0)
4888 return IntRange(NumPositive, true/*NonNegative*/);
4889 else
4890 return IntRange(std::max(NumPositive + 1, NumNegative),
4891 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004892 }
John McCall70aa5392010-01-06 05:24:50 +00004893
4894 const BuiltinType *BT = cast<BuiltinType>(T);
4895 assert(BT->isInteger());
4896
4897 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4898 }
4899
John McCall817d4af2010-11-10 23:38:19 +00004900 /// Returns the "target" range of a canonical integral type, i.e.
4901 /// the range of values expressible in the type.
4902 ///
4903 /// This matches forValueOfCanonicalType except that enums have the
4904 /// full range of their type, not the range of their enumerators.
4905 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4906 assert(T->isCanonicalUnqualified());
4907
4908 if (const VectorType *VT = dyn_cast<VectorType>(T))
4909 T = VT->getElementType().getTypePtr();
4910 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4911 T = CT->getElementType().getTypePtr();
4912 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004913 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004914
4915 const BuiltinType *BT = cast<BuiltinType>(T);
4916 assert(BT->isInteger());
4917
4918 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4919 }
4920
4921 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004922 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004923 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004924 L.NonNegative && R.NonNegative);
4925 }
4926
John McCall817d4af2010-11-10 23:38:19 +00004927 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004928 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004929 return IntRange(std::min(L.Width, R.Width),
4930 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004931 }
4932};
4933
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004934static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4935 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004936 if (value.isSigned() && value.isNegative())
4937 return IntRange(value.getMinSignedBits(), false);
4938
4939 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004940 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004941
4942 // isNonNegative() just checks the sign bit without considering
4943 // signedness.
4944 return IntRange(value.getActiveBits(), true);
4945}
4946
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004947static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4948 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004949 if (result.isInt())
4950 return GetValueRange(C, result.getInt(), MaxWidth);
4951
4952 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004953 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4954 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4955 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4956 R = IntRange::join(R, El);
4957 }
John McCall70aa5392010-01-06 05:24:50 +00004958 return R;
4959 }
4960
4961 if (result.isComplexInt()) {
4962 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4963 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4964 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004965 }
4966
4967 // This can happen with lossless casts to intptr_t of "based" lvalues.
4968 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004969 // FIXME: The only reason we need to pass the type in here is to get
4970 // the sign right on this one case. It would be nice if APValue
4971 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004972 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004973 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004974}
John McCall70aa5392010-01-06 05:24:50 +00004975
Eli Friedmane6d33952013-07-08 20:20:06 +00004976static QualType GetExprType(Expr *E) {
4977 QualType Ty = E->getType();
4978 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4979 Ty = AtomicRHS->getValueType();
4980 return Ty;
4981}
4982
John McCall70aa5392010-01-06 05:24:50 +00004983/// Pseudo-evaluate the given integer expression, estimating the
4984/// range of values it might take.
4985///
4986/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004987static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004988 E = E->IgnoreParens();
4989
4990 // Try a full evaluation first.
4991 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004992 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004993 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004994
4995 // I think we only want to look through implicit casts here; if the
4996 // user has an explicit widening cast, we should treat the value as
4997 // being of the new, wider type.
4998 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004999 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005000 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5001
Eli Friedmane6d33952013-07-08 20:20:06 +00005002 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005003
John McCalle3027922010-08-25 11:45:40 +00005004 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005005
John McCall70aa5392010-01-06 05:24:50 +00005006 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005007 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005008 return OutputTypeRange;
5009
5010 IntRange SubRange
5011 = GetExprRange(C, CE->getSubExpr(),
5012 std::min(MaxWidth, OutputTypeRange.Width));
5013
5014 // Bail out if the subexpr's range is as wide as the cast type.
5015 if (SubRange.Width >= OutputTypeRange.Width)
5016 return OutputTypeRange;
5017
5018 // Otherwise, we take the smaller width, and we're non-negative if
5019 // either the output type or the subexpr is.
5020 return IntRange(SubRange.Width,
5021 SubRange.NonNegative || OutputTypeRange.NonNegative);
5022 }
5023
5024 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5025 // If we can fold the condition, just take that operand.
5026 bool CondResult;
5027 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5028 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5029 : CO->getFalseExpr(),
5030 MaxWidth);
5031
5032 // Otherwise, conservatively merge.
5033 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5034 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5035 return IntRange::join(L, R);
5036 }
5037
5038 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5039 switch (BO->getOpcode()) {
5040
5041 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005042 case BO_LAnd:
5043 case BO_LOr:
5044 case BO_LT:
5045 case BO_GT:
5046 case BO_LE:
5047 case BO_GE:
5048 case BO_EQ:
5049 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005050 return IntRange::forBoolType();
5051
John McCallc3688382011-07-13 06:35:24 +00005052 // The type of the assignments is the type of the LHS, so the RHS
5053 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005054 case BO_MulAssign:
5055 case BO_DivAssign:
5056 case BO_RemAssign:
5057 case BO_AddAssign:
5058 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005059 case BO_XorAssign:
5060 case BO_OrAssign:
5061 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005062 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005063
John McCallc3688382011-07-13 06:35:24 +00005064 // Simple assignments just pass through the RHS, which will have
5065 // been coerced to the LHS type.
5066 case BO_Assign:
5067 // TODO: bitfields?
5068 return GetExprRange(C, BO->getRHS(), MaxWidth);
5069
John McCall70aa5392010-01-06 05:24:50 +00005070 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005071 case BO_PtrMemD:
5072 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005073 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005074
John McCall2ce81ad2010-01-06 22:07:33 +00005075 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005076 case BO_And:
5077 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005078 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5079 GetExprRange(C, BO->getRHS(), MaxWidth));
5080
John McCall70aa5392010-01-06 05:24:50 +00005081 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005082 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005083 // ...except that we want to treat '1 << (blah)' as logically
5084 // positive. It's an important idiom.
5085 if (IntegerLiteral *I
5086 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5087 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005088 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005089 return IntRange(R.Width, /*NonNegative*/ true);
5090 }
5091 }
5092 // fallthrough
5093
John McCalle3027922010-08-25 11:45:40 +00005094 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005095 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005096
John McCall2ce81ad2010-01-06 22:07:33 +00005097 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005098 case BO_Shr:
5099 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005100 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5101
5102 // If the shift amount is a positive constant, drop the width by
5103 // that much.
5104 llvm::APSInt shift;
5105 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5106 shift.isNonNegative()) {
5107 unsigned zext = shift.getZExtValue();
5108 if (zext >= L.Width)
5109 L.Width = (L.NonNegative ? 0 : 1);
5110 else
5111 L.Width -= zext;
5112 }
5113
5114 return L;
5115 }
5116
5117 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005118 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005119 return GetExprRange(C, BO->getRHS(), MaxWidth);
5120
John McCall2ce81ad2010-01-06 22:07:33 +00005121 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005122 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005123 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005124 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005125 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005126
John McCall51431812011-07-14 22:39:48 +00005127 // The width of a division result is mostly determined by the size
5128 // of the LHS.
5129 case BO_Div: {
5130 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005131 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005132 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5133
5134 // If the divisor is constant, use that.
5135 llvm::APSInt divisor;
5136 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5137 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5138 if (log2 >= L.Width)
5139 L.Width = (L.NonNegative ? 0 : 1);
5140 else
5141 L.Width = std::min(L.Width - log2, MaxWidth);
5142 return L;
5143 }
5144
5145 // Otherwise, just use the LHS's width.
5146 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5147 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5148 }
5149
5150 // The result of a remainder can't be larger than the result of
5151 // either side.
5152 case BO_Rem: {
5153 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005154 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005155 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5156 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5157
5158 IntRange meet = IntRange::meet(L, R);
5159 meet.Width = std::min(meet.Width, MaxWidth);
5160 return meet;
5161 }
5162
5163 // The default behavior is okay for these.
5164 case BO_Mul:
5165 case BO_Add:
5166 case BO_Xor:
5167 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005168 break;
5169 }
5170
John McCall51431812011-07-14 22:39:48 +00005171 // The default case is to treat the operation as if it were closed
5172 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005173 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5174 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5175 return IntRange::join(L, R);
5176 }
5177
5178 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5179 switch (UO->getOpcode()) {
5180 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005181 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005182 return IntRange::forBoolType();
5183
5184 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005185 case UO_Deref:
5186 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005187 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005188
5189 default:
5190 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5191 }
5192 }
5193
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005194 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5195 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5196
John McCalld25db7e2013-05-06 21:39:12 +00005197 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005198 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005199 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005200
Eli Friedmane6d33952013-07-08 20:20:06 +00005201 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005202}
John McCall263a48b2010-01-04 23:31:57 +00005203
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005204static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005205 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005206}
5207
John McCall263a48b2010-01-04 23:31:57 +00005208/// Checks whether the given value, which currently has the given
5209/// source semantics, has the same value when coerced through the
5210/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005211static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5212 const llvm::fltSemantics &Src,
5213 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005214 llvm::APFloat truncated = value;
5215
5216 bool ignored;
5217 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5218 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5219
5220 return truncated.bitwiseIsEqual(value);
5221}
5222
5223/// Checks whether the given value, which currently has the given
5224/// source semantics, has the same value when coerced through the
5225/// target semantics.
5226///
5227/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005228static bool IsSameFloatAfterCast(const APValue &value,
5229 const llvm::fltSemantics &Src,
5230 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005231 if (value.isFloat())
5232 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5233
5234 if (value.isVector()) {
5235 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5236 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5237 return false;
5238 return true;
5239 }
5240
5241 assert(value.isComplexFloat());
5242 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5243 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5244}
5245
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005246static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005247
Ted Kremenek6274be42010-09-23 21:43:44 +00005248static bool IsZero(Sema &S, Expr *E) {
5249 // Suppress cases where we are comparing against an enum constant.
5250 if (const DeclRefExpr *DR =
5251 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5252 if (isa<EnumConstantDecl>(DR->getDecl()))
5253 return false;
5254
5255 // Suppress cases where the '0' value is expanded from a macro.
5256 if (E->getLocStart().isMacroID())
5257 return false;
5258
John McCallcc7e5bf2010-05-06 08:58:33 +00005259 llvm::APSInt Value;
5260 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5261}
5262
John McCall2551c1b2010-10-06 00:25:24 +00005263static bool HasEnumType(Expr *E) {
5264 // Strip off implicit integral promotions.
5265 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005266 if (ICE->getCastKind() != CK_IntegralCast &&
5267 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005268 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005269 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005270 }
5271
5272 return E->getType()->isEnumeralType();
5273}
5274
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005275static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005276 // Disable warning in template instantiations.
5277 if (!S.ActiveTemplateInstantiations.empty())
5278 return;
5279
John McCalle3027922010-08-25 11:45:40 +00005280 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005281 if (E->isValueDependent())
5282 return;
5283
John McCalle3027922010-08-25 11:45:40 +00005284 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005285 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005286 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005287 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005288 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005289 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005290 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005291 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005292 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005293 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005294 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005295 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005296 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005297 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005298 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005299 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5300 }
5301}
5302
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005303static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005304 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005305 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005306 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005307 // Disable warning in template instantiations.
5308 if (!S.ActiveTemplateInstantiations.empty())
5309 return;
5310
Richard Trieu0f097742014-04-04 04:13:47 +00005311 // TODO: Investigate using GetExprRange() to get tighter bounds
5312 // on the bit ranges.
5313 QualType OtherT = Other->getType();
5314 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5315 unsigned OtherWidth = OtherRange.Width;
5316
5317 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5318
Richard Trieu560910c2012-11-14 22:50:24 +00005319 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005320 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005321 return;
5322
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005323 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005324 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005325
Richard Trieu0f097742014-04-04 04:13:47 +00005326 // Used for diagnostic printout.
5327 enum {
5328 LiteralConstant = 0,
5329 CXXBoolLiteralTrue,
5330 CXXBoolLiteralFalse
5331 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005332
Richard Trieu0f097742014-04-04 04:13:47 +00005333 if (!OtherIsBooleanType) {
5334 QualType ConstantT = Constant->getType();
5335 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005336
Richard Trieu0f097742014-04-04 04:13:47 +00005337 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5338 return;
5339 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5340 "comparison with non-integer type");
5341
5342 bool ConstantSigned = ConstantT->isSignedIntegerType();
5343 bool CommonSigned = CommonT->isSignedIntegerType();
5344
5345 bool EqualityOnly = false;
5346
5347 if (CommonSigned) {
5348 // The common type is signed, therefore no signed to unsigned conversion.
5349 if (!OtherRange.NonNegative) {
5350 // Check that the constant is representable in type OtherT.
5351 if (ConstantSigned) {
5352 if (OtherWidth >= Value.getMinSignedBits())
5353 return;
5354 } else { // !ConstantSigned
5355 if (OtherWidth >= Value.getActiveBits() + 1)
5356 return;
5357 }
5358 } else { // !OtherSigned
5359 // Check that the constant is representable in type OtherT.
5360 // Negative values are out of range.
5361 if (ConstantSigned) {
5362 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5363 return;
5364 } else { // !ConstantSigned
5365 if (OtherWidth >= Value.getActiveBits())
5366 return;
5367 }
Richard Trieu560910c2012-11-14 22:50:24 +00005368 }
Richard Trieu0f097742014-04-04 04:13:47 +00005369 } else { // !CommonSigned
5370 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005371 if (OtherWidth >= Value.getActiveBits())
5372 return;
Richard Trieu0f097742014-04-04 04:13:47 +00005373 } else if (!OtherRange.NonNegative && !ConstantSigned) {
5374 // Check to see if the constant is representable in OtherT.
5375 if (OtherWidth > Value.getActiveBits())
5376 return;
5377 // Check to see if the constant is equivalent to a negative value
5378 // cast to CommonT.
5379 if (S.Context.getIntWidth(ConstantT) ==
5380 S.Context.getIntWidth(CommonT) &&
5381 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5382 return;
5383 // The constant value rests between values that OtherT can represent
5384 // after conversion. Relational comparison still works, but equality
5385 // comparisons will be tautological.
5386 EqualityOnly = true;
5387 } else { // OtherSigned && ConstantSigned
5388 assert(0 && "Two signed types converted to unsigned types.");
Richard Trieu560910c2012-11-14 22:50:24 +00005389 }
5390 }
Richard Trieu0f097742014-04-04 04:13:47 +00005391
5392 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5393
5394 if (op == BO_EQ || op == BO_NE) {
5395 IsTrue = op == BO_NE;
5396 } else if (EqualityOnly) {
5397 return;
5398 } else if (RhsConstant) {
5399 if (op == BO_GT || op == BO_GE)
5400 IsTrue = !PositiveConstant;
5401 else // op == BO_LT || op == BO_LE
5402 IsTrue = PositiveConstant;
5403 } else {
5404 if (op == BO_LT || op == BO_LE)
5405 IsTrue = !PositiveConstant;
5406 else // op == BO_GT || op == BO_GE
5407 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005408 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005409 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005410 // Other isKnownToHaveBooleanValue
5411 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5412 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5413 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5414
5415 static const struct LinkedConditions {
5416 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5417 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5418 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5419 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5420 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5421 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5422
5423 } TruthTable = {
5424 // Constant on LHS. | Constant on RHS. |
5425 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5426 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5427 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5428 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5429 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5430 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5431 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5432 };
5433
5434 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5435
5436 enum ConstantValue ConstVal = Zero;
5437 if (Value.isUnsigned() || Value.isNonNegative()) {
5438 if (Value == 0) {
5439 LiteralOrBoolConstant =
5440 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5441 ConstVal = Zero;
5442 } else if (Value == 1) {
5443 LiteralOrBoolConstant =
5444 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5445 ConstVal = One;
5446 } else {
5447 LiteralOrBoolConstant = LiteralConstant;
5448 ConstVal = GT_One;
5449 }
5450 } else {
5451 ConstVal = LT_Zero;
5452 }
5453
5454 CompareBoolWithConstantResult CmpRes;
5455
5456 switch (op) {
5457 case BO_LT:
5458 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5459 break;
5460 case BO_GT:
5461 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5462 break;
5463 case BO_LE:
5464 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5465 break;
5466 case BO_GE:
5467 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5468 break;
5469 case BO_EQ:
5470 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5471 break;
5472 case BO_NE:
5473 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5474 break;
5475 default:
5476 CmpRes = Unkwn;
5477 break;
5478 }
5479
5480 if (CmpRes == AFals) {
5481 IsTrue = false;
5482 } else if (CmpRes == ATrue) {
5483 IsTrue = true;
5484 } else {
5485 return;
5486 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005487 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005488
5489 // If this is a comparison to an enum constant, include that
5490 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005491 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005492 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5493 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5494
5495 SmallString<64> PrettySourceValue;
5496 llvm::raw_svector_ostream OS(PrettySourceValue);
5497 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005498 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005499 else
5500 OS << Value;
5501
Richard Trieu0f097742014-04-04 04:13:47 +00005502 S.DiagRuntimeBehavior(
5503 E->getOperatorLoc(), E,
5504 S.PDiag(diag::warn_out_of_range_compare)
5505 << OS.str() << LiteralOrBoolConstant
5506 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5507 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005508}
5509
John McCallcc7e5bf2010-05-06 08:58:33 +00005510/// Analyze the operands of the given comparison. Implements the
5511/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005512static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005513 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5514 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005515}
John McCall263a48b2010-01-04 23:31:57 +00005516
John McCallca01b222010-01-04 23:21:16 +00005517/// \brief Implements -Wsign-compare.
5518///
Richard Trieu82402a02011-09-15 21:56:47 +00005519/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005520static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005521 // The type the comparison is being performed in.
5522 QualType T = E->getLHS()->getType();
5523 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5524 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005525 if (E->isValueDependent())
5526 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005527
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005528 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5529 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005530
5531 bool IsComparisonConstant = false;
5532
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005533 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005534 // of 'true' or 'false'.
5535 if (T->isIntegralType(S.Context)) {
5536 llvm::APSInt RHSValue;
5537 bool IsRHSIntegralLiteral =
5538 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5539 llvm::APSInt LHSValue;
5540 bool IsLHSIntegralLiteral =
5541 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5542 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5543 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5544 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5545 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5546 else
5547 IsComparisonConstant =
5548 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005549 } else if (!T->hasUnsignedIntegerRepresentation())
5550 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005551
John McCallcc7e5bf2010-05-06 08:58:33 +00005552 // We don't do anything special if this isn't an unsigned integral
5553 // comparison: we're only interested in integral comparisons, and
5554 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005555 //
5556 // We also don't care about value-dependent expressions or expressions
5557 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005558 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005559 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005560
John McCallcc7e5bf2010-05-06 08:58:33 +00005561 // Check to see if one of the (unmodified) operands is of different
5562 // signedness.
5563 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005564 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5565 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005566 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005567 signedOperand = LHS;
5568 unsignedOperand = RHS;
5569 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5570 signedOperand = RHS;
5571 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005572 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005573 CheckTrivialUnsignedComparison(S, E);
5574 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005575 }
5576
John McCallcc7e5bf2010-05-06 08:58:33 +00005577 // Otherwise, calculate the effective range of the signed operand.
5578 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005579
John McCallcc7e5bf2010-05-06 08:58:33 +00005580 // Go ahead and analyze implicit conversions in the operands. Note
5581 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005582 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5583 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005584
John McCallcc7e5bf2010-05-06 08:58:33 +00005585 // If the signed range is non-negative, -Wsign-compare won't fire,
5586 // but we should still check for comparisons which are always true
5587 // or false.
5588 if (signedRange.NonNegative)
5589 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005590
5591 // For (in)equality comparisons, if the unsigned operand is a
5592 // constant which cannot collide with a overflowed signed operand,
5593 // then reinterpreting the signed operand as unsigned will not
5594 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005595 if (E->isEqualityOp()) {
5596 unsigned comparisonWidth = S.Context.getIntWidth(T);
5597 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005598
John McCallcc7e5bf2010-05-06 08:58:33 +00005599 // We should never be unable to prove that the unsigned operand is
5600 // non-negative.
5601 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5602
5603 if (unsignedRange.Width < comparisonWidth)
5604 return;
5605 }
5606
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005607 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5608 S.PDiag(diag::warn_mixed_sign_comparison)
5609 << LHS->getType() << RHS->getType()
5610 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005611}
5612
John McCall1f425642010-11-11 03:21:53 +00005613/// Analyzes an attempt to assign the given value to a bitfield.
5614///
5615/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005616static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5617 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005618 assert(Bitfield->isBitField());
5619 if (Bitfield->isInvalidDecl())
5620 return false;
5621
John McCalldeebbcf2010-11-11 05:33:51 +00005622 // White-list bool bitfields.
5623 if (Bitfield->getType()->isBooleanType())
5624 return false;
5625
Douglas Gregor789adec2011-02-04 13:09:01 +00005626 // Ignore value- or type-dependent expressions.
5627 if (Bitfield->getBitWidth()->isValueDependent() ||
5628 Bitfield->getBitWidth()->isTypeDependent() ||
5629 Init->isValueDependent() ||
5630 Init->isTypeDependent())
5631 return false;
5632
John McCall1f425642010-11-11 03:21:53 +00005633 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5634
Richard Smith5fab0c92011-12-28 19:48:30 +00005635 llvm::APSInt Value;
5636 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005637 return false;
5638
John McCall1f425642010-11-11 03:21:53 +00005639 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005640 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005641
5642 if (OriginalWidth <= FieldWidth)
5643 return false;
5644
Eli Friedmanc267a322012-01-26 23:11:39 +00005645 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005646 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005647 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005648
Eli Friedmanc267a322012-01-26 23:11:39 +00005649 // Check whether the stored value is equal to the original value.
5650 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005651 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005652 return false;
5653
Eli Friedmanc267a322012-01-26 23:11:39 +00005654 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005655 // therefore don't strictly fit into a signed bitfield of width 1.
5656 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005657 return false;
5658
John McCall1f425642010-11-11 03:21:53 +00005659 std::string PrettyValue = Value.toString(10);
5660 std::string PrettyTrunc = TruncatedValue.toString(10);
5661
5662 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5663 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5664 << Init->getSourceRange();
5665
5666 return true;
5667}
5668
John McCalld2a53122010-11-09 23:24:47 +00005669/// Analyze the given simple or compound assignment for warning-worthy
5670/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005671static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005672 // Just recurse on the LHS.
5673 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5674
5675 // We want to recurse on the RHS as normal unless we're assigning to
5676 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005677 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005678 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005679 E->getOperatorLoc())) {
5680 // Recurse, ignoring any implicit conversions on the RHS.
5681 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5682 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005683 }
5684 }
5685
5686 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5687}
5688
John McCall263a48b2010-01-04 23:31:57 +00005689/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005690static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005691 SourceLocation CContext, unsigned diag,
5692 bool pruneControlFlow = false) {
5693 if (pruneControlFlow) {
5694 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5695 S.PDiag(diag)
5696 << SourceType << T << E->getSourceRange()
5697 << SourceRange(CContext));
5698 return;
5699 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005700 S.Diag(E->getExprLoc(), diag)
5701 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5702}
5703
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005704/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005705static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005706 SourceLocation CContext, unsigned diag,
5707 bool pruneControlFlow = false) {
5708 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005709}
5710
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005711/// Diagnose an implicit cast from a literal expression. Does not warn when the
5712/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005713void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5714 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005715 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005716 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005717 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005718 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5719 T->hasUnsignedIntegerRepresentation());
5720 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005721 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005722 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005723 return;
5724
Eli Friedman07185912013-08-29 23:44:43 +00005725 // FIXME: Force the precision of the source value down so we don't print
5726 // digits which are usually useless (we don't really care here if we
5727 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5728 // would automatically print the shortest representation, but it's a bit
5729 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005730 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005731 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5732 precision = (precision * 59 + 195) / 196;
5733 Value.toString(PrettySourceValue, precision);
5734
David Blaikie9b88cc02012-05-15 17:18:27 +00005735 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005736 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5737 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5738 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005739 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005740
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005741 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005742 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5743 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005744}
5745
John McCall18a2c2c2010-11-09 22:22:12 +00005746std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5747 if (!Range.Width) return "0";
5748
5749 llvm::APSInt ValueInRange = Value;
5750 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005751 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005752 return ValueInRange.toString(10);
5753}
5754
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005755static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5756 if (!isa<ImplicitCastExpr>(Ex))
5757 return false;
5758
5759 Expr *InnerE = Ex->IgnoreParenImpCasts();
5760 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5761 const Type *Source =
5762 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5763 if (Target->isDependentType())
5764 return false;
5765
5766 const BuiltinType *FloatCandidateBT =
5767 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5768 const Type *BoolCandidateType = ToBool ? Target : Source;
5769
5770 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5771 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5772}
5773
5774void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5775 SourceLocation CC) {
5776 unsigned NumArgs = TheCall->getNumArgs();
5777 for (unsigned i = 0; i < NumArgs; ++i) {
5778 Expr *CurrA = TheCall->getArg(i);
5779 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5780 continue;
5781
5782 bool IsSwapped = ((i > 0) &&
5783 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5784 IsSwapped |= ((i < (NumArgs - 1)) &&
5785 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5786 if (IsSwapped) {
5787 // Warn on this floating-point to bool conversion.
5788 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5789 CurrA->getType(), CC,
5790 diag::warn_impcast_floating_point_to_bool);
5791 }
5792 }
5793}
5794
John McCallcc7e5bf2010-05-06 08:58:33 +00005795void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00005796 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005797 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005798
John McCallcc7e5bf2010-05-06 08:58:33 +00005799 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5800 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5801 if (Source == Target) return;
5802 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005803
Chandler Carruthc22845a2011-07-26 05:40:03 +00005804 // If the conversion context location is invalid don't complain. We also
5805 // don't want to emit a warning if the issue occurs from the expansion of
5806 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5807 // delay this check as long as possible. Once we detect we are in that
5808 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005809 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005810 return;
5811
Richard Trieu021baa32011-09-23 20:10:00 +00005812 // Diagnose implicit casts to bool.
5813 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5814 if (isa<StringLiteral>(E))
5815 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005816 // and expressions, for instance, assert(0 && "error here"), are
5817 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005818 return DiagnoseImpCast(S, E, T, CC,
5819 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005820 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5821 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5822 // This covers the literal expressions that evaluate to Objective-C
5823 // objects.
5824 return DiagnoseImpCast(S, E, T, CC,
5825 diag::warn_impcast_objective_c_literal_to_bool);
5826 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005827 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5828 // Warn on pointer to bool conversion that is always true.
5829 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5830 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005831 }
Richard Trieu021baa32011-09-23 20:10:00 +00005832 }
John McCall263a48b2010-01-04 23:31:57 +00005833
5834 // Strip vector types.
5835 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005836 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005837 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005838 return;
John McCallacf0ee52010-10-08 02:01:28 +00005839 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005840 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005841
5842 // If the vector cast is cast between two vectors of the same size, it is
5843 // a bitcast, not a conversion.
5844 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5845 return;
John McCall263a48b2010-01-04 23:31:57 +00005846
5847 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5848 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5849 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00005850 if (auto VecTy = dyn_cast<VectorType>(Target))
5851 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00005852
5853 // Strip complex types.
5854 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005855 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005856 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005857 return;
5858
John McCallacf0ee52010-10-08 02:01:28 +00005859 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005860 }
John McCall263a48b2010-01-04 23:31:57 +00005861
5862 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5863 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5864 }
5865
5866 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5867 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5868
5869 // If the source is floating point...
5870 if (SourceBT && SourceBT->isFloatingPoint()) {
5871 // ...and the target is floating point...
5872 if (TargetBT && TargetBT->isFloatingPoint()) {
5873 // ...then warn if we're dropping FP rank.
5874
5875 // Builtin FP kinds are ordered by increasing FP rank.
5876 if (SourceBT->getKind() > TargetBT->getKind()) {
5877 // Don't warn about float constants that are precisely
5878 // representable in the target type.
5879 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005880 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005881 // Value might be a float, a float vector, or a float complex.
5882 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005883 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5884 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005885 return;
5886 }
5887
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005888 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005889 return;
5890
John McCallacf0ee52010-10-08 02:01:28 +00005891 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005892 }
5893 return;
5894 }
5895
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005896 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005897 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005898 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005899 return;
5900
Chandler Carruth22c7a792011-02-17 11:05:49 +00005901 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005902 // We also want to warn on, e.g., "int i = -1.234"
5903 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5904 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5905 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5906
Chandler Carruth016ef402011-04-10 08:36:24 +00005907 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5908 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005909 } else {
5910 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5911 }
5912 }
John McCall263a48b2010-01-04 23:31:57 +00005913
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005914 // If the target is bool, warn if expr is a function or method call.
5915 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5916 isa<CallExpr>(E)) {
5917 // Check last argument of function call to see if it is an
5918 // implicit cast from a type matching the type the result
5919 // is being cast to.
5920 CallExpr *CEx = cast<CallExpr>(E);
5921 unsigned NumArgs = CEx->getNumArgs();
5922 if (NumArgs > 0) {
5923 Expr *LastA = CEx->getArg(NumArgs - 1);
5924 Expr *InnerE = LastA->IgnoreParenImpCasts();
5925 const Type *InnerType =
5926 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5927 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5928 // Warn on this floating-point to bool conversion
5929 DiagnoseImpCast(S, E, T, CC,
5930 diag::warn_impcast_floating_point_to_bool);
5931 }
5932 }
5933 }
John McCall263a48b2010-01-04 23:31:57 +00005934 return;
5935 }
5936
Richard Trieubeaf3452011-05-29 19:59:02 +00005937 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005938 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005939 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005940 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005941 SourceLocation Loc = E->getSourceRange().getBegin();
5942 if (Loc.isMacroID())
5943 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005944 if (!Loc.isMacroID() || CC.isMacroID())
5945 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5946 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005947 << FixItHint::CreateReplacement(Loc,
5948 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005949 }
5950
David Blaikie9366d2b2012-06-19 21:19:06 +00005951 if (!Source->isIntegerType() || !Target->isIntegerType())
5952 return;
5953
David Blaikie7555b6a2012-05-15 16:56:36 +00005954 // TODO: remove this early return once the false positives for constant->bool
5955 // in templates, macros, etc, are reduced or removed.
5956 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5957 return;
5958
John McCallcc7e5bf2010-05-06 08:58:33 +00005959 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005960 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005961
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005962 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005963 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005964 // TODO: this should happen for bitfield stores, too.
5965 llvm::APSInt Value(32);
5966 if (E->isIntegerConstantExpr(Value, S.Context)) {
5967 if (S.SourceMgr.isInSystemMacro(CC))
5968 return;
5969
John McCall18a2c2c2010-11-09 22:22:12 +00005970 std::string PrettySourceValue = Value.toString(10);
5971 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005972
Ted Kremenek33ba9952011-10-22 02:37:33 +00005973 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5974 S.PDiag(diag::warn_impcast_integer_precision_constant)
5975 << PrettySourceValue << PrettyTargetValue
5976 << E->getType() << T << E->getSourceRange()
5977 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005978 return;
5979 }
5980
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005981 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5982 if (S.SourceMgr.isInSystemMacro(CC))
5983 return;
5984
David Blaikie9455da02012-04-12 22:40:54 +00005985 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005986 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5987 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005988 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005989 }
5990
5991 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5992 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5993 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005994
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005995 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005996 return;
5997
John McCallcc7e5bf2010-05-06 08:58:33 +00005998 unsigned DiagID = diag::warn_impcast_integer_sign;
5999
6000 // Traditionally, gcc has warned about this under -Wsign-compare.
6001 // We also want to warn about it in -Wconversion.
6002 // So if -Wconversion is off, use a completely identical diagnostic
6003 // in the sign-compare group.
6004 // The conditional-checking code will
6005 if (ICContext) {
6006 DiagID = diag::warn_impcast_integer_sign_conditional;
6007 *ICContext = true;
6008 }
6009
John McCallacf0ee52010-10-08 02:01:28 +00006010 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006011 }
6012
Douglas Gregora78f1932011-02-22 02:45:07 +00006013 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006014 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6015 // type, to give us better diagnostics.
6016 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006017 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006018 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6019 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6020 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6021 SourceType = S.Context.getTypeDeclType(Enum);
6022 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6023 }
6024 }
6025
Douglas Gregora78f1932011-02-22 02:45:07 +00006026 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6027 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006028 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6029 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006030 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006031 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006032 return;
6033
Douglas Gregor364f7db2011-03-12 00:14:31 +00006034 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006035 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006036 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006037
John McCall263a48b2010-01-04 23:31:57 +00006038 return;
6039}
6040
David Blaikie18e9ac72012-05-15 21:57:38 +00006041void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6042 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006043
6044void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006045 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006046 E = E->IgnoreParenImpCasts();
6047
6048 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006049 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006050
John McCallacf0ee52010-10-08 02:01:28 +00006051 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006052 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006053 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006054 return;
6055}
6056
David Blaikie18e9ac72012-05-15 21:57:38 +00006057void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6058 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00006059 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006060
6061 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006062 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6063 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006064
6065 // If -Wconversion would have warned about either of the candidates
6066 // for a signedness conversion to the context type...
6067 if (!Suspicious) return;
6068
6069 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006070 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
6071 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006072 return;
6073
John McCallcc7e5bf2010-05-06 08:58:33 +00006074 // ...then check whether it would have warned about either of the
6075 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006076 if (E->getType() == T) return;
6077
6078 Suspicious = false;
6079 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6080 E->getType(), CC, &Suspicious);
6081 if (!Suspicious)
6082 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006083 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006084}
6085
6086/// AnalyzeImplicitConversions - Find and report any interesting
6087/// implicit conversions in the given expression. There are a couple
6088/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006089void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006090 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006091 Expr *E = OrigE->IgnoreParenImpCasts();
6092
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006093 if (E->isTypeDependent() || E->isValueDependent())
6094 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006095
John McCallcc7e5bf2010-05-06 08:58:33 +00006096 // For conditional operators, we analyze the arguments as if they
6097 // were being fed directly into the output.
6098 if (isa<ConditionalOperator>(E)) {
6099 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006100 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006101 return;
6102 }
6103
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006104 // Check implicit argument conversions for function calls.
6105 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6106 CheckImplicitArgumentConversions(S, Call, CC);
6107
John McCallcc7e5bf2010-05-06 08:58:33 +00006108 // Go ahead and check any implicit conversions we might have skipped.
6109 // The non-canonical typecheck is just an optimization;
6110 // CheckImplicitConversion will filter out dead implicit conversions.
6111 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006112 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006113
6114 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006115
6116 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006117 if (POE->getResultExpr())
6118 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006119 }
6120
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006121 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6122 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6123
John McCallcc7e5bf2010-05-06 08:58:33 +00006124 // Skip past explicit casts.
6125 if (isa<ExplicitCastExpr>(E)) {
6126 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006127 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006128 }
6129
John McCalld2a53122010-11-09 23:24:47 +00006130 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6131 // Do a somewhat different check with comparison operators.
6132 if (BO->isComparisonOp())
6133 return AnalyzeComparison(S, BO);
6134
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006135 // And with simple assignments.
6136 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006137 return AnalyzeAssignment(S, BO);
6138 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006139
6140 // These break the otherwise-useful invariant below. Fortunately,
6141 // we don't really need to recurse into them, because any internal
6142 // expressions should have been analyzed already when they were
6143 // built into statements.
6144 if (isa<StmtExpr>(E)) return;
6145
6146 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006147 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006148
6149 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006150 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006151 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006152 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006153 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006154 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006155 if (!ChildExpr)
6156 continue;
6157
Richard Trieu955231d2014-01-25 01:10:35 +00006158 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006159 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006160 // Ignore checking string literals that are in logical and operators.
6161 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006162 continue;
6163 AnalyzeImplicitConversions(S, ChildExpr, CC);
6164 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006165}
6166
6167} // end anonymous namespace
6168
Richard Trieu3bb8b562014-02-26 02:36:06 +00006169enum {
6170 AddressOf,
6171 FunctionPointer,
6172 ArrayPointer
6173};
6174
6175/// \brief Diagnose pointers that are always non-null.
6176/// \param E the expression containing the pointer
6177/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6178/// compared to a null pointer
6179/// \param IsEqual True when the comparison is equal to a null pointer
6180/// \param Range Extra SourceRange to highlight in the diagnostic
6181void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6182 Expr::NullPointerConstantKind NullKind,
6183 bool IsEqual, SourceRange Range) {
6184
6185 // Don't warn inside macros.
6186 if (E->getExprLoc().isMacroID())
6187 return;
6188 E = E->IgnoreImpCasts();
6189
6190 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6191
6192 bool IsAddressOf = false;
6193
6194 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6195 if (UO->getOpcode() != UO_AddrOf)
6196 return;
6197 IsAddressOf = true;
6198 E = UO->getSubExpr();
6199 }
6200
6201 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006202 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006203 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6204 D = R->getDecl();
6205 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6206 D = M->getMemberDecl();
6207 }
6208
6209 // Weak Decls can be null.
6210 if (!D || D->isWeak())
6211 return;
6212
6213 QualType T = D->getType();
6214 const bool IsArray = T->isArrayType();
6215 const bool IsFunction = T->isFunctionType();
6216
6217 if (IsAddressOf) {
6218 // Address of function is used to silence the function warning.
6219 if (IsFunction)
6220 return;
6221 // Address of reference can be null.
6222 if (T->isReferenceType())
6223 return;
6224 }
6225
6226 // Found nothing.
6227 if (!IsAddressOf && !IsFunction && !IsArray)
6228 return;
6229
6230 // Pretty print the expression for the diagnostic.
6231 std::string Str;
6232 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006233 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006234
6235 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6236 : diag::warn_impcast_pointer_to_bool;
6237 unsigned DiagType;
6238 if (IsAddressOf)
6239 DiagType = AddressOf;
6240 else if (IsFunction)
6241 DiagType = FunctionPointer;
6242 else if (IsArray)
6243 DiagType = ArrayPointer;
6244 else
6245 llvm_unreachable("Could not determine diagnostic.");
6246 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6247 << Range << IsEqual;
6248
6249 if (!IsFunction)
6250 return;
6251
6252 // Suggest '&' to silence the function warning.
6253 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6254 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6255
6256 // Check to see if '()' fixit should be emitted.
6257 QualType ReturnType;
6258 UnresolvedSet<4> NonTemplateOverloads;
6259 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6260 if (ReturnType.isNull())
6261 return;
6262
6263 if (IsCompare) {
6264 // There are two cases here. If there is null constant, the only suggest
6265 // for a pointer return type. If the null is 0, then suggest if the return
6266 // type is a pointer or an integer type.
6267 if (!ReturnType->isPointerType()) {
6268 if (NullKind == Expr::NPCK_ZeroExpression ||
6269 NullKind == Expr::NPCK_ZeroLiteral) {
6270 if (!ReturnType->isIntegerType())
6271 return;
6272 } else {
6273 return;
6274 }
6275 }
6276 } else { // !IsCompare
6277 // For function to bool, only suggest if the function pointer has bool
6278 // return type.
6279 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6280 return;
6281 }
6282 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006283 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006284}
6285
6286
John McCallcc7e5bf2010-05-06 08:58:33 +00006287/// Diagnoses "dangerous" implicit conversions within the given
6288/// expression (which is a full expression). Implements -Wconversion
6289/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006290///
6291/// \param CC the "context" location of the implicit conversion, i.e.
6292/// the most location of the syntactic entity requiring the implicit
6293/// conversion
6294void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006295 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006296 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006297 return;
6298
6299 // Don't diagnose for value- or type-dependent expressions.
6300 if (E->isTypeDependent() || E->isValueDependent())
6301 return;
6302
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006303 // Check for array bounds violations in cases where the check isn't triggered
6304 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6305 // ArraySubscriptExpr is on the RHS of a variable initialization.
6306 CheckArrayAccess(E);
6307
John McCallacf0ee52010-10-08 02:01:28 +00006308 // This is not the right CC for (e.g.) a variable initialization.
6309 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006310}
6311
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006312/// Diagnose when expression is an integer constant expression and its evaluation
6313/// results in integer overflow
6314void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006315 if (isa<BinaryOperator>(E->IgnoreParens()))
6316 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006317}
6318
Richard Smithc406cb72013-01-17 01:17:56 +00006319namespace {
6320/// \brief Visitor for expressions which looks for unsequenced operations on the
6321/// same object.
6322class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006323 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6324
Richard Smithc406cb72013-01-17 01:17:56 +00006325 /// \brief A tree of sequenced regions within an expression. Two regions are
6326 /// unsequenced if one is an ancestor or a descendent of the other. When we
6327 /// finish processing an expression with sequencing, such as a comma
6328 /// expression, we fold its tree nodes into its parent, since they are
6329 /// unsequenced with respect to nodes we will visit later.
6330 class SequenceTree {
6331 struct Value {
6332 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6333 unsigned Parent : 31;
6334 bool Merged : 1;
6335 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006336 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006337
6338 public:
6339 /// \brief A region within an expression which may be sequenced with respect
6340 /// to some other region.
6341 class Seq {
6342 explicit Seq(unsigned N) : Index(N) {}
6343 unsigned Index;
6344 friend class SequenceTree;
6345 public:
6346 Seq() : Index(0) {}
6347 };
6348
6349 SequenceTree() { Values.push_back(Value(0)); }
6350 Seq root() const { return Seq(0); }
6351
6352 /// \brief Create a new sequence of operations, which is an unsequenced
6353 /// subset of \p Parent. This sequence of operations is sequenced with
6354 /// respect to other children of \p Parent.
6355 Seq allocate(Seq Parent) {
6356 Values.push_back(Value(Parent.Index));
6357 return Seq(Values.size() - 1);
6358 }
6359
6360 /// \brief Merge a sequence of operations into its parent.
6361 void merge(Seq S) {
6362 Values[S.Index].Merged = true;
6363 }
6364
6365 /// \brief Determine whether two operations are unsequenced. This operation
6366 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6367 /// should have been merged into its parent as appropriate.
6368 bool isUnsequenced(Seq Cur, Seq Old) {
6369 unsigned C = representative(Cur.Index);
6370 unsigned Target = representative(Old.Index);
6371 while (C >= Target) {
6372 if (C == Target)
6373 return true;
6374 C = Values[C].Parent;
6375 }
6376 return false;
6377 }
6378
6379 private:
6380 /// \brief Pick a representative for a sequence.
6381 unsigned representative(unsigned K) {
6382 if (Values[K].Merged)
6383 // Perform path compression as we go.
6384 return Values[K].Parent = representative(Values[K].Parent);
6385 return K;
6386 }
6387 };
6388
6389 /// An object for which we can track unsequenced uses.
6390 typedef NamedDecl *Object;
6391
6392 /// Different flavors of object usage which we track. We only track the
6393 /// least-sequenced usage of each kind.
6394 enum UsageKind {
6395 /// A read of an object. Multiple unsequenced reads are OK.
6396 UK_Use,
6397 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006398 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006399 UK_ModAsValue,
6400 /// A modification of an object which is not sequenced before the value
6401 /// computation of the expression, such as n++.
6402 UK_ModAsSideEffect,
6403
6404 UK_Count = UK_ModAsSideEffect + 1
6405 };
6406
6407 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006408 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006409 Expr *Use;
6410 SequenceTree::Seq Seq;
6411 };
6412
6413 struct UsageInfo {
6414 UsageInfo() : Diagnosed(false) {}
6415 Usage Uses[UK_Count];
6416 /// Have we issued a diagnostic for this variable already?
6417 bool Diagnosed;
6418 };
6419 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6420
6421 Sema &SemaRef;
6422 /// Sequenced regions within the expression.
6423 SequenceTree Tree;
6424 /// Declaration modifications and references which we have seen.
6425 UsageInfoMap UsageMap;
6426 /// The region we are currently within.
6427 SequenceTree::Seq Region;
6428 /// Filled in with declarations which were modified as a side-effect
6429 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006430 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006431 /// Expressions to check later. We defer checking these to reduce
6432 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006433 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006434
6435 /// RAII object wrapping the visitation of a sequenced subexpression of an
6436 /// expression. At the end of this process, the side-effects of the evaluation
6437 /// become sequenced with respect to the value computation of the result, so
6438 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6439 /// UK_ModAsValue.
6440 struct SequencedSubexpression {
6441 SequencedSubexpression(SequenceChecker &Self)
6442 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6443 Self.ModAsSideEffect = &ModAsSideEffect;
6444 }
6445 ~SequencedSubexpression() {
6446 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6447 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6448 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6449 Self.addUsage(U, ModAsSideEffect[I].first,
6450 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6451 }
6452 Self.ModAsSideEffect = OldModAsSideEffect;
6453 }
6454
6455 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006456 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6457 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006458 };
6459
Richard Smith40238f02013-06-20 22:21:56 +00006460 /// RAII object wrapping the visitation of a subexpression which we might
6461 /// choose to evaluate as a constant. If any subexpression is evaluated and
6462 /// found to be non-constant, this allows us to suppress the evaluation of
6463 /// the outer expression.
6464 class EvaluationTracker {
6465 public:
6466 EvaluationTracker(SequenceChecker &Self)
6467 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6468 Self.EvalTracker = this;
6469 }
6470 ~EvaluationTracker() {
6471 Self.EvalTracker = Prev;
6472 if (Prev)
6473 Prev->EvalOK &= EvalOK;
6474 }
6475
6476 bool evaluate(const Expr *E, bool &Result) {
6477 if (!EvalOK || E->isValueDependent())
6478 return false;
6479 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6480 return EvalOK;
6481 }
6482
6483 private:
6484 SequenceChecker &Self;
6485 EvaluationTracker *Prev;
6486 bool EvalOK;
6487 } *EvalTracker;
6488
Richard Smithc406cb72013-01-17 01:17:56 +00006489 /// \brief Find the object which is produced by the specified expression,
6490 /// if any.
6491 Object getObject(Expr *E, bool Mod) const {
6492 E = E->IgnoreParenCasts();
6493 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6494 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6495 return getObject(UO->getSubExpr(), Mod);
6496 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6497 if (BO->getOpcode() == BO_Comma)
6498 return getObject(BO->getRHS(), Mod);
6499 if (Mod && BO->isAssignmentOp())
6500 return getObject(BO->getLHS(), Mod);
6501 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6502 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6503 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6504 return ME->getMemberDecl();
6505 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6506 // FIXME: If this is a reference, map through to its value.
6507 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006508 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006509 }
6510
6511 /// \brief Note that an object was modified or used by an expression.
6512 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6513 Usage &U = UI.Uses[UK];
6514 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6515 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6516 ModAsSideEffect->push_back(std::make_pair(O, U));
6517 U.Use = Ref;
6518 U.Seq = Region;
6519 }
6520 }
6521 /// \brief Check whether a modification or use conflicts with a prior usage.
6522 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6523 bool IsModMod) {
6524 if (UI.Diagnosed)
6525 return;
6526
6527 const Usage &U = UI.Uses[OtherKind];
6528 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6529 return;
6530
6531 Expr *Mod = U.Use;
6532 Expr *ModOrUse = Ref;
6533 if (OtherKind == UK_Use)
6534 std::swap(Mod, ModOrUse);
6535
6536 SemaRef.Diag(Mod->getExprLoc(),
6537 IsModMod ? diag::warn_unsequenced_mod_mod
6538 : diag::warn_unsequenced_mod_use)
6539 << O << SourceRange(ModOrUse->getExprLoc());
6540 UI.Diagnosed = true;
6541 }
6542
6543 void notePreUse(Object O, Expr *Use) {
6544 UsageInfo &U = UsageMap[O];
6545 // Uses conflict with other modifications.
6546 checkUsage(O, U, Use, UK_ModAsValue, false);
6547 }
6548 void notePostUse(Object O, Expr *Use) {
6549 UsageInfo &U = UsageMap[O];
6550 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6551 addUsage(U, O, Use, UK_Use);
6552 }
6553
6554 void notePreMod(Object O, Expr *Mod) {
6555 UsageInfo &U = UsageMap[O];
6556 // Modifications conflict with other modifications and with uses.
6557 checkUsage(O, U, Mod, UK_ModAsValue, true);
6558 checkUsage(O, U, Mod, UK_Use, false);
6559 }
6560 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6561 UsageInfo &U = UsageMap[O];
6562 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6563 addUsage(U, O, Use, UK);
6564 }
6565
6566public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006567 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006568 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6569 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006570 Visit(E);
6571 }
6572
6573 void VisitStmt(Stmt *S) {
6574 // Skip all statements which aren't expressions for now.
6575 }
6576
6577 void VisitExpr(Expr *E) {
6578 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006579 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006580 }
6581
6582 void VisitCastExpr(CastExpr *E) {
6583 Object O = Object();
6584 if (E->getCastKind() == CK_LValueToRValue)
6585 O = getObject(E->getSubExpr(), false);
6586
6587 if (O)
6588 notePreUse(O, E);
6589 VisitExpr(E);
6590 if (O)
6591 notePostUse(O, E);
6592 }
6593
6594 void VisitBinComma(BinaryOperator *BO) {
6595 // C++11 [expr.comma]p1:
6596 // Every value computation and side effect associated with the left
6597 // expression is sequenced before every value computation and side
6598 // effect associated with the right expression.
6599 SequenceTree::Seq LHS = Tree.allocate(Region);
6600 SequenceTree::Seq RHS = Tree.allocate(Region);
6601 SequenceTree::Seq OldRegion = Region;
6602
6603 {
6604 SequencedSubexpression SeqLHS(*this);
6605 Region = LHS;
6606 Visit(BO->getLHS());
6607 }
6608
6609 Region = RHS;
6610 Visit(BO->getRHS());
6611
6612 Region = OldRegion;
6613
6614 // Forget that LHS and RHS are sequenced. They are both unsequenced
6615 // with respect to other stuff.
6616 Tree.merge(LHS);
6617 Tree.merge(RHS);
6618 }
6619
6620 void VisitBinAssign(BinaryOperator *BO) {
6621 // The modification is sequenced after the value computation of the LHS
6622 // and RHS, so check it before inspecting the operands and update the
6623 // map afterwards.
6624 Object O = getObject(BO->getLHS(), true);
6625 if (!O)
6626 return VisitExpr(BO);
6627
6628 notePreMod(O, BO);
6629
6630 // C++11 [expr.ass]p7:
6631 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6632 // only once.
6633 //
6634 // Therefore, for a compound assignment operator, O is considered used
6635 // everywhere except within the evaluation of E1 itself.
6636 if (isa<CompoundAssignOperator>(BO))
6637 notePreUse(O, BO);
6638
6639 Visit(BO->getLHS());
6640
6641 if (isa<CompoundAssignOperator>(BO))
6642 notePostUse(O, BO);
6643
6644 Visit(BO->getRHS());
6645
Richard Smith83e37bee2013-06-26 23:16:51 +00006646 // C++11 [expr.ass]p1:
6647 // the assignment is sequenced [...] before the value computation of the
6648 // assignment expression.
6649 // C11 6.5.16/3 has no such rule.
6650 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6651 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006652 }
6653 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6654 VisitBinAssign(CAO);
6655 }
6656
6657 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6658 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6659 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6660 Object O = getObject(UO->getSubExpr(), true);
6661 if (!O)
6662 return VisitExpr(UO);
6663
6664 notePreMod(O, UO);
6665 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006666 // C++11 [expr.pre.incr]p1:
6667 // the expression ++x is equivalent to x+=1
6668 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6669 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006670 }
6671
6672 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6673 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6674 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6675 Object O = getObject(UO->getSubExpr(), true);
6676 if (!O)
6677 return VisitExpr(UO);
6678
6679 notePreMod(O, UO);
6680 Visit(UO->getSubExpr());
6681 notePostMod(O, UO, UK_ModAsSideEffect);
6682 }
6683
6684 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6685 void VisitBinLOr(BinaryOperator *BO) {
6686 // The side-effects of the LHS of an '&&' are sequenced before the
6687 // value computation of the RHS, and hence before the value computation
6688 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6689 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006690 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006691 {
6692 SequencedSubexpression Sequenced(*this);
6693 Visit(BO->getLHS());
6694 }
6695
6696 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006697 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006698 if (!Result)
6699 Visit(BO->getRHS());
6700 } else {
6701 // Check for unsequenced operations in the RHS, treating it as an
6702 // entirely separate evaluation.
6703 //
6704 // FIXME: If there are operations in the RHS which are unsequenced
6705 // with respect to operations outside the RHS, and those operations
6706 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006707 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006708 }
Richard Smithc406cb72013-01-17 01:17:56 +00006709 }
6710 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006711 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006712 {
6713 SequencedSubexpression Sequenced(*this);
6714 Visit(BO->getLHS());
6715 }
6716
6717 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006718 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006719 if (Result)
6720 Visit(BO->getRHS());
6721 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006722 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006723 }
Richard Smithc406cb72013-01-17 01:17:56 +00006724 }
6725
6726 // Only visit the condition, unless we can be sure which subexpression will
6727 // be chosen.
6728 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006729 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006730 {
6731 SequencedSubexpression Sequenced(*this);
6732 Visit(CO->getCond());
6733 }
Richard Smithc406cb72013-01-17 01:17:56 +00006734
6735 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006736 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006737 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006738 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006739 WorkList.push_back(CO->getTrueExpr());
6740 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006741 }
Richard Smithc406cb72013-01-17 01:17:56 +00006742 }
6743
Richard Smithe3dbfe02013-06-30 10:40:20 +00006744 void VisitCallExpr(CallExpr *CE) {
6745 // C++11 [intro.execution]p15:
6746 // When calling a function [...], every value computation and side effect
6747 // associated with any argument expression, or with the postfix expression
6748 // designating the called function, is sequenced before execution of every
6749 // expression or statement in the body of the function [and thus before
6750 // the value computation of its result].
6751 SequencedSubexpression Sequenced(*this);
6752 Base::VisitCallExpr(CE);
6753
6754 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6755 }
6756
Richard Smithc406cb72013-01-17 01:17:56 +00006757 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006758 // This is a call, so all subexpressions are sequenced before the result.
6759 SequencedSubexpression Sequenced(*this);
6760
Richard Smithc406cb72013-01-17 01:17:56 +00006761 if (!CCE->isListInitialization())
6762 return VisitExpr(CCE);
6763
6764 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006765 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006766 SequenceTree::Seq Parent = Region;
6767 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6768 E = CCE->arg_end();
6769 I != E; ++I) {
6770 Region = Tree.allocate(Parent);
6771 Elts.push_back(Region);
6772 Visit(*I);
6773 }
6774
6775 // Forget that the initializers are sequenced.
6776 Region = Parent;
6777 for (unsigned I = 0; I < Elts.size(); ++I)
6778 Tree.merge(Elts[I]);
6779 }
6780
6781 void VisitInitListExpr(InitListExpr *ILE) {
6782 if (!SemaRef.getLangOpts().CPlusPlus11)
6783 return VisitExpr(ILE);
6784
6785 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006786 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006787 SequenceTree::Seq Parent = Region;
6788 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6789 Expr *E = ILE->getInit(I);
6790 if (!E) continue;
6791 Region = Tree.allocate(Parent);
6792 Elts.push_back(Region);
6793 Visit(E);
6794 }
6795
6796 // Forget that the initializers are sequenced.
6797 Region = Parent;
6798 for (unsigned I = 0; I < Elts.size(); ++I)
6799 Tree.merge(Elts[I]);
6800 }
6801};
6802}
6803
6804void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006805 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006806 WorkList.push_back(E);
6807 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006808 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006809 SequenceChecker(*this, Item, WorkList);
6810 }
Richard Smithc406cb72013-01-17 01:17:56 +00006811}
6812
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006813void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6814 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006815 CheckImplicitConversions(E, CheckLoc);
6816 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006817 if (!IsConstexpr && !E->isValueDependent())
6818 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006819}
6820
John McCall1f425642010-11-11 03:21:53 +00006821void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6822 FieldDecl *BitField,
6823 Expr *Init) {
6824 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6825}
6826
Mike Stump0c2ec772010-01-21 03:59:47 +00006827/// CheckParmsForFunctionDef - Check that the parameters of the given
6828/// function are appropriate for the definition of a function. This
6829/// takes care of any checks that cannot be performed on the
6830/// declaration itself, e.g., that the types of each of the function
6831/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006832bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6833 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006834 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006835 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006836 for (; P != PEnd; ++P) {
6837 ParmVarDecl *Param = *P;
6838
Mike Stump0c2ec772010-01-21 03:59:47 +00006839 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6840 // function declarator that is part of a function definition of
6841 // that function shall not have incomplete type.
6842 //
6843 // This is also C++ [dcl.fct]p6.
6844 if (!Param->isInvalidDecl() &&
6845 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006846 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006847 Param->setInvalidDecl();
6848 HasInvalidParm = true;
6849 }
6850
6851 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6852 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006853 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00006854 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006855 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006856 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006857 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006858
6859 // C99 6.7.5.3p12:
6860 // If the function declarator is not part of a definition of that
6861 // function, parameters may have incomplete type and may use the [*]
6862 // notation in their sequences of declarator specifiers to specify
6863 // variable length array types.
6864 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006865 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006866 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006867 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006868 // information is added for it.
6869 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006870 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006871 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006872 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006873 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006874
6875 // MSVC destroys objects passed by value in the callee. Therefore a
6876 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006877 // object's destructor. However, we don't perform any direct access check
6878 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006879 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6880 .getCXXABI()
6881 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006882 if (!Param->isInvalidDecl()) {
6883 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6884 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6885 if (!ClassDecl->isInvalidDecl() &&
6886 !ClassDecl->hasIrrelevantDestructor() &&
6887 !ClassDecl->isDependentContext()) {
6888 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6889 MarkFunctionReferenced(Param->getLocation(), Destructor);
6890 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6891 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006892 }
6893 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006894 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006895 }
6896
6897 return HasInvalidParm;
6898}
John McCall2b5c1b22010-08-12 21:44:57 +00006899
6900/// CheckCastAlign - Implements -Wcast-align, which warns when a
6901/// pointer cast increases the alignment requirements.
6902void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6903 // This is actually a lot of work to potentially be doing on every
6904 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006905 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6906 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006907 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006908 return;
6909
6910 // Ignore dependent types.
6911 if (T->isDependentType() || Op->getType()->isDependentType())
6912 return;
6913
6914 // Require that the destination be a pointer type.
6915 const PointerType *DestPtr = T->getAs<PointerType>();
6916 if (!DestPtr) return;
6917
6918 // If the destination has alignment 1, we're done.
6919 QualType DestPointee = DestPtr->getPointeeType();
6920 if (DestPointee->isIncompleteType()) return;
6921 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6922 if (DestAlign.isOne()) return;
6923
6924 // Require that the source be a pointer type.
6925 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6926 if (!SrcPtr) return;
6927 QualType SrcPointee = SrcPtr->getPointeeType();
6928
6929 // Whitelist casts from cv void*. We already implicitly
6930 // whitelisted casts to cv void*, since they have alignment 1.
6931 // Also whitelist casts involving incomplete types, which implicitly
6932 // includes 'void'.
6933 if (SrcPointee->isIncompleteType()) return;
6934
6935 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6936 if (SrcAlign >= DestAlign) return;
6937
6938 Diag(TRange.getBegin(), diag::warn_cast_align)
6939 << Op->getType() << T
6940 << static_cast<unsigned>(SrcAlign.getQuantity())
6941 << static_cast<unsigned>(DestAlign.getQuantity())
6942 << TRange << Op->getSourceRange();
6943}
6944
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006945static const Type* getElementType(const Expr *BaseExpr) {
6946 const Type* EltType = BaseExpr->getType().getTypePtr();
6947 if (EltType->isAnyPointerType())
6948 return EltType->getPointeeType().getTypePtr();
6949 else if (EltType->isArrayType())
6950 return EltType->getBaseElementTypeUnsafe();
6951 return EltType;
6952}
6953
Chandler Carruth28389f02011-08-05 09:10:50 +00006954/// \brief Check whether this array fits the idiom of a size-one tail padded
6955/// array member of a struct.
6956///
6957/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6958/// commonly used to emulate flexible arrays in C89 code.
6959static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6960 const NamedDecl *ND) {
6961 if (Size != 1 || !ND) return false;
6962
6963 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6964 if (!FD) return false;
6965
6966 // Don't consider sizes resulting from macro expansions or template argument
6967 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006968
6969 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006970 while (TInfo) {
6971 TypeLoc TL = TInfo->getTypeLoc();
6972 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006973 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6974 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006975 TInfo = TDL->getTypeSourceInfo();
6976 continue;
6977 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006978 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6979 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006980 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6981 return false;
6982 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006983 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006984 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006985
6986 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006987 if (!RD) return false;
6988 if (RD->isUnion()) return false;
6989 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6990 if (!CRD->isStandardLayout()) return false;
6991 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006992
Benjamin Kramer8c543672011-08-06 03:04:42 +00006993 // See if this is the last field decl in the record.
6994 const Decl *D = FD;
6995 while ((D = D->getNextDeclInContext()))
6996 if (isa<FieldDecl>(D))
6997 return false;
6998 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006999}
7000
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007001void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007002 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007003 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007004 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007005 if (IndexExpr->isValueDependent())
7006 return;
7007
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007008 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007009 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007010 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007011 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007012 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007013 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007014
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007015 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007016 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007017 return;
Richard Smith13f67182011-12-16 19:31:14 +00007018 if (IndexNegated)
7019 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007020
Craig Topperc3ec1492014-05-26 06:22:03 +00007021 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007022 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7023 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007024 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007025 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007026
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007027 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007028 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007029 if (!size.isStrictlyPositive())
7030 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007031
7032 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007033 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007034 // Make sure we're comparing apples to apples when comparing index to size
7035 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7036 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007037 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007038 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007039 if (ptrarith_typesize != array_typesize) {
7040 // There's a cast to a different size type involved
7041 uint64_t ratio = array_typesize / ptrarith_typesize;
7042 // TODO: Be smarter about handling cases where array_typesize is not a
7043 // multiple of ptrarith_typesize
7044 if (ptrarith_typesize * ratio == array_typesize)
7045 size *= llvm::APInt(size.getBitWidth(), ratio);
7046 }
7047 }
7048
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007049 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007050 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007051 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007052 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007053
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007054 // For array subscripting the index must be less than size, but for pointer
7055 // arithmetic also allow the index (offset) to be equal to size since
7056 // computing the next address after the end of the array is legal and
7057 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007058 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007059 return;
7060
7061 // Also don't warn for arrays of size 1 which are members of some
7062 // structure. These are often used to approximate flexible arrays in C89
7063 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007064 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007065 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007066
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007067 // Suppress the warning if the subscript expression (as identified by the
7068 // ']' location) and the index expression are both from macro expansions
7069 // within a system header.
7070 if (ASE) {
7071 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7072 ASE->getRBracketLoc());
7073 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7074 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7075 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007076 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007077 return;
7078 }
7079 }
7080
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007081 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007082 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007083 DiagID = diag::warn_array_index_exceeds_bounds;
7084
7085 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7086 PDiag(DiagID) << index.toString(10, true)
7087 << size.toString(10, true)
7088 << (unsigned)size.getLimitedValue(~0U)
7089 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007090 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007091 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007092 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007093 DiagID = diag::warn_ptr_arith_precedes_bounds;
7094 if (index.isNegative()) index = -index;
7095 }
7096
7097 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7098 PDiag(DiagID) << index.toString(10, true)
7099 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007100 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007101
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007102 if (!ND) {
7103 // Try harder to find a NamedDecl to point at in the note.
7104 while (const ArraySubscriptExpr *ASE =
7105 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7106 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7107 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7108 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7109 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7110 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7111 }
7112
Chandler Carruth1af88f12011-02-17 21:10:52 +00007113 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007114 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7115 PDiag(diag::note_array_index_out_of_bounds)
7116 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007117}
7118
Ted Kremenekdf26df72011-03-01 18:41:00 +00007119void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007120 int AllowOnePastEnd = 0;
7121 while (expr) {
7122 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007123 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007124 case Stmt::ArraySubscriptExprClass: {
7125 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007126 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007127 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007128 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007129 }
7130 case Stmt::UnaryOperatorClass: {
7131 // Only unwrap the * and & unary operators
7132 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7133 expr = UO->getSubExpr();
7134 switch (UO->getOpcode()) {
7135 case UO_AddrOf:
7136 AllowOnePastEnd++;
7137 break;
7138 case UO_Deref:
7139 AllowOnePastEnd--;
7140 break;
7141 default:
7142 return;
7143 }
7144 break;
7145 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007146 case Stmt::ConditionalOperatorClass: {
7147 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7148 if (const Expr *lhs = cond->getLHS())
7149 CheckArrayAccess(lhs);
7150 if (const Expr *rhs = cond->getRHS())
7151 CheckArrayAccess(rhs);
7152 return;
7153 }
7154 default:
7155 return;
7156 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007157 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007158}
John McCall31168b02011-06-15 23:02:42 +00007159
7160//===--- CHECK: Objective-C retain cycles ----------------------------------//
7161
7162namespace {
7163 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007164 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007165 VarDecl *Variable;
7166 SourceRange Range;
7167 SourceLocation Loc;
7168 bool Indirect;
7169
7170 void setLocsFrom(Expr *e) {
7171 Loc = e->getExprLoc();
7172 Range = e->getSourceRange();
7173 }
7174 };
7175}
7176
7177/// Consider whether capturing the given variable can possibly lead to
7178/// a retain cycle.
7179static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007180 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007181 // lifetime. In MRR, it's captured strongly if the variable is
7182 // __block and has an appropriate type.
7183 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7184 return false;
7185
7186 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007187 if (ref)
7188 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007189 return true;
7190}
7191
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007192static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007193 while (true) {
7194 e = e->IgnoreParens();
7195 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7196 switch (cast->getCastKind()) {
7197 case CK_BitCast:
7198 case CK_LValueBitCast:
7199 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007200 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007201 e = cast->getSubExpr();
7202 continue;
7203
John McCall31168b02011-06-15 23:02:42 +00007204 default:
7205 return false;
7206 }
7207 }
7208
7209 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7210 ObjCIvarDecl *ivar = ref->getDecl();
7211 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7212 return false;
7213
7214 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007215 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007216 return false;
7217
7218 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7219 owner.Indirect = true;
7220 return true;
7221 }
7222
7223 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7224 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7225 if (!var) return false;
7226 return considerVariable(var, ref, owner);
7227 }
7228
John McCall31168b02011-06-15 23:02:42 +00007229 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7230 if (member->isArrow()) return false;
7231
7232 // Don't count this as an indirect ownership.
7233 e = member->getBase();
7234 continue;
7235 }
7236
John McCallfe96e0b2011-11-06 09:01:30 +00007237 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7238 // Only pay attention to pseudo-objects on property references.
7239 ObjCPropertyRefExpr *pre
7240 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7241 ->IgnoreParens());
7242 if (!pre) return false;
7243 if (pre->isImplicitProperty()) return false;
7244 ObjCPropertyDecl *property = pre->getExplicitProperty();
7245 if (!property->isRetaining() &&
7246 !(property->getPropertyIvarDecl() &&
7247 property->getPropertyIvarDecl()->getType()
7248 .getObjCLifetime() == Qualifiers::OCL_Strong))
7249 return false;
7250
7251 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007252 if (pre->isSuperReceiver()) {
7253 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7254 if (!owner.Variable)
7255 return false;
7256 owner.Loc = pre->getLocation();
7257 owner.Range = pre->getSourceRange();
7258 return true;
7259 }
John McCallfe96e0b2011-11-06 09:01:30 +00007260 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7261 ->getSourceExpr());
7262 continue;
7263 }
7264
John McCall31168b02011-06-15 23:02:42 +00007265 // Array ivars?
7266
7267 return false;
7268 }
7269}
7270
7271namespace {
7272 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7273 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7274 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Craig Topperc3ec1492014-05-26 06:22:03 +00007275 Variable(variable), Capturer(nullptr) {}
John McCall31168b02011-06-15 23:02:42 +00007276
7277 VarDecl *Variable;
7278 Expr *Capturer;
7279
7280 void VisitDeclRefExpr(DeclRefExpr *ref) {
7281 if (ref->getDecl() == Variable && !Capturer)
7282 Capturer = ref;
7283 }
7284
John McCall31168b02011-06-15 23:02:42 +00007285 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7286 if (Capturer) return;
7287 Visit(ref->getBase());
7288 if (Capturer && ref->isFreeIvar())
7289 Capturer = ref;
7290 }
7291
7292 void VisitBlockExpr(BlockExpr *block) {
7293 // Look inside nested blocks
7294 if (block->getBlockDecl()->capturesVariable(Variable))
7295 Visit(block->getBlockDecl()->getBody());
7296 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007297
7298 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7299 if (Capturer) return;
7300 if (OVE->getSourceExpr())
7301 Visit(OVE->getSourceExpr());
7302 }
John McCall31168b02011-06-15 23:02:42 +00007303 };
7304}
7305
7306/// Check whether the given argument is a block which captures a
7307/// variable.
7308static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7309 assert(owner.Variable && owner.Loc.isValid());
7310
7311 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007312
7313 // Look through [^{...} copy] and Block_copy(^{...}).
7314 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7315 Selector Cmd = ME->getSelector();
7316 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7317 e = ME->getInstanceReceiver();
7318 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007319 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007320 e = e->IgnoreParenCasts();
7321 }
7322 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7323 if (CE->getNumArgs() == 1) {
7324 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007325 if (Fn) {
7326 const IdentifierInfo *FnI = Fn->getIdentifier();
7327 if (FnI && FnI->isStr("_Block_copy")) {
7328 e = CE->getArg(0)->IgnoreParenCasts();
7329 }
7330 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007331 }
7332 }
7333
John McCall31168b02011-06-15 23:02:42 +00007334 BlockExpr *block = dyn_cast<BlockExpr>(e);
7335 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007336 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007337
7338 FindCaptureVisitor visitor(S.Context, owner.Variable);
7339 visitor.Visit(block->getBlockDecl()->getBody());
7340 return visitor.Capturer;
7341}
7342
7343static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7344 RetainCycleOwner &owner) {
7345 assert(capturer);
7346 assert(owner.Variable && owner.Loc.isValid());
7347
7348 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7349 << owner.Variable << capturer->getSourceRange();
7350 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7351 << owner.Indirect << owner.Range;
7352}
7353
7354/// Check for a keyword selector that starts with the word 'add' or
7355/// 'set'.
7356static bool isSetterLikeSelector(Selector sel) {
7357 if (sel.isUnarySelector()) return false;
7358
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007359 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007360 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007361 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007362 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007363 else if (str.startswith("add")) {
7364 // Specially whitelist 'addOperationWithBlock:'.
7365 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7366 return false;
7367 str = str.substr(3);
7368 }
John McCall31168b02011-06-15 23:02:42 +00007369 else
7370 return false;
7371
7372 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007373 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007374}
7375
7376/// Check a message send to see if it's likely to cause a retain cycle.
7377void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7378 // Only check instance methods whose selector looks like a setter.
7379 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7380 return;
7381
7382 // Try to find a variable that the receiver is strongly owned by.
7383 RetainCycleOwner owner;
7384 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007385 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007386 return;
7387 } else {
7388 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7389 owner.Variable = getCurMethodDecl()->getSelfDecl();
7390 owner.Loc = msg->getSuperLoc();
7391 owner.Range = msg->getSuperLoc();
7392 }
7393
7394 // Check whether the receiver is captured by any of the arguments.
7395 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7396 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7397 return diagnoseRetainCycle(*this, capturer, owner);
7398}
7399
7400/// Check a property assign to see if it's likely to cause a retain cycle.
7401void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7402 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007403 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007404 return;
7405
7406 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7407 diagnoseRetainCycle(*this, capturer, owner);
7408}
7409
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007410void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7411 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007412 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007413 return;
7414
7415 // Because we don't have an expression for the variable, we have to set the
7416 // location explicitly here.
7417 Owner.Loc = Var->getLocation();
7418 Owner.Range = Var->getSourceRange();
7419
7420 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7421 diagnoseRetainCycle(*this, Capturer, Owner);
7422}
7423
Ted Kremenek9304da92012-12-21 08:04:28 +00007424static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7425 Expr *RHS, bool isProperty) {
7426 // Check if RHS is an Objective-C object literal, which also can get
7427 // immediately zapped in a weak reference. Note that we explicitly
7428 // allow ObjCStringLiterals, since those are designed to never really die.
7429 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007430
Ted Kremenek64873352012-12-21 22:46:35 +00007431 // This enum needs to match with the 'select' in
7432 // warn_objc_arc_literal_assign (off-by-1).
7433 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7434 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7435 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007436
7437 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007438 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007439 << (isProperty ? 0 : 1)
7440 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007441
7442 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007443}
7444
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007445static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7446 Qualifiers::ObjCLifetime LT,
7447 Expr *RHS, bool isProperty) {
7448 // Strip off any implicit cast added to get to the one ARC-specific.
7449 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7450 if (cast->getCastKind() == CK_ARCConsumeObject) {
7451 S.Diag(Loc, diag::warn_arc_retained_assign)
7452 << (LT == Qualifiers::OCL_ExplicitNone)
7453 << (isProperty ? 0 : 1)
7454 << RHS->getSourceRange();
7455 return true;
7456 }
7457 RHS = cast->getSubExpr();
7458 }
7459
7460 if (LT == Qualifiers::OCL_Weak &&
7461 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7462 return true;
7463
7464 return false;
7465}
7466
Ted Kremenekb36234d2012-12-21 08:04:20 +00007467bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7468 QualType LHS, Expr *RHS) {
7469 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7470
7471 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7472 return false;
7473
7474 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7475 return true;
7476
7477 return false;
7478}
7479
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007480void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7481 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007482 QualType LHSType;
7483 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007484 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007485 ObjCPropertyRefExpr *PRE
7486 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7487 if (PRE && !PRE->isImplicitProperty()) {
7488 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7489 if (PD)
7490 LHSType = PD->getType();
7491 }
7492
7493 if (LHSType.isNull())
7494 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007495
7496 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7497
7498 if (LT == Qualifiers::OCL_Weak) {
7499 DiagnosticsEngine::Level Level =
7500 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7501 if (Level != DiagnosticsEngine::Ignored)
7502 getCurFunction()->markSafeWeakUse(LHS);
7503 }
7504
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007505 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7506 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007507
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007508 // FIXME. Check for other life times.
7509 if (LT != Qualifiers::OCL_None)
7510 return;
7511
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007512 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007513 if (PRE->isImplicitProperty())
7514 return;
7515 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7516 if (!PD)
7517 return;
7518
Bill Wendling44426052012-12-20 19:22:21 +00007519 unsigned Attributes = PD->getPropertyAttributes();
7520 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007521 // when 'assign' attribute was not explicitly specified
7522 // by user, ignore it and rely on property type itself
7523 // for lifetime info.
7524 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7525 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7526 LHSType->isObjCRetainableType())
7527 return;
7528
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007529 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007530 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007531 Diag(Loc, diag::warn_arc_retained_property_assign)
7532 << RHS->getSourceRange();
7533 return;
7534 }
7535 RHS = cast->getSubExpr();
7536 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007537 }
Bill Wendling44426052012-12-20 19:22:21 +00007538 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007539 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7540 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007541 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007542 }
7543}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007544
7545//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7546
7547namespace {
7548bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7549 SourceLocation StmtLoc,
7550 const NullStmt *Body) {
7551 // Do not warn if the body is a macro that expands to nothing, e.g:
7552 //
7553 // #define CALL(x)
7554 // if (condition)
7555 // CALL(0);
7556 //
7557 if (Body->hasLeadingEmptyMacro())
7558 return false;
7559
7560 // Get line numbers of statement and body.
7561 bool StmtLineInvalid;
7562 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7563 &StmtLineInvalid);
7564 if (StmtLineInvalid)
7565 return false;
7566
7567 bool BodyLineInvalid;
7568 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7569 &BodyLineInvalid);
7570 if (BodyLineInvalid)
7571 return false;
7572
7573 // Warn if null statement and body are on the same line.
7574 if (StmtLine != BodyLine)
7575 return false;
7576
7577 return true;
7578}
7579} // Unnamed namespace
7580
7581void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7582 const Stmt *Body,
7583 unsigned DiagID) {
7584 // Since this is a syntactic check, don't emit diagnostic for template
7585 // instantiations, this just adds noise.
7586 if (CurrentInstantiationScope)
7587 return;
7588
7589 // The body should be a null statement.
7590 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7591 if (!NBody)
7592 return;
7593
7594 // Do the usual checks.
7595 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7596 return;
7597
7598 Diag(NBody->getSemiLoc(), DiagID);
7599 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7600}
7601
7602void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7603 const Stmt *PossibleBody) {
7604 assert(!CurrentInstantiationScope); // Ensured by caller
7605
7606 SourceLocation StmtLoc;
7607 const Stmt *Body;
7608 unsigned DiagID;
7609 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7610 StmtLoc = FS->getRParenLoc();
7611 Body = FS->getBody();
7612 DiagID = diag::warn_empty_for_body;
7613 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7614 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7615 Body = WS->getBody();
7616 DiagID = diag::warn_empty_while_body;
7617 } else
7618 return; // Neither `for' nor `while'.
7619
7620 // The body should be a null statement.
7621 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7622 if (!NBody)
7623 return;
7624
7625 // Skip expensive checks if diagnostic is disabled.
7626 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7627 DiagnosticsEngine::Ignored)
7628 return;
7629
7630 // Do the usual checks.
7631 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7632 return;
7633
7634 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7635 // noise level low, emit diagnostics only if for/while is followed by a
7636 // CompoundStmt, e.g.:
7637 // for (int i = 0; i < n; i++);
7638 // {
7639 // a(i);
7640 // }
7641 // or if for/while is followed by a statement with more indentation
7642 // than for/while itself:
7643 // for (int i = 0; i < n; i++);
7644 // a(i);
7645 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7646 if (!ProbableTypo) {
7647 bool BodyColInvalid;
7648 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7649 PossibleBody->getLocStart(),
7650 &BodyColInvalid);
7651 if (BodyColInvalid)
7652 return;
7653
7654 bool StmtColInvalid;
7655 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7656 S->getLocStart(),
7657 &StmtColInvalid);
7658 if (StmtColInvalid)
7659 return;
7660
7661 if (BodyCol > StmtCol)
7662 ProbableTypo = true;
7663 }
7664
7665 if (ProbableTypo) {
7666 Diag(NBody->getSemiLoc(), DiagID);
7667 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7668 }
7669}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007670
7671//===--- Layout compatibility ----------------------------------------------//
7672
7673namespace {
7674
7675bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7676
7677/// \brief Check if two enumeration types are layout-compatible.
7678bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7679 // C++11 [dcl.enum] p8:
7680 // Two enumeration types are layout-compatible if they have the same
7681 // underlying type.
7682 return ED1->isComplete() && ED2->isComplete() &&
7683 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7684}
7685
7686/// \brief Check if two fields are layout-compatible.
7687bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7688 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7689 return false;
7690
7691 if (Field1->isBitField() != Field2->isBitField())
7692 return false;
7693
7694 if (Field1->isBitField()) {
7695 // Make sure that the bit-fields are the same length.
7696 unsigned Bits1 = Field1->getBitWidthValue(C);
7697 unsigned Bits2 = Field2->getBitWidthValue(C);
7698
7699 if (Bits1 != Bits2)
7700 return false;
7701 }
7702
7703 return true;
7704}
7705
7706/// \brief Check if two standard-layout structs are layout-compatible.
7707/// (C++11 [class.mem] p17)
7708bool isLayoutCompatibleStruct(ASTContext &C,
7709 RecordDecl *RD1,
7710 RecordDecl *RD2) {
7711 // If both records are C++ classes, check that base classes match.
7712 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7713 // If one of records is a CXXRecordDecl we are in C++ mode,
7714 // thus the other one is a CXXRecordDecl, too.
7715 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7716 // Check number of base classes.
7717 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7718 return false;
7719
7720 // Check the base classes.
7721 for (CXXRecordDecl::base_class_const_iterator
7722 Base1 = D1CXX->bases_begin(),
7723 BaseEnd1 = D1CXX->bases_end(),
7724 Base2 = D2CXX->bases_begin();
7725 Base1 != BaseEnd1;
7726 ++Base1, ++Base2) {
7727 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7728 return false;
7729 }
7730 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7731 // If only RD2 is a C++ class, it should have zero base classes.
7732 if (D2CXX->getNumBases() > 0)
7733 return false;
7734 }
7735
7736 // Check the fields.
7737 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7738 Field2End = RD2->field_end(),
7739 Field1 = RD1->field_begin(),
7740 Field1End = RD1->field_end();
7741 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7742 if (!isLayoutCompatible(C, *Field1, *Field2))
7743 return false;
7744 }
7745 if (Field1 != Field1End || Field2 != Field2End)
7746 return false;
7747
7748 return true;
7749}
7750
7751/// \brief Check if two standard-layout unions are layout-compatible.
7752/// (C++11 [class.mem] p18)
7753bool isLayoutCompatibleUnion(ASTContext &C,
7754 RecordDecl *RD1,
7755 RecordDecl *RD2) {
7756 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007757 for (auto *Field2 : RD2->fields())
7758 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007759
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007760 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007761 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7762 I = UnmatchedFields.begin(),
7763 E = UnmatchedFields.end();
7764
7765 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007766 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007767 bool Result = UnmatchedFields.erase(*I);
7768 (void) Result;
7769 assert(Result);
7770 break;
7771 }
7772 }
7773 if (I == E)
7774 return false;
7775 }
7776
7777 return UnmatchedFields.empty();
7778}
7779
7780bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7781 if (RD1->isUnion() != RD2->isUnion())
7782 return false;
7783
7784 if (RD1->isUnion())
7785 return isLayoutCompatibleUnion(C, RD1, RD2);
7786 else
7787 return isLayoutCompatibleStruct(C, RD1, RD2);
7788}
7789
7790/// \brief Check if two types are layout-compatible in C++11 sense.
7791bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7792 if (T1.isNull() || T2.isNull())
7793 return false;
7794
7795 // C++11 [basic.types] p11:
7796 // If two types T1 and T2 are the same type, then T1 and T2 are
7797 // layout-compatible types.
7798 if (C.hasSameType(T1, T2))
7799 return true;
7800
7801 T1 = T1.getCanonicalType().getUnqualifiedType();
7802 T2 = T2.getCanonicalType().getUnqualifiedType();
7803
7804 const Type::TypeClass TC1 = T1->getTypeClass();
7805 const Type::TypeClass TC2 = T2->getTypeClass();
7806
7807 if (TC1 != TC2)
7808 return false;
7809
7810 if (TC1 == Type::Enum) {
7811 return isLayoutCompatible(C,
7812 cast<EnumType>(T1)->getDecl(),
7813 cast<EnumType>(T2)->getDecl());
7814 } else if (TC1 == Type::Record) {
7815 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7816 return false;
7817
7818 return isLayoutCompatible(C,
7819 cast<RecordType>(T1)->getDecl(),
7820 cast<RecordType>(T2)->getDecl());
7821 }
7822
7823 return false;
7824}
7825}
7826
7827//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7828
7829namespace {
7830/// \brief Given a type tag expression find the type tag itself.
7831///
7832/// \param TypeExpr Type tag expression, as it appears in user's code.
7833///
7834/// \param VD Declaration of an identifier that appears in a type tag.
7835///
7836/// \param MagicValue Type tag magic value.
7837bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7838 const ValueDecl **VD, uint64_t *MagicValue) {
7839 while(true) {
7840 if (!TypeExpr)
7841 return false;
7842
7843 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7844
7845 switch (TypeExpr->getStmtClass()) {
7846 case Stmt::UnaryOperatorClass: {
7847 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7848 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7849 TypeExpr = UO->getSubExpr();
7850 continue;
7851 }
7852 return false;
7853 }
7854
7855 case Stmt::DeclRefExprClass: {
7856 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7857 *VD = DRE->getDecl();
7858 return true;
7859 }
7860
7861 case Stmt::IntegerLiteralClass: {
7862 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7863 llvm::APInt MagicValueAPInt = IL->getValue();
7864 if (MagicValueAPInt.getActiveBits() <= 64) {
7865 *MagicValue = MagicValueAPInt.getZExtValue();
7866 return true;
7867 } else
7868 return false;
7869 }
7870
7871 case Stmt::BinaryConditionalOperatorClass:
7872 case Stmt::ConditionalOperatorClass: {
7873 const AbstractConditionalOperator *ACO =
7874 cast<AbstractConditionalOperator>(TypeExpr);
7875 bool Result;
7876 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7877 if (Result)
7878 TypeExpr = ACO->getTrueExpr();
7879 else
7880 TypeExpr = ACO->getFalseExpr();
7881 continue;
7882 }
7883 return false;
7884 }
7885
7886 case Stmt::BinaryOperatorClass: {
7887 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7888 if (BO->getOpcode() == BO_Comma) {
7889 TypeExpr = BO->getRHS();
7890 continue;
7891 }
7892 return false;
7893 }
7894
7895 default:
7896 return false;
7897 }
7898 }
7899}
7900
7901/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7902///
7903/// \param TypeExpr Expression that specifies a type tag.
7904///
7905/// \param MagicValues Registered magic values.
7906///
7907/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7908/// kind.
7909///
7910/// \param TypeInfo Information about the corresponding C type.
7911///
7912/// \returns true if the corresponding C type was found.
7913bool GetMatchingCType(
7914 const IdentifierInfo *ArgumentKind,
7915 const Expr *TypeExpr, const ASTContext &Ctx,
7916 const llvm::DenseMap<Sema::TypeTagMagicValue,
7917 Sema::TypeTagData> *MagicValues,
7918 bool &FoundWrongKind,
7919 Sema::TypeTagData &TypeInfo) {
7920 FoundWrongKind = false;
7921
7922 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00007923 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007924
7925 uint64_t MagicValue;
7926
7927 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7928 return false;
7929
7930 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00007931 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007932 if (I->getArgumentKind() != ArgumentKind) {
7933 FoundWrongKind = true;
7934 return false;
7935 }
7936 TypeInfo.Type = I->getMatchingCType();
7937 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7938 TypeInfo.MustBeNull = I->getMustBeNull();
7939 return true;
7940 }
7941 return false;
7942 }
7943
7944 if (!MagicValues)
7945 return false;
7946
7947 llvm::DenseMap<Sema::TypeTagMagicValue,
7948 Sema::TypeTagData>::const_iterator I =
7949 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7950 if (I == MagicValues->end())
7951 return false;
7952
7953 TypeInfo = I->second;
7954 return true;
7955}
7956} // unnamed namespace
7957
7958void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7959 uint64_t MagicValue, QualType Type,
7960 bool LayoutCompatible,
7961 bool MustBeNull) {
7962 if (!TypeTagForDatatypeMagicValues)
7963 TypeTagForDatatypeMagicValues.reset(
7964 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7965
7966 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7967 (*TypeTagForDatatypeMagicValues)[Magic] =
7968 TypeTagData(Type, LayoutCompatible, MustBeNull);
7969}
7970
7971namespace {
7972bool IsSameCharType(QualType T1, QualType T2) {
7973 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7974 if (!BT1)
7975 return false;
7976
7977 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7978 if (!BT2)
7979 return false;
7980
7981 BuiltinType::Kind T1Kind = BT1->getKind();
7982 BuiltinType::Kind T2Kind = BT2->getKind();
7983
7984 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7985 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7986 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7987 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7988}
7989} // unnamed namespace
7990
7991void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7992 const Expr * const *ExprArgs) {
7993 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7994 bool IsPointerAttr = Attr->getIsPointer();
7995
7996 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7997 bool FoundWrongKind;
7998 TypeTagData TypeInfo;
7999 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8000 TypeTagForDatatypeMagicValues.get(),
8001 FoundWrongKind, TypeInfo)) {
8002 if (FoundWrongKind)
8003 Diag(TypeTagExpr->getExprLoc(),
8004 diag::warn_type_tag_for_datatype_wrong_kind)
8005 << TypeTagExpr->getSourceRange();
8006 return;
8007 }
8008
8009 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8010 if (IsPointerAttr) {
8011 // Skip implicit cast of pointer to `void *' (as a function argument).
8012 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008013 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008014 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008015 ArgumentExpr = ICE->getSubExpr();
8016 }
8017 QualType ArgumentType = ArgumentExpr->getType();
8018
8019 // Passing a `void*' pointer shouldn't trigger a warning.
8020 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8021 return;
8022
8023 if (TypeInfo.MustBeNull) {
8024 // Type tag with matching void type requires a null pointer.
8025 if (!ArgumentExpr->isNullPointerConstant(Context,
8026 Expr::NPC_ValueDependentIsNotNull)) {
8027 Diag(ArgumentExpr->getExprLoc(),
8028 diag::warn_type_safety_null_pointer_required)
8029 << ArgumentKind->getName()
8030 << ArgumentExpr->getSourceRange()
8031 << TypeTagExpr->getSourceRange();
8032 }
8033 return;
8034 }
8035
8036 QualType RequiredType = TypeInfo.Type;
8037 if (IsPointerAttr)
8038 RequiredType = Context.getPointerType(RequiredType);
8039
8040 bool mismatch = false;
8041 if (!TypeInfo.LayoutCompatible) {
8042 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8043
8044 // C++11 [basic.fundamental] p1:
8045 // Plain char, signed char, and unsigned char are three distinct types.
8046 //
8047 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8048 // char' depending on the current char signedness mode.
8049 if (mismatch)
8050 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8051 RequiredType->getPointeeType())) ||
8052 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8053 mismatch = false;
8054 } else
8055 if (IsPointerAttr)
8056 mismatch = !isLayoutCompatible(Context,
8057 ArgumentType->getPointeeType(),
8058 RequiredType->getPointeeType());
8059 else
8060 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8061
8062 if (mismatch)
8063 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008064 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008065 << TypeInfo.LayoutCompatible << RequiredType
8066 << ArgumentExpr->getSourceRange()
8067 << TypeTagExpr->getSourceRange();
8068}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008069