blob: 976f3a696dfb3b2d89febcb9f8ace1b73fce075a [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 Northover3acd6bd2014-07-02 12:56:02 +0000489 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000490 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000491 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000492 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000493 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
494 BuiltinID == AArch64::BI__builtin_arm_strex ||
495 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000496 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000497 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000498 BuiltinID == ARM::BI__builtin_arm_ldaex ||
499 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
500 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000501
502 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
503
504 // Ensure that we have the proper number of arguments.
505 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
506 return true;
507
508 // Inspect the pointer argument of the atomic builtin. This should always be
509 // a pointer type, whose element is an integral scalar or pointer type.
510 // Because it is a pointer type, we don't have to worry about any implicit
511 // casts here.
512 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
513 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
514 if (PointerArgRes.isInvalid())
515 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000516 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000517
518 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
519 if (!pointerType) {
520 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
521 << PointerArg->getType() << PointerArg->getSourceRange();
522 return true;
523 }
524
525 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
526 // task is to insert the appropriate casts into the AST. First work out just
527 // what the appropriate type is.
528 QualType ValType = pointerType->getPointeeType();
529 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
530 if (IsLdrex)
531 AddrType.addConst();
532
533 // Issue a warning if the cast is dodgy.
534 CastKind CastNeeded = CK_NoOp;
535 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
536 CastNeeded = CK_BitCast;
537 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
538 << PointerArg->getType()
539 << Context.getPointerType(AddrType)
540 << AA_Passing << PointerArg->getSourceRange();
541 }
542
543 // Finally, do the cast and replace the argument with the corrected version.
544 AddrType = Context.getPointerType(AddrType);
545 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
546 if (PointerArgRes.isInvalid())
547 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000548 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000549
550 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
551
552 // In general, we allow ints, floats and pointers to be loaded and stored.
553 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
554 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
555 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
556 << PointerArg->getType() << PointerArg->getSourceRange();
557 return true;
558 }
559
560 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000561 if (Context.getTypeSize(ValType) > MaxWidth) {
562 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000563 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
564 << PointerArg->getType() << PointerArg->getSourceRange();
565 return true;
566 }
567
568 switch (ValType.getObjCLifetime()) {
569 case Qualifiers::OCL_None:
570 case Qualifiers::OCL_ExplicitNone:
571 // okay
572 break;
573
574 case Qualifiers::OCL_Weak:
575 case Qualifiers::OCL_Strong:
576 case Qualifiers::OCL_Autoreleasing:
577 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
578 << ValType << PointerArg->getSourceRange();
579 return true;
580 }
581
582
583 if (IsLdrex) {
584 TheCall->setType(ValType);
585 return false;
586 }
587
588 // Initialize the argument to be stored.
589 ExprResult ValArg = TheCall->getArg(0);
590 InitializedEntity Entity = InitializedEntity::InitializeParameter(
591 Context, ValType, /*consume*/ false);
592 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
593 if (ValArg.isInvalid())
594 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000595 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000596
597 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
598 // but the custom checker bypasses all default analysis.
599 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000600 return false;
601}
602
Nate Begeman4904e322010-06-08 02:47:44 +0000603bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000604 llvm::APSInt Result;
605
Tim Northover6aacd492013-07-16 09:47:53 +0000606 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000607 BuiltinID == ARM::BI__builtin_arm_ldaex ||
608 BuiltinID == ARM::BI__builtin_arm_strex ||
609 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000610 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000611 }
612
Tim Northover12670412014-02-19 10:37:05 +0000613 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
614 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000615
Yi Kong4efadfb2014-07-03 16:01:25 +0000616 // For intrinsics which take an immediate value as part of the instruction,
617 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000618 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000619 switch (BuiltinID) {
620 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000621 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
622 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000623 case ARM::BI__builtin_arm_vcvtr_f:
624 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000625 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000626 case ARM::BI__builtin_arm_dsb:
627 case ARM::BI__builtin_arm_isb: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000628 }
Nate Begemand773fe62010-06-13 04:47:52 +0000629
Nate Begemanf568b072010-08-03 21:32:34 +0000630 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000631 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000632}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000633
Tim Northover573cbee2014-05-24 12:52:07 +0000634bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000635 CallExpr *TheCall) {
636 llvm::APSInt Result;
637
Tim Northover573cbee2014-05-24 12:52:07 +0000638 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000639 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
640 BuiltinID == AArch64::BI__builtin_arm_strex ||
641 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000642 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
643 }
644
645 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
646 return true;
647
648 return false;
649}
650
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000651bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
652 unsigned i = 0, l = 0, u = 0;
653 switch (BuiltinID) {
654 default: return false;
655 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
656 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000657 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
658 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
659 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
660 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
661 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000662 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000663
Richard Sandiford28940af2014-04-16 08:47:51 +0000664 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000665}
666
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000667bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
668 switch (BuiltinID) {
669 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000670 // This is declared to take (const char*, int)
671 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000672 }
673 return false;
674}
675
Richard Smith55ce3522012-06-25 20:30:08 +0000676/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
677/// parameter with the FormatAttr's correct format_idx and firstDataArg.
678/// Returns true when the format fits the function and the FormatStringInfo has
679/// been populated.
680bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
681 FormatStringInfo *FSI) {
682 FSI->HasVAListArg = Format->getFirstArg() == 0;
683 FSI->FormatIdx = Format->getFormatIdx() - 1;
684 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000685
Richard Smith55ce3522012-06-25 20:30:08 +0000686 // The way the format attribute works in GCC, the implicit this argument
687 // of member functions is counted. However, it doesn't appear in our own
688 // lists, so decrement format_idx in that case.
689 if (IsCXXMember) {
690 if(FSI->FormatIdx == 0)
691 return false;
692 --FSI->FormatIdx;
693 if (FSI->FirstDataArg != 0)
694 --FSI->FirstDataArg;
695 }
696 return true;
697}
Mike Stump11289f42009-09-09 15:08:12 +0000698
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000699/// Checks if a the given expression evaluates to null.
700///
701/// \brief Returns true if the value evaluates to null.
702static bool CheckNonNullExpr(Sema &S,
703 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000704 // As a special case, transparent unions initialized with zero are
705 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000706 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000707 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
708 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000709 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000710 if (const InitListExpr *ILE =
711 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000712 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000713 }
714
715 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000716 return (!Expr->isValueDependent() &&
717 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
718 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000719}
720
721static void CheckNonNullArgument(Sema &S,
722 const Expr *ArgExpr,
723 SourceLocation CallSiteLoc) {
724 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000725 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
726}
727
Ted Kremenek2bc73332014-01-17 06:24:43 +0000728static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000729 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000730 const Expr * const *ExprArgs,
731 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000732 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000733 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000734 for (const auto &Val : NonNull->args())
735 CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000736 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000737
738 // Check the attributes on the parameters.
739 ArrayRef<ParmVarDecl*> parms;
740 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
741 parms = FD->parameters();
742 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
743 parms = MD->parameters();
744
745 unsigned argIndex = 0;
746 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
747 I != E; ++I, ++argIndex) {
748 const ParmVarDecl *PVD = *I;
749 if (PVD->hasAttr<NonNullAttr>())
750 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
751 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000752}
753
Richard Smith55ce3522012-06-25 20:30:08 +0000754/// Handles the checks for format strings, non-POD arguments to vararg
755/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000756void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
757 unsigned NumParams, bool IsMemberFunction,
758 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000759 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000760 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000761 if (CurContext->isDependentContext())
762 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000763
Ted Kremenekb8176da2010-09-09 04:33:05 +0000764 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000765 llvm::SmallBitVector CheckedVarArgs;
766 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000767 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000768 // Only create vector if there are format attributes.
769 CheckedVarArgs.resize(Args.size());
770
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000771 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000772 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000773 }
Richard Smithd7293d72013-08-05 18:49:43 +0000774 }
Richard Smith55ce3522012-06-25 20:30:08 +0000775
776 // Refuse POD arguments that weren't caught by the format string
777 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000778 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000779 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000780 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000781 if (const Expr *Arg = Args[ArgIdx]) {
782 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
783 checkVariadicArgument(Arg, CallType);
784 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000785 }
Richard Smithd7293d72013-08-05 18:49:43 +0000786 }
Mike Stump11289f42009-09-09 15:08:12 +0000787
Richard Trieu41bc0992013-06-22 00:20:41 +0000788 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000789 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000790
Richard Trieu41bc0992013-06-22 00:20:41 +0000791 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000792 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
793 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000794 }
Richard Smith55ce3522012-06-25 20:30:08 +0000795}
796
797/// CheckConstructorCall - Check a constructor call for correctness and safety
798/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000799void Sema::CheckConstructorCall(FunctionDecl *FDecl,
800 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000801 const FunctionProtoType *Proto,
802 SourceLocation Loc) {
803 VariadicCallType CallType =
804 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000805 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000806 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
807}
808
809/// CheckFunctionCall - Check a direct function call for various correctness
810/// and safety properties not strictly enforced by the C type system.
811bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
812 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000813 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
814 isa<CXXMethodDecl>(FDecl);
815 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
816 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000817 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
818 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000819 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000820 Expr** Args = TheCall->getArgs();
821 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000822 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000823 // If this is a call to a member operator, hide the first argument
824 // from checkCall.
825 // FIXME: Our choice of AST representation here is less than ideal.
826 ++Args;
827 --NumArgs;
828 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000829 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000830 IsMemberFunction, TheCall->getRParenLoc(),
831 TheCall->getCallee()->getSourceRange(), CallType);
832
833 IdentifierInfo *FnInfo = FDecl->getIdentifier();
834 // None of the checks below are needed for functions that don't have
835 // simple names (e.g., C++ conversion functions).
836 if (!FnInfo)
837 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000838
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000839 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
840
Anna Zaks22122702012-01-17 00:37:07 +0000841 unsigned CMId = FDecl->getMemoryFunctionKind();
842 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000843 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000844
Anna Zaks201d4892012-01-13 21:52:01 +0000845 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000846 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000847 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000848 else if (CMId == Builtin::BIstrncat)
849 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000850 else
Anna Zaks22122702012-01-17 00:37:07 +0000851 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000852
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000853 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000854}
855
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000856bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000857 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000858 VariadicCallType CallType =
859 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000860
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000861 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000862 /*IsMemberFunction=*/false,
863 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000864
865 return false;
866}
867
Richard Trieu664c4c62013-06-20 21:03:13 +0000868bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
869 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000870 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
871 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000872 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000873
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000874 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000875 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000876 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000877
Richard Trieu664c4c62013-06-20 21:03:13 +0000878 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000879 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000880 CallType = VariadicDoesNotApply;
881 } else if (Ty->isBlockPointerType()) {
882 CallType = VariadicBlock;
883 } else { // Ty->isFunctionPointerType()
884 CallType = VariadicFunction;
885 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000886 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000887
Alp Toker9cacbab2014-01-20 20:26:09 +0000888 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
889 TheCall->getNumArgs()),
890 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000891 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000892
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000893 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000894}
895
Richard Trieu41bc0992013-06-22 00:20:41 +0000896/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
897/// such as function pointers returned from functions.
898bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000899 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +0000900 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000901 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000902
Craig Topperc3ec1492014-05-26 06:22:03 +0000903 checkCall(/*FDecl=*/nullptr,
904 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
905 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +0000906 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000907 TheCall->getCallee()->getSourceRange(), CallType);
908
909 return false;
910}
911
Tim Northovere94a34c2014-03-11 10:49:14 +0000912static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
913 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
914 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
915 return false;
916
917 switch (Op) {
918 case AtomicExpr::AO__c11_atomic_init:
919 llvm_unreachable("There is no ordering argument for an init");
920
921 case AtomicExpr::AO__c11_atomic_load:
922 case AtomicExpr::AO__atomic_load_n:
923 case AtomicExpr::AO__atomic_load:
924 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
925 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
926
927 case AtomicExpr::AO__c11_atomic_store:
928 case AtomicExpr::AO__atomic_store:
929 case AtomicExpr::AO__atomic_store_n:
930 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
931 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
932 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
933
934 default:
935 return true;
936 }
937}
938
Richard Smithfeea8832012-04-12 05:08:17 +0000939ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
940 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000941 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
942 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000943
Richard Smithfeea8832012-04-12 05:08:17 +0000944 // All these operations take one of the following forms:
945 enum {
946 // C __c11_atomic_init(A *, C)
947 Init,
948 // C __c11_atomic_load(A *, int)
949 Load,
950 // void __atomic_load(A *, CP, int)
951 Copy,
952 // C __c11_atomic_add(A *, M, int)
953 Arithmetic,
954 // C __atomic_exchange_n(A *, CP, int)
955 Xchg,
956 // void __atomic_exchange(A *, C *, CP, int)
957 GNUXchg,
958 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
959 C11CmpXchg,
960 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
961 GNUCmpXchg
962 } Form = Init;
963 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
964 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
965 // where:
966 // C is an appropriate type,
967 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
968 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
969 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
970 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000971
Richard Smithfeea8832012-04-12 05:08:17 +0000972 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
973 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
974 && "need to update code for modified C11 atomics");
975 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
976 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
977 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
978 Op == AtomicExpr::AO__atomic_store_n ||
979 Op == AtomicExpr::AO__atomic_exchange_n ||
980 Op == AtomicExpr::AO__atomic_compare_exchange_n;
981 bool IsAddSub = false;
982
983 switch (Op) {
984 case AtomicExpr::AO__c11_atomic_init:
985 Form = Init;
986 break;
987
988 case AtomicExpr::AO__c11_atomic_load:
989 case AtomicExpr::AO__atomic_load_n:
990 Form = Load;
991 break;
992
993 case AtomicExpr::AO__c11_atomic_store:
994 case AtomicExpr::AO__atomic_load:
995 case AtomicExpr::AO__atomic_store:
996 case AtomicExpr::AO__atomic_store_n:
997 Form = Copy;
998 break;
999
1000 case AtomicExpr::AO__c11_atomic_fetch_add:
1001 case AtomicExpr::AO__c11_atomic_fetch_sub:
1002 case AtomicExpr::AO__atomic_fetch_add:
1003 case AtomicExpr::AO__atomic_fetch_sub:
1004 case AtomicExpr::AO__atomic_add_fetch:
1005 case AtomicExpr::AO__atomic_sub_fetch:
1006 IsAddSub = true;
1007 // Fall through.
1008 case AtomicExpr::AO__c11_atomic_fetch_and:
1009 case AtomicExpr::AO__c11_atomic_fetch_or:
1010 case AtomicExpr::AO__c11_atomic_fetch_xor:
1011 case AtomicExpr::AO__atomic_fetch_and:
1012 case AtomicExpr::AO__atomic_fetch_or:
1013 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001014 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001015 case AtomicExpr::AO__atomic_and_fetch:
1016 case AtomicExpr::AO__atomic_or_fetch:
1017 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001018 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001019 Form = Arithmetic;
1020 break;
1021
1022 case AtomicExpr::AO__c11_atomic_exchange:
1023 case AtomicExpr::AO__atomic_exchange_n:
1024 Form = Xchg;
1025 break;
1026
1027 case AtomicExpr::AO__atomic_exchange:
1028 Form = GNUXchg;
1029 break;
1030
1031 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1032 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1033 Form = C11CmpXchg;
1034 break;
1035
1036 case AtomicExpr::AO__atomic_compare_exchange:
1037 case AtomicExpr::AO__atomic_compare_exchange_n:
1038 Form = GNUCmpXchg;
1039 break;
1040 }
1041
1042 // Check we have the right number of arguments.
1043 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001044 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001045 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001046 << TheCall->getCallee()->getSourceRange();
1047 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001048 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1049 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001050 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001051 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001052 << TheCall->getCallee()->getSourceRange();
1053 return ExprError();
1054 }
1055
Richard Smithfeea8832012-04-12 05:08:17 +00001056 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001057 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001058 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1059 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1060 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001061 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001062 << Ptr->getType() << Ptr->getSourceRange();
1063 return ExprError();
1064 }
1065
Richard Smithfeea8832012-04-12 05:08:17 +00001066 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1067 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1068 QualType ValType = AtomTy; // 'C'
1069 if (IsC11) {
1070 if (!AtomTy->isAtomicType()) {
1071 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1072 << Ptr->getType() << Ptr->getSourceRange();
1073 return ExprError();
1074 }
Richard Smithe00921a2012-09-15 06:09:58 +00001075 if (AtomTy.isConstQualified()) {
1076 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1077 << Ptr->getType() << Ptr->getSourceRange();
1078 return ExprError();
1079 }
Richard Smithfeea8832012-04-12 05:08:17 +00001080 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001081 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001082
Richard Smithfeea8832012-04-12 05:08:17 +00001083 // For an arithmetic operation, the implied arithmetic must be well-formed.
1084 if (Form == Arithmetic) {
1085 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1086 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1087 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1088 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1089 return ExprError();
1090 }
1091 if (!IsAddSub && !ValType->isIntegerType()) {
1092 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1093 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1094 return ExprError();
1095 }
1096 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1097 // For __atomic_*_n operations, the value type must be a scalar integral or
1098 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001099 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001100 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1101 return ExprError();
1102 }
1103
Eli Friedmanaa769812013-09-11 03:49:34 +00001104 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1105 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001106 // For GNU atomics, require a trivially-copyable type. This is not part of
1107 // the GNU atomics specification, but we enforce it for sanity.
1108 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001109 << Ptr->getType() << Ptr->getSourceRange();
1110 return ExprError();
1111 }
1112
Richard Smithfeea8832012-04-12 05:08:17 +00001113 // FIXME: For any builtin other than a load, the ValType must not be
1114 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001115
1116 switch (ValType.getObjCLifetime()) {
1117 case Qualifiers::OCL_None:
1118 case Qualifiers::OCL_ExplicitNone:
1119 // okay
1120 break;
1121
1122 case Qualifiers::OCL_Weak:
1123 case Qualifiers::OCL_Strong:
1124 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001125 // FIXME: Can this happen? By this point, ValType should be known
1126 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001127 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1128 << ValType << Ptr->getSourceRange();
1129 return ExprError();
1130 }
1131
1132 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001133 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001134 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001135 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001136 ResultType = Context.BoolTy;
1137
Richard Smithfeea8832012-04-12 05:08:17 +00001138 // The type of a parameter passed 'by value'. In the GNU atomics, such
1139 // arguments are actually passed as pointers.
1140 QualType ByValType = ValType; // 'CP'
1141 if (!IsC11 && !IsN)
1142 ByValType = Ptr->getType();
1143
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001144 // The first argument --- the pointer --- has a fixed type; we
1145 // deduce the types of the rest of the arguments accordingly. Walk
1146 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001147 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001148 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001149 if (i < NumVals[Form] + 1) {
1150 switch (i) {
1151 case 1:
1152 // The second argument is the non-atomic operand. For arithmetic, this
1153 // is always passed by value, and for a compare_exchange it is always
1154 // passed by address. For the rest, GNU uses by-address and C11 uses
1155 // by-value.
1156 assert(Form != Load);
1157 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1158 Ty = ValType;
1159 else if (Form == Copy || Form == Xchg)
1160 Ty = ByValType;
1161 else if (Form == Arithmetic)
1162 Ty = Context.getPointerDiffType();
1163 else
1164 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1165 break;
1166 case 2:
1167 // The third argument to compare_exchange / GNU exchange is a
1168 // (pointer to a) desired value.
1169 Ty = ByValType;
1170 break;
1171 case 3:
1172 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1173 Ty = Context.BoolTy;
1174 break;
1175 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001176 } else {
1177 // The order(s) are always converted to int.
1178 Ty = Context.IntTy;
1179 }
Richard Smithfeea8832012-04-12 05:08:17 +00001180
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001181 InitializedEntity Entity =
1182 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001183 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001184 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1185 if (Arg.isInvalid())
1186 return true;
1187 TheCall->setArg(i, Arg.get());
1188 }
1189
Richard Smithfeea8832012-04-12 05:08:17 +00001190 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001191 SmallVector<Expr*, 5> SubExprs;
1192 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001193 switch (Form) {
1194 case Init:
1195 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001196 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001197 break;
1198 case Load:
1199 SubExprs.push_back(TheCall->getArg(1)); // Order
1200 break;
1201 case Copy:
1202 case Arithmetic:
1203 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001204 SubExprs.push_back(TheCall->getArg(2)); // Order
1205 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001206 break;
1207 case GNUXchg:
1208 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1209 SubExprs.push_back(TheCall->getArg(3)); // Order
1210 SubExprs.push_back(TheCall->getArg(1)); // Val1
1211 SubExprs.push_back(TheCall->getArg(2)); // Val2
1212 break;
1213 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001214 SubExprs.push_back(TheCall->getArg(3)); // Order
1215 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001216 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001217 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001218 break;
1219 case GNUCmpXchg:
1220 SubExprs.push_back(TheCall->getArg(4)); // Order
1221 SubExprs.push_back(TheCall->getArg(1)); // Val1
1222 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1223 SubExprs.push_back(TheCall->getArg(2)); // Val2
1224 SubExprs.push_back(TheCall->getArg(3)); // Weak
1225 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001226 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001227
1228 if (SubExprs.size() >= 2 && Form != Init) {
1229 llvm::APSInt Result(32);
1230 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1231 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001232 Diag(SubExprs[1]->getLocStart(),
1233 diag::warn_atomic_op_has_invalid_memory_order)
1234 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001235 }
1236
Fariborz Jahanian615de762013-05-28 17:37:39 +00001237 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1238 SubExprs, ResultType, Op,
1239 TheCall->getRParenLoc());
1240
1241 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1242 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1243 Context.AtomicUsesUnsupportedLibcall(AE))
1244 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1245 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001246
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001247 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001248}
1249
1250
John McCall29ad95b2011-08-27 01:09:30 +00001251/// checkBuiltinArgument - Given a call to a builtin function, perform
1252/// normal type-checking on the given argument, updating the call in
1253/// place. This is useful when a builtin function requires custom
1254/// type-checking for some of its arguments but not necessarily all of
1255/// them.
1256///
1257/// Returns true on error.
1258static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1259 FunctionDecl *Fn = E->getDirectCallee();
1260 assert(Fn && "builtin call without direct callee!");
1261
1262 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1263 InitializedEntity Entity =
1264 InitializedEntity::InitializeParameter(S.Context, Param);
1265
1266 ExprResult Arg = E->getArg(0);
1267 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1268 if (Arg.isInvalid())
1269 return true;
1270
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001271 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001272 return false;
1273}
1274
Chris Lattnerdc046542009-05-08 06:58:22 +00001275/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1276/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1277/// type of its first argument. The main ActOnCallExpr routines have already
1278/// promoted the types of arguments because all of these calls are prototyped as
1279/// void(...).
1280///
1281/// This function goes through and does final semantic checking for these
1282/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001283ExprResult
1284Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001285 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001286 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1287 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1288
1289 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001290 if (TheCall->getNumArgs() < 1) {
1291 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1292 << 0 << 1 << TheCall->getNumArgs()
1293 << TheCall->getCallee()->getSourceRange();
1294 return ExprError();
1295 }
Mike Stump11289f42009-09-09 15:08:12 +00001296
Chris Lattnerdc046542009-05-08 06:58:22 +00001297 // Inspect the first argument of the atomic builtin. This should always be
1298 // a pointer type, whose element is an integral scalar or pointer type.
1299 // Because it is a pointer type, we don't have to worry about any implicit
1300 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001301 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001302 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001303 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1304 if (FirstArgResult.isInvalid())
1305 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001306 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001307 TheCall->setArg(0, FirstArg);
1308
John McCall31168b02011-06-15 23:02:42 +00001309 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1310 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001311 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1312 << FirstArg->getType() << FirstArg->getSourceRange();
1313 return ExprError();
1314 }
Mike Stump11289f42009-09-09 15:08:12 +00001315
John McCall31168b02011-06-15 23:02:42 +00001316 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001317 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001318 !ValType->isBlockPointerType()) {
1319 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1320 << FirstArg->getType() << FirstArg->getSourceRange();
1321 return ExprError();
1322 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001323
John McCall31168b02011-06-15 23:02:42 +00001324 switch (ValType.getObjCLifetime()) {
1325 case Qualifiers::OCL_None:
1326 case Qualifiers::OCL_ExplicitNone:
1327 // okay
1328 break;
1329
1330 case Qualifiers::OCL_Weak:
1331 case Qualifiers::OCL_Strong:
1332 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001333 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001334 << ValType << FirstArg->getSourceRange();
1335 return ExprError();
1336 }
1337
John McCallb50451a2011-10-05 07:41:44 +00001338 // Strip any qualifiers off ValType.
1339 ValType = ValType.getUnqualifiedType();
1340
Chandler Carruth3973af72010-07-18 20:54:12 +00001341 // The majority of builtins return a value, but a few have special return
1342 // types, so allow them to override appropriately below.
1343 QualType ResultType = ValType;
1344
Chris Lattnerdc046542009-05-08 06:58:22 +00001345 // We need to figure out which concrete builtin this maps onto. For example,
1346 // __sync_fetch_and_add with a 2 byte object turns into
1347 // __sync_fetch_and_add_2.
1348#define BUILTIN_ROW(x) \
1349 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1350 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001351
Chris Lattnerdc046542009-05-08 06:58:22 +00001352 static const unsigned BuiltinIndices[][5] = {
1353 BUILTIN_ROW(__sync_fetch_and_add),
1354 BUILTIN_ROW(__sync_fetch_and_sub),
1355 BUILTIN_ROW(__sync_fetch_and_or),
1356 BUILTIN_ROW(__sync_fetch_and_and),
1357 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001358
Chris Lattnerdc046542009-05-08 06:58:22 +00001359 BUILTIN_ROW(__sync_add_and_fetch),
1360 BUILTIN_ROW(__sync_sub_and_fetch),
1361 BUILTIN_ROW(__sync_and_and_fetch),
1362 BUILTIN_ROW(__sync_or_and_fetch),
1363 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001364
Chris Lattnerdc046542009-05-08 06:58:22 +00001365 BUILTIN_ROW(__sync_val_compare_and_swap),
1366 BUILTIN_ROW(__sync_bool_compare_and_swap),
1367 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001368 BUILTIN_ROW(__sync_lock_release),
1369 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001370 };
Mike Stump11289f42009-09-09 15:08:12 +00001371#undef BUILTIN_ROW
1372
Chris Lattnerdc046542009-05-08 06:58:22 +00001373 // Determine the index of the size.
1374 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001375 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001376 case 1: SizeIndex = 0; break;
1377 case 2: SizeIndex = 1; break;
1378 case 4: SizeIndex = 2; break;
1379 case 8: SizeIndex = 3; break;
1380 case 16: SizeIndex = 4; break;
1381 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001382 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1383 << FirstArg->getType() << FirstArg->getSourceRange();
1384 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001385 }
Mike Stump11289f42009-09-09 15:08:12 +00001386
Chris Lattnerdc046542009-05-08 06:58:22 +00001387 // Each of these builtins has one pointer argument, followed by some number of
1388 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1389 // that we ignore. Find out which row of BuiltinIndices to read from as well
1390 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001391 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001392 unsigned BuiltinIndex, NumFixed = 1;
1393 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001394 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001395 case Builtin::BI__sync_fetch_and_add:
1396 case Builtin::BI__sync_fetch_and_add_1:
1397 case Builtin::BI__sync_fetch_and_add_2:
1398 case Builtin::BI__sync_fetch_and_add_4:
1399 case Builtin::BI__sync_fetch_and_add_8:
1400 case Builtin::BI__sync_fetch_and_add_16:
1401 BuiltinIndex = 0;
1402 break;
1403
1404 case Builtin::BI__sync_fetch_and_sub:
1405 case Builtin::BI__sync_fetch_and_sub_1:
1406 case Builtin::BI__sync_fetch_and_sub_2:
1407 case Builtin::BI__sync_fetch_and_sub_4:
1408 case Builtin::BI__sync_fetch_and_sub_8:
1409 case Builtin::BI__sync_fetch_and_sub_16:
1410 BuiltinIndex = 1;
1411 break;
1412
1413 case Builtin::BI__sync_fetch_and_or:
1414 case Builtin::BI__sync_fetch_and_or_1:
1415 case Builtin::BI__sync_fetch_and_or_2:
1416 case Builtin::BI__sync_fetch_and_or_4:
1417 case Builtin::BI__sync_fetch_and_or_8:
1418 case Builtin::BI__sync_fetch_and_or_16:
1419 BuiltinIndex = 2;
1420 break;
1421
1422 case Builtin::BI__sync_fetch_and_and:
1423 case Builtin::BI__sync_fetch_and_and_1:
1424 case Builtin::BI__sync_fetch_and_and_2:
1425 case Builtin::BI__sync_fetch_and_and_4:
1426 case Builtin::BI__sync_fetch_and_and_8:
1427 case Builtin::BI__sync_fetch_and_and_16:
1428 BuiltinIndex = 3;
1429 break;
Mike Stump11289f42009-09-09 15:08:12 +00001430
Douglas Gregor73722482011-11-28 16:30:08 +00001431 case Builtin::BI__sync_fetch_and_xor:
1432 case Builtin::BI__sync_fetch_and_xor_1:
1433 case Builtin::BI__sync_fetch_and_xor_2:
1434 case Builtin::BI__sync_fetch_and_xor_4:
1435 case Builtin::BI__sync_fetch_and_xor_8:
1436 case Builtin::BI__sync_fetch_and_xor_16:
1437 BuiltinIndex = 4;
1438 break;
1439
1440 case Builtin::BI__sync_add_and_fetch:
1441 case Builtin::BI__sync_add_and_fetch_1:
1442 case Builtin::BI__sync_add_and_fetch_2:
1443 case Builtin::BI__sync_add_and_fetch_4:
1444 case Builtin::BI__sync_add_and_fetch_8:
1445 case Builtin::BI__sync_add_and_fetch_16:
1446 BuiltinIndex = 5;
1447 break;
1448
1449 case Builtin::BI__sync_sub_and_fetch:
1450 case Builtin::BI__sync_sub_and_fetch_1:
1451 case Builtin::BI__sync_sub_and_fetch_2:
1452 case Builtin::BI__sync_sub_and_fetch_4:
1453 case Builtin::BI__sync_sub_and_fetch_8:
1454 case Builtin::BI__sync_sub_and_fetch_16:
1455 BuiltinIndex = 6;
1456 break;
1457
1458 case Builtin::BI__sync_and_and_fetch:
1459 case Builtin::BI__sync_and_and_fetch_1:
1460 case Builtin::BI__sync_and_and_fetch_2:
1461 case Builtin::BI__sync_and_and_fetch_4:
1462 case Builtin::BI__sync_and_and_fetch_8:
1463 case Builtin::BI__sync_and_and_fetch_16:
1464 BuiltinIndex = 7;
1465 break;
1466
1467 case Builtin::BI__sync_or_and_fetch:
1468 case Builtin::BI__sync_or_and_fetch_1:
1469 case Builtin::BI__sync_or_and_fetch_2:
1470 case Builtin::BI__sync_or_and_fetch_4:
1471 case Builtin::BI__sync_or_and_fetch_8:
1472 case Builtin::BI__sync_or_and_fetch_16:
1473 BuiltinIndex = 8;
1474 break;
1475
1476 case Builtin::BI__sync_xor_and_fetch:
1477 case Builtin::BI__sync_xor_and_fetch_1:
1478 case Builtin::BI__sync_xor_and_fetch_2:
1479 case Builtin::BI__sync_xor_and_fetch_4:
1480 case Builtin::BI__sync_xor_and_fetch_8:
1481 case Builtin::BI__sync_xor_and_fetch_16:
1482 BuiltinIndex = 9;
1483 break;
Mike Stump11289f42009-09-09 15:08:12 +00001484
Chris Lattnerdc046542009-05-08 06:58:22 +00001485 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001486 case Builtin::BI__sync_val_compare_and_swap_1:
1487 case Builtin::BI__sync_val_compare_and_swap_2:
1488 case Builtin::BI__sync_val_compare_and_swap_4:
1489 case Builtin::BI__sync_val_compare_and_swap_8:
1490 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001491 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001492 NumFixed = 2;
1493 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001494
Chris Lattnerdc046542009-05-08 06:58:22 +00001495 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001496 case Builtin::BI__sync_bool_compare_and_swap_1:
1497 case Builtin::BI__sync_bool_compare_and_swap_2:
1498 case Builtin::BI__sync_bool_compare_and_swap_4:
1499 case Builtin::BI__sync_bool_compare_and_swap_8:
1500 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001501 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001502 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001503 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001504 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001505
1506 case Builtin::BI__sync_lock_test_and_set:
1507 case Builtin::BI__sync_lock_test_and_set_1:
1508 case Builtin::BI__sync_lock_test_and_set_2:
1509 case Builtin::BI__sync_lock_test_and_set_4:
1510 case Builtin::BI__sync_lock_test_and_set_8:
1511 case Builtin::BI__sync_lock_test_and_set_16:
1512 BuiltinIndex = 12;
1513 break;
1514
Chris Lattnerdc046542009-05-08 06:58:22 +00001515 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001516 case Builtin::BI__sync_lock_release_1:
1517 case Builtin::BI__sync_lock_release_2:
1518 case Builtin::BI__sync_lock_release_4:
1519 case Builtin::BI__sync_lock_release_8:
1520 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001521 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001522 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001523 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001524 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001525
1526 case Builtin::BI__sync_swap:
1527 case Builtin::BI__sync_swap_1:
1528 case Builtin::BI__sync_swap_2:
1529 case Builtin::BI__sync_swap_4:
1530 case Builtin::BI__sync_swap_8:
1531 case Builtin::BI__sync_swap_16:
1532 BuiltinIndex = 14;
1533 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
Chris Lattnerdc046542009-05-08 06:58:22 +00001536 // Now that we know how many fixed arguments we expect, first check that we
1537 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001538 if (TheCall->getNumArgs() < 1+NumFixed) {
1539 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1540 << 0 << 1+NumFixed << TheCall->getNumArgs()
1541 << TheCall->getCallee()->getSourceRange();
1542 return ExprError();
1543 }
Mike Stump11289f42009-09-09 15:08:12 +00001544
Chris Lattner5b9241b2009-05-08 15:36:58 +00001545 // Get the decl for the concrete builtin from this, we can tell what the
1546 // concrete integer type we should convert to is.
1547 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1548 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001549 FunctionDecl *NewBuiltinDecl;
1550 if (NewBuiltinID == BuiltinID)
1551 NewBuiltinDecl = FDecl;
1552 else {
1553 // Perform builtin lookup to avoid redeclaring it.
1554 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1555 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1556 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1557 assert(Res.getFoundDecl());
1558 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001559 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001560 return ExprError();
1561 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001562
John McCallcf142162010-08-07 06:22:56 +00001563 // The first argument --- the pointer --- has a fixed type; we
1564 // deduce the types of the rest of the arguments accordingly. Walk
1565 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001566 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001567 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001568
Chris Lattnerdc046542009-05-08 06:58:22 +00001569 // GCC does an implicit conversion to the pointer or integer ValType. This
1570 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001571 // Initialize the argument.
1572 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1573 ValType, /*consume*/ false);
1574 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001575 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001576 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001577
Chris Lattnerdc046542009-05-08 06:58:22 +00001578 // Okay, we have something that *can* be converted to the right type. Check
1579 // to see if there is a potentially weird extension going on here. This can
1580 // happen when you do an atomic operation on something like an char* and
1581 // pass in 42. The 42 gets converted to char. This is even more strange
1582 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001583 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001584 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001587 ASTContext& Context = this->getASTContext();
1588
1589 // Create a new DeclRefExpr to refer to the new decl.
1590 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1591 Context,
1592 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001593 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001594 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001595 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001596 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001597 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001598 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001599
Chris Lattnerdc046542009-05-08 06:58:22 +00001600 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001601 // FIXME: This loses syntactic information.
1602 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1603 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1604 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001605 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001606
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001607 // Change the result type of the call to match the original value type. This
1608 // is arbitrary, but the codegen for these builtins ins design to handle it
1609 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001610 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001611
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001612 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001613}
1614
Chris Lattner6436fb62009-02-18 06:01:06 +00001615/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001616/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001617/// Note: It might also make sense to do the UTF-16 conversion here (would
1618/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001619bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001620 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001621 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1622
Douglas Gregorfb65e592011-07-27 05:40:30 +00001623 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001624 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1625 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001626 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001627 }
Mike Stump11289f42009-09-09 15:08:12 +00001628
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001629 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001630 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001631 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001632 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001633 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001634 UTF16 *ToPtr = &ToBuf[0];
1635
1636 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1637 &ToPtr, ToPtr + NumBytes,
1638 strictConversion);
1639 // Check for conversion failure.
1640 if (Result != conversionOK)
1641 Diag(Arg->getLocStart(),
1642 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1643 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001644 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001645}
1646
Chris Lattnere202e6a2007-12-20 00:05:45 +00001647/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1648/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001649bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1650 Expr *Fn = TheCall->getCallee();
1651 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001652 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001653 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001654 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1655 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001656 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001657 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001658 return true;
1659 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001660
1661 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001662 return Diag(TheCall->getLocEnd(),
1663 diag::err_typecheck_call_too_few_args_at_least)
1664 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001665 }
1666
John McCall29ad95b2011-08-27 01:09:30 +00001667 // Type-check the first argument normally.
1668 if (checkBuiltinArgument(*this, TheCall, 0))
1669 return true;
1670
Chris Lattnere202e6a2007-12-20 00:05:45 +00001671 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001672 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001673 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001674 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001675 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001676 else if (FunctionDecl *FD = getCurFunctionDecl())
1677 isVariadic = FD->isVariadic();
1678 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001679 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001680
Chris Lattnere202e6a2007-12-20 00:05:45 +00001681 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001682 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1683 return true;
1684 }
Mike Stump11289f42009-09-09 15:08:12 +00001685
Chris Lattner43be2e62007-12-19 23:59:04 +00001686 // Verify that the second argument to the builtin is the last argument of the
1687 // current function or method.
1688 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001689 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001690
Nico Weber9eea7642013-05-24 23:31:57 +00001691 // These are valid if SecondArgIsLastNamedArgument is false after the next
1692 // block.
1693 QualType Type;
1694 SourceLocation ParamLoc;
1695
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001696 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1697 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001698 // FIXME: This isn't correct for methods (results in bogus warning).
1699 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001700 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001701 if (CurBlock)
1702 LastArg = *(CurBlock->TheDecl->param_end()-1);
1703 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001704 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001705 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001706 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001707 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001708
1709 Type = PV->getType();
1710 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001711 }
1712 }
Mike Stump11289f42009-09-09 15:08:12 +00001713
Chris Lattner43be2e62007-12-19 23:59:04 +00001714 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001715 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001716 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001717 else if (Type->isReferenceType()) {
1718 Diag(Arg->getLocStart(),
1719 diag::warn_va_start_of_reference_type_is_undefined);
1720 Diag(ParamLoc, diag::note_parameter_type) << Type;
1721 }
1722
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001723 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001724 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001725}
Chris Lattner43be2e62007-12-19 23:59:04 +00001726
Chris Lattner2da14fb2007-12-20 00:26:33 +00001727/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1728/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001729bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1730 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001731 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001732 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001733 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001734 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001735 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001736 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001737 << SourceRange(TheCall->getArg(2)->getLocStart(),
1738 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001739
John Wiegley01296292011-04-08 18:41:53 +00001740 ExprResult OrigArg0 = TheCall->getArg(0);
1741 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001742
Chris Lattner2da14fb2007-12-20 00:26:33 +00001743 // Do standard promotions between the two arguments, returning their common
1744 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001745 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001746 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1747 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001748
1749 // Make sure any conversions are pushed back into the call; this is
1750 // type safe since unordered compare builtins are declared as "_Bool
1751 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001752 TheCall->setArg(0, OrigArg0.get());
1753 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001754
John Wiegley01296292011-04-08 18:41:53 +00001755 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001756 return false;
1757
Chris Lattner2da14fb2007-12-20 00:26:33 +00001758 // If the common type isn't a real floating type, then the arguments were
1759 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001760 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001761 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001762 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001763 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1764 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001765
Chris Lattner2da14fb2007-12-20 00:26:33 +00001766 return false;
1767}
1768
Benjamin Kramer634fc102010-02-15 22:42:31 +00001769/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1770/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001771/// to check everything. We expect the last argument to be a floating point
1772/// value.
1773bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1774 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001775 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001776 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001777 if (TheCall->getNumArgs() > NumArgs)
1778 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001779 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001780 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001781 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001782 (*(TheCall->arg_end()-1))->getLocEnd());
1783
Benjamin Kramer64aae502010-02-16 10:07:31 +00001784 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001785
Eli Friedman7e4faac2009-08-31 20:06:00 +00001786 if (OrigArg->isTypeDependent())
1787 return false;
1788
Chris Lattner68784ef2010-05-06 05:50:07 +00001789 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001790 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001791 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001792 diag::err_typecheck_call_invalid_unary_fp)
1793 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001794
Chris Lattner68784ef2010-05-06 05:50:07 +00001795 // If this is an implicit conversion from float -> double, remove it.
1796 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1797 Expr *CastArg = Cast->getSubExpr();
1798 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1799 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1800 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00001801 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00001802 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001803 }
1804 }
1805
Eli Friedman7e4faac2009-08-31 20:06:00 +00001806 return false;
1807}
1808
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001809/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1810// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001811ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001812 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001813 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001814 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001815 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1816 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001817
Nate Begemana0110022010-06-08 00:16:34 +00001818 // Determine which of the following types of shufflevector we're checking:
1819 // 1) unary, vector mask: (lhs, mask)
1820 // 2) binary, vector mask: (lhs, rhs, mask)
1821 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1822 QualType resType = TheCall->getArg(0)->getType();
1823 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001824
Douglas Gregorc25f7662009-05-19 22:10:17 +00001825 if (!TheCall->getArg(0)->isTypeDependent() &&
1826 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001827 QualType LHSType = TheCall->getArg(0)->getType();
1828 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001829
Craig Topperbaca3892013-07-29 06:47:04 +00001830 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1831 return ExprError(Diag(TheCall->getLocStart(),
1832 diag::err_shufflevector_non_vector)
1833 << SourceRange(TheCall->getArg(0)->getLocStart(),
1834 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001835
Nate Begemana0110022010-06-08 00:16:34 +00001836 numElements = LHSType->getAs<VectorType>()->getNumElements();
1837 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001838
Nate Begemana0110022010-06-08 00:16:34 +00001839 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1840 // with mask. If so, verify that RHS is an integer vector type with the
1841 // same number of elts as lhs.
1842 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001843 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001844 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001845 return ExprError(Diag(TheCall->getLocStart(),
1846 diag::err_shufflevector_incompatible_vector)
1847 << SourceRange(TheCall->getArg(1)->getLocStart(),
1848 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001849 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001850 return ExprError(Diag(TheCall->getLocStart(),
1851 diag::err_shufflevector_incompatible_vector)
1852 << SourceRange(TheCall->getArg(0)->getLocStart(),
1853 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001854 } else if (numElements != numResElements) {
1855 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001856 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001857 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001858 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001859 }
1860
1861 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001862 if (TheCall->getArg(i)->isTypeDependent() ||
1863 TheCall->getArg(i)->isValueDependent())
1864 continue;
1865
Nate Begemana0110022010-06-08 00:16:34 +00001866 llvm::APSInt Result(32);
1867 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1868 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001869 diag::err_shufflevector_nonconstant_argument)
1870 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001871
Craig Topper50ad5b72013-08-03 17:40:38 +00001872 // Allow -1 which will be translated to undef in the IR.
1873 if (Result.isSigned() && Result.isAllOnesValue())
1874 continue;
1875
Chris Lattner7ab824e2008-08-10 02:05:13 +00001876 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001877 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001878 diag::err_shufflevector_argument_too_large)
1879 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001880 }
1881
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001882 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001883
Chris Lattner7ab824e2008-08-10 02:05:13 +00001884 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001885 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00001886 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001887 }
1888
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001889 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
1890 TheCall->getCallee()->getLocStart(),
1891 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001892}
Chris Lattner43be2e62007-12-19 23:59:04 +00001893
Hal Finkelc4d7c822013-09-18 03:29:45 +00001894/// SemaConvertVectorExpr - Handle __builtin_convertvector
1895ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1896 SourceLocation BuiltinLoc,
1897 SourceLocation RParenLoc) {
1898 ExprValueKind VK = VK_RValue;
1899 ExprObjectKind OK = OK_Ordinary;
1900 QualType DstTy = TInfo->getType();
1901 QualType SrcTy = E->getType();
1902
1903 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1904 return ExprError(Diag(BuiltinLoc,
1905 diag::err_convertvector_non_vector)
1906 << E->getSourceRange());
1907 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1908 return ExprError(Diag(BuiltinLoc,
1909 diag::err_convertvector_non_vector_type));
1910
1911 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1912 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1913 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1914 if (SrcElts != DstElts)
1915 return ExprError(Diag(BuiltinLoc,
1916 diag::err_convertvector_incompatible_vector)
1917 << E->getSourceRange());
1918 }
1919
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001920 return new (Context)
1921 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00001922}
1923
Daniel Dunbarb7257262008-07-21 22:59:13 +00001924/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1925// This is declared to take (const void*, ...) and can take two
1926// optional constant int args.
1927bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001928 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001929
Chris Lattner3b054132008-11-19 05:08:23 +00001930 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001931 return Diag(TheCall->getLocEnd(),
1932 diag::err_typecheck_call_too_many_args_at_most)
1933 << 0 /*function call*/ << 3 << NumArgs
1934 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001935
1936 // Argument 0 is checked for us and the remaining arguments must be
1937 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00001938 for (unsigned i = 1; i != NumArgs; ++i)
1939 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001940 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001941
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001942 return false;
1943}
1944
Eric Christopher8d0c6212010-04-17 02:26:23 +00001945/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1946/// TheCall is a constant expression.
1947bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1948 llvm::APSInt &Result) {
1949 Expr *Arg = TheCall->getArg(ArgNum);
1950 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1951 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1952
1953 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1954
1955 if (!Arg->isIntegerConstantExpr(Result, Context))
1956 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001957 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001958
Chris Lattnerd545ad12009-09-23 06:06:36 +00001959 return false;
1960}
1961
Richard Sandiford28940af2014-04-16 08:47:51 +00001962/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
1963/// TheCall is a constant expression in the range [Low, High].
1964bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
1965 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001966 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001967
1968 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00001969 Expr *Arg = TheCall->getArg(ArgNum);
1970 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001971 return false;
1972
Eric Christopher8d0c6212010-04-17 02:26:23 +00001973 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00001974 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001975 return true;
1976
Richard Sandiford28940af2014-04-16 08:47:51 +00001977 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00001978 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00001979 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001980
1981 return false;
1982}
1983
Eli Friedmanc97d0142009-05-03 06:04:26 +00001984/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001985/// This checks that val is a constant 1.
1986bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1987 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001988 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001989
Eric Christopher8d0c6212010-04-17 02:26:23 +00001990 // TODO: This is less than ideal. Overload this to take a value.
1991 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1992 return true;
1993
1994 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001995 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1996 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1997
1998 return false;
1999}
2000
Richard Smithd7293d72013-08-05 18:49:43 +00002001namespace {
2002enum StringLiteralCheckType {
2003 SLCT_NotALiteral,
2004 SLCT_UncheckedLiteral,
2005 SLCT_CheckedLiteral
2006};
2007}
2008
Richard Smith55ce3522012-06-25 20:30:08 +00002009// Determine if an expression is a string literal or constant string.
2010// If this function returns false on the arguments to a function expecting a
2011// format string, we will usually need to emit a warning.
2012// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002013static StringLiteralCheckType
2014checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2015 bool HasVAListArg, unsigned format_idx,
2016 unsigned firstDataArg, Sema::FormatStringType Type,
2017 Sema::VariadicCallType CallType, bool InFunctionCall,
2018 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002019 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002020 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002021 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002022
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002023 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002024
Richard Smithd7293d72013-08-05 18:49:43 +00002025 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002026 // Technically -Wformat-nonliteral does not warn about this case.
2027 // The behavior of printf and friends in this case is implementation
2028 // dependent. Ideally if the format string cannot be null then
2029 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002030 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002031
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002032 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002033 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002034 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002035 // The expression is a literal if both sub-expressions were, and it was
2036 // completely checked only if both sub-expressions were checked.
2037 const AbstractConditionalOperator *C =
2038 cast<AbstractConditionalOperator>(E);
2039 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002040 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002041 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002042 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002043 if (Left == SLCT_NotALiteral)
2044 return SLCT_NotALiteral;
2045 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002046 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002047 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002048 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002049 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002050 }
2051
2052 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002053 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2054 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002055 }
2056
John McCallc07a0c72011-02-17 10:25:35 +00002057 case Stmt::OpaqueValueExprClass:
2058 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2059 E = src;
2060 goto tryAgain;
2061 }
Richard Smith55ce3522012-06-25 20:30:08 +00002062 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002063
Ted Kremeneka8890832011-02-24 23:03:04 +00002064 case Stmt::PredefinedExprClass:
2065 // While __func__, etc., are technically not string literals, they
2066 // cannot contain format specifiers and thus are not a security
2067 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002068 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002069
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002070 case Stmt::DeclRefExprClass: {
2071 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002072
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002073 // As an exception, do not flag errors for variables binding to
2074 // const string literals.
2075 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2076 bool isConstant = false;
2077 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002078
Richard Smithd7293d72013-08-05 18:49:43 +00002079 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2080 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002081 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002082 isConstant = T.isConstant(S.Context) &&
2083 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002084 } else if (T->isObjCObjectPointerType()) {
2085 // In ObjC, there is usually no "const ObjectPointer" type,
2086 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002087 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002088 }
Mike Stump11289f42009-09-09 15:08:12 +00002089
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002090 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002091 if (const Expr *Init = VD->getAnyInitializer()) {
2092 // Look through initializers like const char c[] = { "foo" }
2093 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2094 if (InitList->isStringLiteralInit())
2095 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2096 }
Richard Smithd7293d72013-08-05 18:49:43 +00002097 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002098 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002099 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002100 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002101 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002102 }
Mike Stump11289f42009-09-09 15:08:12 +00002103
Anders Carlssonb012ca92009-06-28 19:55:58 +00002104 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2105 // special check to see if the format string is a function parameter
2106 // of the function calling the printf function. If the function
2107 // has an attribute indicating it is a printf-like function, then we
2108 // should suppress warnings concerning non-literals being used in a call
2109 // to a vprintf function. For example:
2110 //
2111 // void
2112 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2113 // va_list ap;
2114 // va_start(ap, fmt);
2115 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2116 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002117 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002118 if (HasVAListArg) {
2119 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2120 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2121 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002122 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002123 // adjust for implicit parameter
2124 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2125 if (MD->isInstance())
2126 ++PVIndex;
2127 // We also check if the formats are compatible.
2128 // We can't pass a 'scanf' string to a 'printf' function.
2129 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002130 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002131 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002132 }
2133 }
2134 }
2135 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002136 }
Mike Stump11289f42009-09-09 15:08:12 +00002137
Richard Smith55ce3522012-06-25 20:30:08 +00002138 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002139 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002140
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002141 case Stmt::CallExprClass:
2142 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002143 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002144 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2145 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2146 unsigned ArgIndex = FA->getFormatIdx();
2147 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2148 if (MD->isInstance())
2149 --ArgIndex;
2150 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002151
Richard Smithd7293d72013-08-05 18:49:43 +00002152 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002153 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002154 Type, CallType, InFunctionCall,
2155 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002156 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2157 unsigned BuiltinID = FD->getBuiltinID();
2158 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2159 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2160 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002161 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002162 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002163 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002164 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002165 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002166 }
2167 }
Mike Stump11289f42009-09-09 15:08:12 +00002168
Richard Smith55ce3522012-06-25 20:30:08 +00002169 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002170 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002171 case Stmt::ObjCStringLiteralClass:
2172 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002173 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002174
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002175 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002176 StrE = ObjCFExpr->getString();
2177 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002178 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002179
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002180 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002181 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2182 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002183 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002184 }
Mike Stump11289f42009-09-09 15:08:12 +00002185
Richard Smith55ce3522012-06-25 20:30:08 +00002186 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002187 }
Mike Stump11289f42009-09-09 15:08:12 +00002188
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002189 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002190 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002191 }
2192}
2193
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002194Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002195 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002196 .Case("scanf", FST_Scanf)
2197 .Cases("printf", "printf0", FST_Printf)
2198 .Cases("NSString", "CFString", FST_NSString)
2199 .Case("strftime", FST_Strftime)
2200 .Case("strfmon", FST_Strfmon)
2201 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2202 .Default(FST_Unknown);
2203}
2204
Jordan Rose3e0ec582012-07-19 18:10:23 +00002205/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002206/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002207/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002208bool Sema::CheckFormatArguments(const FormatAttr *Format,
2209 ArrayRef<const Expr *> Args,
2210 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002211 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002212 SourceLocation Loc, SourceRange Range,
2213 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002214 FormatStringInfo FSI;
2215 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002216 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002217 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002218 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002219 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002220}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002221
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002222bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002223 bool HasVAListArg, unsigned format_idx,
2224 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002225 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002226 SourceLocation Loc, SourceRange Range,
2227 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002228 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002229 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002230 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002231 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002232 }
Mike Stump11289f42009-09-09 15:08:12 +00002233
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002234 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002235
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002236 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002237 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002238 // Dynamically generated format strings are difficult to
2239 // automatically vet at compile time. Requiring that format strings
2240 // are string literals: (1) permits the checking of format strings by
2241 // the compiler and thereby (2) can practically remove the source of
2242 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002243
Mike Stump11289f42009-09-09 15:08:12 +00002244 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002245 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002246 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002247 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002248 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002249 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2250 format_idx, firstDataArg, Type, CallType,
2251 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002252 if (CT != SLCT_NotALiteral)
2253 // Literal format string found, check done!
2254 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002255
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002256 // Strftime is particular as it always uses a single 'time' argument,
2257 // so it is safe to pass a non-literal string.
2258 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002259 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002260
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002261 // Do not emit diag when the string param is a macro expansion and the
2262 // format is either NSString or CFString. This is a hack to prevent
2263 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2264 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002265 if (Type == FST_NSString &&
2266 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002267 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002268
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002269 // If there are no arguments specified, warn with -Wformat-security, otherwise
2270 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002271 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002272 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002273 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002274 << OrigFormatExpr->getSourceRange();
2275 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002276 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002277 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002278 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002279 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002280}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002281
Ted Kremenekab278de2010-01-28 23:39:18 +00002282namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002283class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2284protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002285 Sema &S;
2286 const StringLiteral *FExpr;
2287 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002288 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002289 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002290 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002291 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002292 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002293 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002294 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002295 bool usesPositionalArgs;
2296 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002297 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002298 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002299 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002300public:
Ted Kremenek02087932010-07-16 02:11:22 +00002301 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002302 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002303 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002304 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002305 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002306 Sema::VariadicCallType callType,
2307 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002308 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002309 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2310 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002311 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002312 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002313 inFunctionCall(inFunctionCall), CallType(callType),
2314 CheckedVarArgs(CheckedVarArgs) {
2315 CoveredArgs.resize(numDataArgs);
2316 CoveredArgs.reset();
2317 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002318
Ted Kremenek019d2242010-01-29 01:50:07 +00002319 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002320
Ted Kremenek02087932010-07-16 02:11:22 +00002321 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002322 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002323
Jordan Rose92303592012-09-08 04:00:03 +00002324 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002325 const analyze_format_string::FormatSpecifier &FS,
2326 const analyze_format_string::ConversionSpecifier &CS,
2327 const char *startSpecifier, unsigned specifierLen,
2328 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002329
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002330 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002331 const analyze_format_string::FormatSpecifier &FS,
2332 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002333
2334 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002335 const analyze_format_string::ConversionSpecifier &CS,
2336 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002337
Craig Toppere14c0f82014-03-12 04:55:44 +00002338 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002339
Craig Toppere14c0f82014-03-12 04:55:44 +00002340 void HandleInvalidPosition(const char *startSpecifier,
2341 unsigned specifierLen,
2342 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002343
Craig Toppere14c0f82014-03-12 04:55:44 +00002344 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002345
Craig Toppere14c0f82014-03-12 04:55:44 +00002346 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002347
Richard Trieu03cf7b72011-10-28 00:41:25 +00002348 template <typename Range>
2349 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2350 const Expr *ArgumentExpr,
2351 PartialDiagnostic PDiag,
2352 SourceLocation StringLoc,
2353 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002354 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002355
Ted Kremenek02087932010-07-16 02:11:22 +00002356protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002357 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2358 const char *startSpec,
2359 unsigned specifierLen,
2360 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002361
2362 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2363 const char *startSpec,
2364 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002365
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002366 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002367 CharSourceRange getSpecifierRange(const char *startSpecifier,
2368 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002369 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002370
Ted Kremenek5739de72010-01-29 01:06:55 +00002371 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002372
2373 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2374 const analyze_format_string::ConversionSpecifier &CS,
2375 const char *startSpecifier, unsigned specifierLen,
2376 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002377
2378 template <typename Range>
2379 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2380 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002381 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002382};
2383}
2384
Ted Kremenek02087932010-07-16 02:11:22 +00002385SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002386 return OrigFormatExpr->getSourceRange();
2387}
2388
Ted Kremenek02087932010-07-16 02:11:22 +00002389CharSourceRange CheckFormatHandler::
2390getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002391 SourceLocation Start = getLocationOfByte(startSpecifier);
2392 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2393
2394 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002395 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002396
2397 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002398}
2399
Ted Kremenek02087932010-07-16 02:11:22 +00002400SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002401 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002402}
2403
Ted Kremenek02087932010-07-16 02:11:22 +00002404void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2405 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002406 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2407 getLocationOfByte(startSpecifier),
2408 /*IsStringLocation*/true,
2409 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002410}
2411
Jordan Rose92303592012-09-08 04:00:03 +00002412void CheckFormatHandler::HandleInvalidLengthModifier(
2413 const analyze_format_string::FormatSpecifier &FS,
2414 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002415 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002416 using namespace analyze_format_string;
2417
2418 const LengthModifier &LM = FS.getLengthModifier();
2419 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2420
2421 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002422 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002423 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002424 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002425 getLocationOfByte(LM.getStart()),
2426 /*IsStringLocation*/true,
2427 getSpecifierRange(startSpecifier, specifierLen));
2428
2429 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2430 << FixedLM->toString()
2431 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2432
2433 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002434 FixItHint Hint;
2435 if (DiagID == diag::warn_format_nonsensical_length)
2436 Hint = FixItHint::CreateRemoval(LMRange);
2437
2438 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002439 getLocationOfByte(LM.getStart()),
2440 /*IsStringLocation*/true,
2441 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002442 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002443 }
2444}
2445
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002446void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002447 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002448 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002449 using namespace analyze_format_string;
2450
2451 const LengthModifier &LM = FS.getLengthModifier();
2452 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2453
2454 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002455 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002456 if (FixedLM) {
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
2463 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2464 << FixedLM->toString()
2465 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2466
2467 } else {
2468 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2469 << LM.toString() << 0,
2470 getLocationOfByte(LM.getStart()),
2471 /*IsStringLocation*/true,
2472 getSpecifierRange(startSpecifier, specifierLen));
2473 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002474}
2475
2476void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2477 const analyze_format_string::ConversionSpecifier &CS,
2478 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002479 using namespace analyze_format_string;
2480
2481 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002482 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002483 if (FixedCS) {
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
2490 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2491 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2492 << FixedCS->toString()
2493 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2494 } else {
2495 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2496 << CS.toString() << /*conversion specifier*/1,
2497 getLocationOfByte(CS.getStart()),
2498 /*IsStringLocation*/true,
2499 getSpecifierRange(startSpecifier, specifierLen));
2500 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002501}
2502
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002503void CheckFormatHandler::HandlePosition(const char *startPos,
2504 unsigned posLen) {
2505 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2506 getLocationOfByte(startPos),
2507 /*IsStringLocation*/true,
2508 getSpecifierRange(startPos, posLen));
2509}
2510
Ted Kremenekd1668192010-02-27 01:41:03 +00002511void
Ted Kremenek02087932010-07-16 02:11:22 +00002512CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2513 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002514 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2515 << (unsigned) p,
2516 getLocationOfByte(startPos), /*IsStringLocation*/true,
2517 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002518}
2519
Ted Kremenek02087932010-07-16 02:11:22 +00002520void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002521 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002522 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2523 getLocationOfByte(startPos),
2524 /*IsStringLocation*/true,
2525 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002526}
2527
Ted Kremenek02087932010-07-16 02:11:22 +00002528void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002529 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002530 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002531 EmitFormatDiagnostic(
2532 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2533 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2534 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002535 }
Ted Kremenek02087932010-07-16 02:11:22 +00002536}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002537
Jordan Rose58bbe422012-07-19 18:10:08 +00002538// Note that this may return NULL if there was an error parsing or building
2539// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002540const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002541 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002542}
2543
2544void CheckFormatHandler::DoneProcessing() {
2545 // Does the number of data arguments exceed the number of
2546 // format conversions in the format string?
2547 if (!HasVAListArg) {
2548 // Find any arguments that weren't covered.
2549 CoveredArgs.flip();
2550 signed notCoveredArg = CoveredArgs.find_first();
2551 if (notCoveredArg >= 0) {
2552 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002553 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2554 SourceLocation Loc = E->getLocStart();
2555 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2556 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2557 Loc, /*IsStringLocation*/false,
2558 getFormatStringRange());
2559 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002560 }
Ted Kremenek02087932010-07-16 02:11:22 +00002561 }
2562 }
2563}
2564
Ted Kremenekce815422010-07-19 21:25:57 +00002565bool
2566CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2567 SourceLocation Loc,
2568 const char *startSpec,
2569 unsigned specifierLen,
2570 const char *csStart,
2571 unsigned csLen) {
2572
2573 bool keepGoing = true;
2574 if (argIndex < NumDataArgs) {
2575 // Consider the argument coverered, even though the specifier doesn't
2576 // make sense.
2577 CoveredArgs.set(argIndex);
2578 }
2579 else {
2580 // If argIndex exceeds the number of data arguments we
2581 // don't issue a warning because that is just a cascade of warnings (and
2582 // they may have intended '%%' anyway). We don't want to continue processing
2583 // the format string after this point, however, as we will like just get
2584 // gibberish when trying to match arguments.
2585 keepGoing = false;
2586 }
2587
Richard Trieu03cf7b72011-10-28 00:41:25 +00002588 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2589 << StringRef(csStart, csLen),
2590 Loc, /*IsStringLocation*/true,
2591 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002592
2593 return keepGoing;
2594}
2595
Richard Trieu03cf7b72011-10-28 00:41:25 +00002596void
2597CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2598 const char *startSpec,
2599 unsigned specifierLen) {
2600 EmitFormatDiagnostic(
2601 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2602 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2603}
2604
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002605bool
2606CheckFormatHandler::CheckNumArgs(
2607 const analyze_format_string::FormatSpecifier &FS,
2608 const analyze_format_string::ConversionSpecifier &CS,
2609 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2610
2611 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002612 PartialDiagnostic PDiag = FS.usesPositionalArg()
2613 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2614 << (argIndex+1) << NumDataArgs)
2615 : S.PDiag(diag::warn_printf_insufficient_data_args);
2616 EmitFormatDiagnostic(
2617 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2618 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002619 return false;
2620 }
2621 return true;
2622}
2623
Richard Trieu03cf7b72011-10-28 00:41:25 +00002624template<typename Range>
2625void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2626 SourceLocation Loc,
2627 bool IsStringLocation,
2628 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002629 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002630 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002631 Loc, IsStringLocation, StringRange, FixIt);
2632}
2633
2634/// \brief If the format string is not within the funcion call, emit a note
2635/// so that the function call and string are in diagnostic messages.
2636///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002637/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002638/// call and only one diagnostic message will be produced. Otherwise, an
2639/// extra note will be emitted pointing to location of the format string.
2640///
2641/// \param ArgumentExpr the expression that is passed as the format string
2642/// argument in the function call. Used for getting locations when two
2643/// diagnostics are emitted.
2644///
2645/// \param PDiag the callee should already have provided any strings for the
2646/// diagnostic message. This function only adds locations and fixits
2647/// to diagnostics.
2648///
2649/// \param Loc primary location for diagnostic. If two diagnostics are
2650/// required, one will be at Loc and a new SourceLocation will be created for
2651/// the other one.
2652///
2653/// \param IsStringLocation if true, Loc points to the format string should be
2654/// used for the note. Otherwise, Loc points to the argument list and will
2655/// be used with PDiag.
2656///
2657/// \param StringRange some or all of the string to highlight. This is
2658/// templated so it can accept either a CharSourceRange or a SourceRange.
2659///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002660/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002661template<typename Range>
2662void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2663 const Expr *ArgumentExpr,
2664 PartialDiagnostic PDiag,
2665 SourceLocation Loc,
2666 bool IsStringLocation,
2667 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002668 ArrayRef<FixItHint> FixIt) {
2669 if (InFunctionCall) {
2670 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2671 D << StringRange;
2672 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2673 I != E; ++I) {
2674 D << *I;
2675 }
2676 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002677 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2678 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002679
2680 const Sema::SemaDiagnosticBuilder &Note =
2681 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2682 diag::note_format_string_defined);
2683
2684 Note << StringRange;
2685 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2686 I != E; ++I) {
2687 Note << *I;
2688 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002689 }
2690}
2691
Ted Kremenek02087932010-07-16 02:11:22 +00002692//===--- CHECK: Printf format string checking ------------------------------===//
2693
2694namespace {
2695class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002696 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002697public:
2698 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2699 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002700 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002701 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002702 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002703 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002704 Sema::VariadicCallType CallType,
2705 llvm::SmallBitVector &CheckedVarArgs)
2706 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2707 numDataArgs, beg, hasVAListArg, Args,
2708 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2709 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002710 {}
2711
Craig Toppere14c0f82014-03-12 04:55:44 +00002712
Ted Kremenek02087932010-07-16 02:11:22 +00002713 bool HandleInvalidPrintfConversionSpecifier(
2714 const analyze_printf::PrintfSpecifier &FS,
2715 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002716 unsigned specifierLen) override;
2717
Ted Kremenek02087932010-07-16 02:11:22 +00002718 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2719 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002720 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002721 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2722 const char *StartSpecifier,
2723 unsigned SpecifierLen,
2724 const Expr *E);
2725
Ted Kremenek02087932010-07-16 02:11:22 +00002726 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2727 const char *startSpecifier, unsigned specifierLen);
2728 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2729 const analyze_printf::OptionalAmount &Amt,
2730 unsigned type,
2731 const char *startSpecifier, unsigned specifierLen);
2732 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2733 const analyze_printf::OptionalFlag &flag,
2734 const char *startSpecifier, unsigned specifierLen);
2735 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2736 const analyze_printf::OptionalFlag &ignoredFlag,
2737 const analyze_printf::OptionalFlag &flag,
2738 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002739 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002740 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002741
Ted Kremenek02087932010-07-16 02:11:22 +00002742};
2743}
2744
2745bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2746 const analyze_printf::PrintfSpecifier &FS,
2747 const char *startSpecifier,
2748 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002749 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002750 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002751
Ted Kremenekce815422010-07-19 21:25:57 +00002752 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2753 getLocationOfByte(CS.getStart()),
2754 startSpecifier, specifierLen,
2755 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002756}
2757
Ted Kremenek02087932010-07-16 02:11:22 +00002758bool CheckPrintfHandler::HandleAmount(
2759 const analyze_format_string::OptionalAmount &Amt,
2760 unsigned k, const char *startSpecifier,
2761 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002762
2763 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002764 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002765 unsigned argIndex = Amt.getArgIndex();
2766 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002767 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2768 << k,
2769 getLocationOfByte(Amt.getStart()),
2770 /*IsStringLocation*/true,
2771 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002772 // Don't do any more checking. We will just emit
2773 // spurious errors.
2774 return false;
2775 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002776
Ted Kremenek5739de72010-01-29 01:06:55 +00002777 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002778 // Although not in conformance with C99, we also allow the argument to be
2779 // an 'unsigned int' as that is a reasonably safe case. GCC also
2780 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002781 CoveredArgs.set(argIndex);
2782 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002783 if (!Arg)
2784 return false;
2785
Ted Kremenek5739de72010-01-29 01:06:55 +00002786 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002787
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002788 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2789 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002790
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002791 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002792 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002793 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002794 << T << Arg->getSourceRange(),
2795 getLocationOfByte(Amt.getStart()),
2796 /*IsStringLocation*/true,
2797 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002798 // Don't do any more checking. We will just emit
2799 // spurious errors.
2800 return false;
2801 }
2802 }
2803 }
2804 return true;
2805}
Ted Kremenek5739de72010-01-29 01:06:55 +00002806
Tom Careb49ec692010-06-17 19:00:27 +00002807void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002808 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002809 const analyze_printf::OptionalAmount &Amt,
2810 unsigned type,
2811 const char *startSpecifier,
2812 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002813 const analyze_printf::PrintfConversionSpecifier &CS =
2814 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002815
Richard Trieu03cf7b72011-10-28 00:41:25 +00002816 FixItHint fixit =
2817 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2818 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2819 Amt.getConstantLength()))
2820 : FixItHint();
2821
2822 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2823 << type << CS.toString(),
2824 getLocationOfByte(Amt.getStart()),
2825 /*IsStringLocation*/true,
2826 getSpecifierRange(startSpecifier, specifierLen),
2827 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002828}
2829
Ted Kremenek02087932010-07-16 02:11:22 +00002830void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002831 const analyze_printf::OptionalFlag &flag,
2832 const char *startSpecifier,
2833 unsigned specifierLen) {
2834 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002835 const analyze_printf::PrintfConversionSpecifier &CS =
2836 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002837 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2838 << flag.toString() << CS.toString(),
2839 getLocationOfByte(flag.getPosition()),
2840 /*IsStringLocation*/true,
2841 getSpecifierRange(startSpecifier, specifierLen),
2842 FixItHint::CreateRemoval(
2843 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002844}
2845
2846void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002847 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002848 const analyze_printf::OptionalFlag &ignoredFlag,
2849 const analyze_printf::OptionalFlag &flag,
2850 const char *startSpecifier,
2851 unsigned specifierLen) {
2852 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002853 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2854 << ignoredFlag.toString() << flag.toString(),
2855 getLocationOfByte(ignoredFlag.getPosition()),
2856 /*IsStringLocation*/true,
2857 getSpecifierRange(startSpecifier, specifierLen),
2858 FixItHint::CreateRemoval(
2859 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002860}
2861
Richard Smith55ce3522012-06-25 20:30:08 +00002862// Determines if the specified is a C++ class or struct containing
2863// a member with the specified name and kind (e.g. a CXXMethodDecl named
2864// "c_str()").
2865template<typename MemberKind>
2866static llvm::SmallPtrSet<MemberKind*, 1>
2867CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2868 const RecordType *RT = Ty->getAs<RecordType>();
2869 llvm::SmallPtrSet<MemberKind*, 1> Results;
2870
2871 if (!RT)
2872 return Results;
2873 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002874 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002875 return Results;
2876
Alp Tokerb6cc5922014-05-03 03:45:55 +00002877 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00002878 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002879 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002880
2881 // We just need to include all members of the right kind turned up by the
2882 // filter, at this point.
2883 if (S.LookupQualifiedName(R, RT->getDecl()))
2884 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2885 NamedDecl *decl = (*I)->getUnderlyingDecl();
2886 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2887 Results.insert(FK);
2888 }
2889 return Results;
2890}
2891
Richard Smith2868a732014-02-28 01:36:39 +00002892/// Check if we could call '.c_str()' on an object.
2893///
2894/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2895/// allow the call, or if it would be ambiguous).
2896bool Sema::hasCStrMethod(const Expr *E) {
2897 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2898 MethodSet Results =
2899 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2900 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2901 MI != ME; ++MI)
2902 if ((*MI)->getMinRequiredArguments() == 0)
2903 return true;
2904 return false;
2905}
2906
Richard Smith55ce3522012-06-25 20:30:08 +00002907// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002908// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002909// Returns true when a c_str() conversion method is found.
2910bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002911 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002912 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2913
2914 MethodSet Results =
2915 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2916
2917 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2918 MI != ME; ++MI) {
2919 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002920 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002921 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002922 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00002923 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00002924 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2925 << "c_str()"
2926 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2927 return true;
2928 }
2929 }
2930
2931 return false;
2932}
2933
Ted Kremenekab278de2010-01-28 23:39:18 +00002934bool
Ted Kremenek02087932010-07-16 02:11:22 +00002935CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002936 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002937 const char *startSpecifier,
2938 unsigned specifierLen) {
2939
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002940 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002941 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002942 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002943
Ted Kremenek6cd69422010-07-19 22:01:06 +00002944 if (FS.consumesDataArgument()) {
2945 if (atFirstArg) {
2946 atFirstArg = false;
2947 usesPositionalArgs = FS.usesPositionalArg();
2948 }
2949 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002950 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2951 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002952 return false;
2953 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002954 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002955
Ted Kremenekd1668192010-02-27 01:41:03 +00002956 // First check if the field width, precision, and conversion specifier
2957 // have matching data arguments.
2958 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2959 startSpecifier, specifierLen)) {
2960 return false;
2961 }
2962
2963 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2964 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002965 return false;
2966 }
2967
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002968 if (!CS.consumesDataArgument()) {
2969 // FIXME: Technically specifying a precision or field width here
2970 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002971 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002972 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002973
Ted Kremenek4a49d982010-02-26 19:18:41 +00002974 // Consume the argument.
2975 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002976 if (argIndex < NumDataArgs) {
2977 // The check to see if the argIndex is valid will come later.
2978 // We set the bit here because we may exit early from this
2979 // function if we encounter some other error.
2980 CoveredArgs.set(argIndex);
2981 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002982
2983 // Check for using an Objective-C specific conversion specifier
2984 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002985 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002986 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2987 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00002988 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002989
Tom Careb49ec692010-06-17 19:00:27 +00002990 // Check for invalid use of field width
2991 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00002992 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00002993 startSpecifier, specifierLen);
2994 }
2995
2996 // Check for invalid use of precision
2997 if (!FS.hasValidPrecision()) {
2998 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2999 startSpecifier, specifierLen);
3000 }
3001
3002 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003003 if (!FS.hasValidThousandsGroupingPrefix())
3004 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003005 if (!FS.hasValidLeadingZeros())
3006 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3007 if (!FS.hasValidPlusPrefix())
3008 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003009 if (!FS.hasValidSpacePrefix())
3010 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003011 if (!FS.hasValidAlternativeForm())
3012 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3013 if (!FS.hasValidLeftJustified())
3014 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3015
3016 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003017 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3018 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3019 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003020 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3021 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3022 startSpecifier, specifierLen);
3023
3024 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003025 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003026 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3027 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003028 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003029 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003030 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003031 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3032 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003033
Jordan Rose92303592012-09-08 04:00:03 +00003034 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3035 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3036
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003037 // The remaining checks depend on the data arguments.
3038 if (HasVAListArg)
3039 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003040
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003041 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003042 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003043
Jordan Rose58bbe422012-07-19 18:10:08 +00003044 const Expr *Arg = getDataArg(argIndex);
3045 if (!Arg)
3046 return true;
3047
3048 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003049}
3050
Jordan Roseaee34382012-09-05 22:56:26 +00003051static bool requiresParensToAddCast(const Expr *E) {
3052 // FIXME: We should have a general way to reason about operator
3053 // precedence and whether parens are actually needed here.
3054 // Take care of a few common cases where they aren't.
3055 const Expr *Inside = E->IgnoreImpCasts();
3056 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3057 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3058
3059 switch (Inside->getStmtClass()) {
3060 case Stmt::ArraySubscriptExprClass:
3061 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003062 case Stmt::CharacterLiteralClass:
3063 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003064 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003065 case Stmt::FloatingLiteralClass:
3066 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003067 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003068 case Stmt::ObjCArrayLiteralClass:
3069 case Stmt::ObjCBoolLiteralExprClass:
3070 case Stmt::ObjCBoxedExprClass:
3071 case Stmt::ObjCDictionaryLiteralClass:
3072 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003073 case Stmt::ObjCIvarRefExprClass:
3074 case Stmt::ObjCMessageExprClass:
3075 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003076 case Stmt::ObjCStringLiteralClass:
3077 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003078 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003079 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003080 case Stmt::UnaryOperatorClass:
3081 return false;
3082 default:
3083 return true;
3084 }
3085}
3086
Richard Smith55ce3522012-06-25 20:30:08 +00003087bool
3088CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3089 const char *StartSpecifier,
3090 unsigned SpecifierLen,
3091 const Expr *E) {
3092 using namespace analyze_format_string;
3093 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003094 // Now type check the data expression that matches the
3095 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003096 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3097 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003098 if (!AT.isValid())
3099 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003100
Jordan Rose598ec092012-12-05 18:44:40 +00003101 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003102 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3103 ExprTy = TET->getUnderlyingExpr()->getType();
3104 }
3105
Jordan Rose598ec092012-12-05 18:44:40 +00003106 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003107 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003108
Jordan Rose22b74712012-09-05 22:56:19 +00003109 // Look through argument promotions for our error message's reported type.
3110 // This includes the integral and floating promotions, but excludes array
3111 // and function pointer decay; seeing that an argument intended to be a
3112 // string has type 'char [6]' is probably more confusing than 'char *'.
3113 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3114 if (ICE->getCastKind() == CK_IntegralCast ||
3115 ICE->getCastKind() == CK_FloatingCast) {
3116 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003117 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003118
3119 // Check if we didn't match because of an implicit cast from a 'char'
3120 // or 'short' to an 'int'. This is done because printf is a varargs
3121 // function.
3122 if (ICE->getType() == S.Context.IntTy ||
3123 ICE->getType() == S.Context.UnsignedIntTy) {
3124 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003125 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003126 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003127 }
Jordan Rose98709982012-06-04 22:48:57 +00003128 }
Jordan Rose598ec092012-12-05 18:44:40 +00003129 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3130 // Special case for 'a', which has type 'int' in C.
3131 // Note, however, that we do /not/ want to treat multibyte constants like
3132 // 'MooV' as characters! This form is deprecated but still exists.
3133 if (ExprTy == S.Context.IntTy)
3134 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3135 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003136 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003137
Jordan Rosebc53ed12014-05-31 04:12:14 +00003138 // Look through enums to their underlying type.
3139 bool IsEnum = false;
3140 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3141 ExprTy = EnumTy->getDecl()->getIntegerType();
3142 IsEnum = true;
3143 }
3144
Jordan Rose0e5badd2012-12-05 18:44:49 +00003145 // %C in an Objective-C context prints a unichar, not a wchar_t.
3146 // If the argument is an integer of some kind, believe the %C and suggest
3147 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003148 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003149 if (ObjCContext &&
3150 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3151 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3152 !ExprTy->isCharType()) {
3153 // 'unichar' is defined as a typedef of unsigned short, but we should
3154 // prefer using the typedef if it is visible.
3155 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003156
3157 // While we are here, check if the value is an IntegerLiteral that happens
3158 // to be within the valid range.
3159 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3160 const llvm::APInt &V = IL->getValue();
3161 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3162 return true;
3163 }
3164
Jordan Rose0e5badd2012-12-05 18:44:49 +00003165 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3166 Sema::LookupOrdinaryName);
3167 if (S.LookupName(Result, S.getCurScope())) {
3168 NamedDecl *ND = Result.getFoundDecl();
3169 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3170 if (TD->getUnderlyingType() == IntendedTy)
3171 IntendedTy = S.Context.getTypedefType(TD);
3172 }
3173 }
3174 }
3175
3176 // Special-case some of Darwin's platform-independence types by suggesting
3177 // casts to primitive types that are known to be large enough.
3178 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003179 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003180 // Use a 'while' to peel off layers of typedefs.
3181 QualType TyTy = IntendedTy;
3182 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003183 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003184 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003185 .Case("NSInteger", S.Context.LongTy)
3186 .Case("NSUInteger", S.Context.UnsignedLongTy)
3187 .Case("SInt32", S.Context.IntTy)
3188 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003189 .Default(QualType());
3190
3191 if (!CastTy.isNull()) {
3192 ShouldNotPrintDirectly = true;
3193 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003194 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003195 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003196 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003197 }
3198 }
3199
Jordan Rose22b74712012-09-05 22:56:19 +00003200 // We may be able to offer a FixItHint if it is a supported type.
3201 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003202 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003203 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003204
Jordan Rose22b74712012-09-05 22:56:19 +00003205 if (success) {
3206 // Get the fix string from the fixed format specifier
3207 SmallString<16> buf;
3208 llvm::raw_svector_ostream os(buf);
3209 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003210
Jordan Roseaee34382012-09-05 22:56:26 +00003211 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3212
Jordan Rose0e5badd2012-12-05 18:44:49 +00003213 if (IntendedTy == ExprTy) {
3214 // In this case, the specifier is wrong and should be changed to match
3215 // the argument.
3216 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003217 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3218 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003219 << E->getSourceRange(),
3220 E->getLocStart(),
3221 /*IsStringLocation*/false,
3222 SpecRange,
3223 FixItHint::CreateReplacement(SpecRange, os.str()));
3224
3225 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003226 // The canonical type for formatting this value is different from the
3227 // actual type of the expression. (This occurs, for example, with Darwin's
3228 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3229 // should be printed as 'long' for 64-bit compatibility.)
3230 // Rather than emitting a normal format/argument mismatch, we want to
3231 // add a cast to the recommended type (and correct the format string
3232 // if necessary).
3233 SmallString<16> CastBuf;
3234 llvm::raw_svector_ostream CastFix(CastBuf);
3235 CastFix << "(";
3236 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3237 CastFix << ")";
3238
3239 SmallVector<FixItHint,4> Hints;
3240 if (!AT.matchesType(S.Context, IntendedTy))
3241 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3242
3243 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3244 // If there's already a cast present, just replace it.
3245 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3246 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3247
3248 } else if (!requiresParensToAddCast(E)) {
3249 // If the expression has high enough precedence,
3250 // just write the C-style cast.
3251 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3252 CastFix.str()));
3253 } else {
3254 // Otherwise, add parens around the expression as well as the cast.
3255 CastFix << "(";
3256 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3257 CastFix.str()));
3258
Alp Tokerb6cc5922014-05-03 03:45:55 +00003259 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003260 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3261 }
3262
Jordan Rose0e5badd2012-12-05 18:44:49 +00003263 if (ShouldNotPrintDirectly) {
3264 // The expression has a type that should not be printed directly.
3265 // We extract the name from the typedef because we don't want to show
3266 // the underlying type in the diagnostic.
3267 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003268
Jordan Rose0e5badd2012-12-05 18:44:49 +00003269 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003270 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003271 << E->getSourceRange(),
3272 E->getLocStart(), /*IsStringLocation=*/false,
3273 SpecRange, Hints);
3274 } else {
3275 // In this case, the expression could be printed using a different
3276 // specifier, but we've decided that the specifier is probably correct
3277 // and we should cast instead. Just use the normal warning message.
3278 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003279 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3280 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003281 << E->getSourceRange(),
3282 E->getLocStart(), /*IsStringLocation*/false,
3283 SpecRange, Hints);
3284 }
Jordan Roseaee34382012-09-05 22:56:26 +00003285 }
Jordan Rose22b74712012-09-05 22:56:19 +00003286 } else {
3287 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3288 SpecifierLen);
3289 // Since the warning for passing non-POD types to variadic functions
3290 // was deferred until now, we emit a warning for non-POD
3291 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003292 switch (S.isValidVarArgType(ExprTy)) {
3293 case Sema::VAK_Valid:
3294 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003295 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003296 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3297 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003298 << CSR
3299 << E->getSourceRange(),
3300 E->getLocStart(), /*IsStringLocation*/false, CSR);
3301 break;
3302
3303 case Sema::VAK_Undefined:
3304 EmitFormatDiagnostic(
3305 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003306 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003307 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003308 << CallType
3309 << AT.getRepresentativeTypeName(S.Context)
3310 << CSR
3311 << E->getSourceRange(),
3312 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003313 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003314 break;
3315
3316 case Sema::VAK_Invalid:
3317 if (ExprTy->isObjCObjectType())
3318 EmitFormatDiagnostic(
3319 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3320 << S.getLangOpts().CPlusPlus11
3321 << ExprTy
3322 << CallType
3323 << AT.getRepresentativeTypeName(S.Context)
3324 << CSR
3325 << E->getSourceRange(),
3326 E->getLocStart(), /*IsStringLocation*/false, CSR);
3327 else
3328 // FIXME: If this is an initializer list, suggest removing the braces
3329 // or inserting a cast to the target type.
3330 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3331 << isa<InitListExpr>(E) << ExprTy << CallType
3332 << AT.getRepresentativeTypeName(S.Context)
3333 << E->getSourceRange();
3334 break;
3335 }
3336
3337 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3338 "format string specifier index out of range");
3339 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003340 }
3341
Ted Kremenekab278de2010-01-28 23:39:18 +00003342 return true;
3343}
3344
Ted Kremenek02087932010-07-16 02:11:22 +00003345//===--- CHECK: Scanf format string checking ------------------------------===//
3346
3347namespace {
3348class CheckScanfHandler : public CheckFormatHandler {
3349public:
3350 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3351 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003352 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003353 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003354 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003355 Sema::VariadicCallType CallType,
3356 llvm::SmallBitVector &CheckedVarArgs)
3357 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3358 numDataArgs, beg, hasVAListArg,
3359 Args, formatIdx, inFunctionCall, CallType,
3360 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003361 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003362
3363 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3364 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003365 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003366
3367 bool HandleInvalidScanfConversionSpecifier(
3368 const analyze_scanf::ScanfSpecifier &FS,
3369 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003370 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003371
Craig Toppere14c0f82014-03-12 04:55:44 +00003372 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003373};
Ted Kremenek019d2242010-01-29 01:50:07 +00003374}
Ted Kremenekab278de2010-01-28 23:39:18 +00003375
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003376void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3377 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003378 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3379 getLocationOfByte(end), /*IsStringLocation*/true,
3380 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003381}
3382
Ted Kremenekce815422010-07-19 21:25:57 +00003383bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3384 const analyze_scanf::ScanfSpecifier &FS,
3385 const char *startSpecifier,
3386 unsigned specifierLen) {
3387
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003388 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003389 FS.getConversionSpecifier();
3390
3391 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3392 getLocationOfByte(CS.getStart()),
3393 startSpecifier, specifierLen,
3394 CS.getStart(), CS.getLength());
3395}
3396
Ted Kremenek02087932010-07-16 02:11:22 +00003397bool CheckScanfHandler::HandleScanfSpecifier(
3398 const analyze_scanf::ScanfSpecifier &FS,
3399 const char *startSpecifier,
3400 unsigned specifierLen) {
3401
3402 using namespace analyze_scanf;
3403 using namespace analyze_format_string;
3404
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003405 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003406
Ted Kremenek6cd69422010-07-19 22:01:06 +00003407 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3408 // be used to decide if we are using positional arguments consistently.
3409 if (FS.consumesDataArgument()) {
3410 if (atFirstArg) {
3411 atFirstArg = false;
3412 usesPositionalArgs = FS.usesPositionalArg();
3413 }
3414 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003415 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3416 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003417 return false;
3418 }
Ted Kremenek02087932010-07-16 02:11:22 +00003419 }
3420
3421 // Check if the field with is non-zero.
3422 const OptionalAmount &Amt = FS.getFieldWidth();
3423 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3424 if (Amt.getConstantAmount() == 0) {
3425 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3426 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003427 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3428 getLocationOfByte(Amt.getStart()),
3429 /*IsStringLocation*/true, R,
3430 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003431 }
3432 }
3433
3434 if (!FS.consumesDataArgument()) {
3435 // FIXME: Technically specifying a precision or field width here
3436 // makes no sense. Worth issuing a warning at some point.
3437 return true;
3438 }
3439
3440 // Consume the argument.
3441 unsigned argIndex = FS.getArgIndex();
3442 if (argIndex < NumDataArgs) {
3443 // The check to see if the argIndex is valid will come later.
3444 // We set the bit here because we may exit early from this
3445 // function if we encounter some other error.
3446 CoveredArgs.set(argIndex);
3447 }
3448
Ted Kremenek4407ea42010-07-20 20:04:47 +00003449 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003450 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003451 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3452 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003453 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003454 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003455 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003456 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3457 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003458
Jordan Rose92303592012-09-08 04:00:03 +00003459 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3460 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3461
Ted Kremenek02087932010-07-16 02:11:22 +00003462 // The remaining checks depend on the data arguments.
3463 if (HasVAListArg)
3464 return true;
3465
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003466 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003467 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003468
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003469 // Check that the argument type matches the format specifier.
3470 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003471 if (!Ex)
3472 return true;
3473
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003474 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3475 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003476 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003477 bool success = fixedFS.fixType(Ex->getType(),
3478 Ex->IgnoreImpCasts()->getType(),
3479 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003480
3481 if (success) {
3482 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003483 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003484 llvm::raw_svector_ostream os(buf);
3485 fixedFS.toString(os);
3486
3487 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
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003490 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003491 Ex->getLocStart(),
3492 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003493 getSpecifierRange(startSpecifier, specifierLen),
3494 FixItHint::CreateReplacement(
3495 getSpecifierRange(startSpecifier, specifierLen),
3496 os.str()));
3497 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003498 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003499 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3500 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003501 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003502 Ex->getLocStart(),
3503 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003504 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003505 }
3506 }
3507
Ted Kremenek02087932010-07-16 02:11:22 +00003508 return true;
3509}
3510
3511void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003512 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003513 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003514 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003515 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003516 bool inFunctionCall, VariadicCallType CallType,
3517 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003518
Ted Kremenekab278de2010-01-28 23:39:18 +00003519 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003520 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003521 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003522 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003523 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3524 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003525 return;
3526 }
Ted Kremenek02087932010-07-16 02:11:22 +00003527
Ted Kremenekab278de2010-01-28 23:39:18 +00003528 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003529 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003530 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003531 // Account for cases where the string literal is truncated in a declaration.
3532 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3533 assert(T && "String literal not of constant array type!");
3534 size_t TypeSize = T->getSize().getZExtValue();
3535 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003536 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003537
3538 // Emit a warning if the string literal is truncated and does not contain an
3539 // embedded null character.
3540 if (TypeSize <= StrRef.size() &&
3541 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3542 CheckFormatHandler::EmitFormatDiagnostic(
3543 *this, inFunctionCall, Args[format_idx],
3544 PDiag(diag::warn_printf_format_string_not_null_terminated),
3545 FExpr->getLocStart(),
3546 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3547 return;
3548 }
3549
Ted Kremenekab278de2010-01-28 23:39:18 +00003550 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003551 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003552 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003553 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003554 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3555 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003556 return;
3557 }
Ted Kremenek02087932010-07-16 02:11:22 +00003558
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003559 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003560 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003561 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003562 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003563 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003564
Hans Wennborg23926bd2011-12-15 10:25:47 +00003565 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003566 getLangOpts(),
3567 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003568 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003569 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003570 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003571 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003572 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003573
Hans Wennborg23926bd2011-12-15 10:25:47 +00003574 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003575 getLangOpts(),
3576 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003577 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003578 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003579}
3580
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003581//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3582
3583// Returns the related absolute value function that is larger, of 0 if one
3584// does not exist.
3585static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3586 switch (AbsFunction) {
3587 default:
3588 return 0;
3589
3590 case Builtin::BI__builtin_abs:
3591 return Builtin::BI__builtin_labs;
3592 case Builtin::BI__builtin_labs:
3593 return Builtin::BI__builtin_llabs;
3594 case Builtin::BI__builtin_llabs:
3595 return 0;
3596
3597 case Builtin::BI__builtin_fabsf:
3598 return Builtin::BI__builtin_fabs;
3599 case Builtin::BI__builtin_fabs:
3600 return Builtin::BI__builtin_fabsl;
3601 case Builtin::BI__builtin_fabsl:
3602 return 0;
3603
3604 case Builtin::BI__builtin_cabsf:
3605 return Builtin::BI__builtin_cabs;
3606 case Builtin::BI__builtin_cabs:
3607 return Builtin::BI__builtin_cabsl;
3608 case Builtin::BI__builtin_cabsl:
3609 return 0;
3610
3611 case Builtin::BIabs:
3612 return Builtin::BIlabs;
3613 case Builtin::BIlabs:
3614 return Builtin::BIllabs;
3615 case Builtin::BIllabs:
3616 return 0;
3617
3618 case Builtin::BIfabsf:
3619 return Builtin::BIfabs;
3620 case Builtin::BIfabs:
3621 return Builtin::BIfabsl;
3622 case Builtin::BIfabsl:
3623 return 0;
3624
3625 case Builtin::BIcabsf:
3626 return Builtin::BIcabs;
3627 case Builtin::BIcabs:
3628 return Builtin::BIcabsl;
3629 case Builtin::BIcabsl:
3630 return 0;
3631 }
3632}
3633
3634// Returns the argument type of the absolute value function.
3635static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3636 unsigned AbsType) {
3637 if (AbsType == 0)
3638 return QualType();
3639
3640 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3641 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3642 if (Error != ASTContext::GE_None)
3643 return QualType();
3644
3645 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3646 if (!FT)
3647 return QualType();
3648
3649 if (FT->getNumParams() != 1)
3650 return QualType();
3651
3652 return FT->getParamType(0);
3653}
3654
3655// Returns the best absolute value function, or zero, based on type and
3656// current absolute value function.
3657static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3658 unsigned AbsFunctionKind) {
3659 unsigned BestKind = 0;
3660 uint64_t ArgSize = Context.getTypeSize(ArgType);
3661 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3662 Kind = getLargerAbsoluteValueFunction(Kind)) {
3663 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3664 if (Context.getTypeSize(ParamType) >= ArgSize) {
3665 if (BestKind == 0)
3666 BestKind = Kind;
3667 else if (Context.hasSameType(ParamType, ArgType)) {
3668 BestKind = Kind;
3669 break;
3670 }
3671 }
3672 }
3673 return BestKind;
3674}
3675
3676enum AbsoluteValueKind {
3677 AVK_Integer,
3678 AVK_Floating,
3679 AVK_Complex
3680};
3681
3682static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3683 if (T->isIntegralOrEnumerationType())
3684 return AVK_Integer;
3685 if (T->isRealFloatingType())
3686 return AVK_Floating;
3687 if (T->isAnyComplexType())
3688 return AVK_Complex;
3689
3690 llvm_unreachable("Type not integer, floating, or complex");
3691}
3692
3693// Changes the absolute value function to a different type. Preserves whether
3694// the function is a builtin.
3695static unsigned changeAbsFunction(unsigned AbsKind,
3696 AbsoluteValueKind ValueKind) {
3697 switch (ValueKind) {
3698 case AVK_Integer:
3699 switch (AbsKind) {
3700 default:
3701 return 0;
3702 case Builtin::BI__builtin_fabsf:
3703 case Builtin::BI__builtin_fabs:
3704 case Builtin::BI__builtin_fabsl:
3705 case Builtin::BI__builtin_cabsf:
3706 case Builtin::BI__builtin_cabs:
3707 case Builtin::BI__builtin_cabsl:
3708 return Builtin::BI__builtin_abs;
3709 case Builtin::BIfabsf:
3710 case Builtin::BIfabs:
3711 case Builtin::BIfabsl:
3712 case Builtin::BIcabsf:
3713 case Builtin::BIcabs:
3714 case Builtin::BIcabsl:
3715 return Builtin::BIabs;
3716 }
3717 case AVK_Floating:
3718 switch (AbsKind) {
3719 default:
3720 return 0;
3721 case Builtin::BI__builtin_abs:
3722 case Builtin::BI__builtin_labs:
3723 case Builtin::BI__builtin_llabs:
3724 case Builtin::BI__builtin_cabsf:
3725 case Builtin::BI__builtin_cabs:
3726 case Builtin::BI__builtin_cabsl:
3727 return Builtin::BI__builtin_fabsf;
3728 case Builtin::BIabs:
3729 case Builtin::BIlabs:
3730 case Builtin::BIllabs:
3731 case Builtin::BIcabsf:
3732 case Builtin::BIcabs:
3733 case Builtin::BIcabsl:
3734 return Builtin::BIfabsf;
3735 }
3736 case AVK_Complex:
3737 switch (AbsKind) {
3738 default:
3739 return 0;
3740 case Builtin::BI__builtin_abs:
3741 case Builtin::BI__builtin_labs:
3742 case Builtin::BI__builtin_llabs:
3743 case Builtin::BI__builtin_fabsf:
3744 case Builtin::BI__builtin_fabs:
3745 case Builtin::BI__builtin_fabsl:
3746 return Builtin::BI__builtin_cabsf;
3747 case Builtin::BIabs:
3748 case Builtin::BIlabs:
3749 case Builtin::BIllabs:
3750 case Builtin::BIfabsf:
3751 case Builtin::BIfabs:
3752 case Builtin::BIfabsl:
3753 return Builtin::BIcabsf;
3754 }
3755 }
3756 llvm_unreachable("Unable to convert function");
3757}
3758
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003759static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003760 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3761 if (!FnInfo)
3762 return 0;
3763
3764 switch (FDecl->getBuiltinID()) {
3765 default:
3766 return 0;
3767 case Builtin::BI__builtin_abs:
3768 case Builtin::BI__builtin_fabs:
3769 case Builtin::BI__builtin_fabsf:
3770 case Builtin::BI__builtin_fabsl:
3771 case Builtin::BI__builtin_labs:
3772 case Builtin::BI__builtin_llabs:
3773 case Builtin::BI__builtin_cabs:
3774 case Builtin::BI__builtin_cabsf:
3775 case Builtin::BI__builtin_cabsl:
3776 case Builtin::BIabs:
3777 case Builtin::BIlabs:
3778 case Builtin::BIllabs:
3779 case Builtin::BIfabs:
3780 case Builtin::BIfabsf:
3781 case Builtin::BIfabsl:
3782 case Builtin::BIcabs:
3783 case Builtin::BIcabsf:
3784 case Builtin::BIcabsl:
3785 return FDecl->getBuiltinID();
3786 }
3787 llvm_unreachable("Unknown Builtin type");
3788}
3789
3790// If the replacement is valid, emit a note with replacement function.
3791// Additionally, suggest including the proper header if not already included.
3792static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00003793 unsigned AbsKind, QualType ArgType) {
3794 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003795 const char *HeaderName = nullptr;
3796 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003797 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3798 FunctionName = "std::abs";
3799 if (ArgType->isIntegralOrEnumerationType()) {
3800 HeaderName = "cstdlib";
3801 } else if (ArgType->isRealFloatingType()) {
3802 HeaderName = "cmath";
3803 } else {
3804 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003805 }
Richard Trieubeffb832014-04-15 23:47:53 +00003806
3807 // Lookup all std::abs
3808 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00003809 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00003810 R.suppressDiagnostics();
3811 S.LookupQualifiedName(R, Std);
3812
3813 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003814 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003815 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3816 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3817 } else {
3818 FDecl = dyn_cast<FunctionDecl>(I);
3819 }
3820 if (!FDecl)
3821 continue;
3822
3823 // Found std::abs(), check that they are the right ones.
3824 if (FDecl->getNumParams() != 1)
3825 continue;
3826
3827 // Check that the parameter type can handle the argument.
3828 QualType ParamType = FDecl->getParamDecl(0)->getType();
3829 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3830 S.Context.getTypeSize(ArgType) <=
3831 S.Context.getTypeSize(ParamType)) {
3832 // Found a function, don't need the header hint.
3833 EmitHeaderHint = false;
3834 break;
3835 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003836 }
Richard Trieubeffb832014-04-15 23:47:53 +00003837 }
3838 } else {
3839 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3840 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3841
3842 if (HeaderName) {
3843 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3844 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3845 R.suppressDiagnostics();
3846 S.LookupName(R, S.getCurScope());
3847
3848 if (R.isSingleResult()) {
3849 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3850 if (FD && FD->getBuiltinID() == AbsKind) {
3851 EmitHeaderHint = false;
3852 } else {
3853 return;
3854 }
3855 } else if (!R.empty()) {
3856 return;
3857 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003858 }
3859 }
3860
3861 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00003862 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003863
Richard Trieubeffb832014-04-15 23:47:53 +00003864 if (!HeaderName)
3865 return;
3866
3867 if (!EmitHeaderHint)
3868 return;
3869
Alp Toker5d96e0a2014-07-11 20:53:51 +00003870 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
3871 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00003872}
3873
3874static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3875 if (!FDecl)
3876 return false;
3877
3878 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
3879 return false;
3880
3881 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
3882
3883 while (ND && ND->isInlineNamespace()) {
3884 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003885 }
Richard Trieubeffb832014-04-15 23:47:53 +00003886
3887 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
3888 return false;
3889
3890 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
3891 return false;
3892
3893 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003894}
3895
3896// Warn when using the wrong abs() function.
3897void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3898 const FunctionDecl *FDecl,
3899 IdentifierInfo *FnInfo) {
3900 if (Call->getNumArgs() != 1)
3901 return;
3902
3903 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00003904 bool IsStdAbs = IsFunctionStdAbs(FDecl);
3905 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003906 return;
3907
3908 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3909 QualType ParamType = Call->getArg(0)->getType();
3910
Alp Toker5d96e0a2014-07-11 20:53:51 +00003911 // Unsigned types cannot be negative. Suggest removing the absolute value
3912 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003913 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00003914 const char *FunctionName =
3915 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003916 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3917 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00003918 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003919 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3920 return;
3921 }
3922
Richard Trieubeffb832014-04-15 23:47:53 +00003923 // std::abs has overloads which prevent most of the absolute value problems
3924 // from occurring.
3925 if (IsStdAbs)
3926 return;
3927
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003928 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3929 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3930
3931 // The argument and parameter are the same kind. Check if they are the right
3932 // size.
3933 if (ArgValueKind == ParamValueKind) {
3934 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3935 return;
3936
3937 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3938 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3939 << FDecl << ArgType << ParamType;
3940
3941 if (NewAbsKind == 0)
3942 return;
3943
3944 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003945 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003946 return;
3947 }
3948
3949 // ArgValueKind != ParamValueKind
3950 // The wrong type of absolute value function was used. Attempt to find the
3951 // proper one.
3952 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3953 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3954 if (NewAbsKind == 0)
3955 return;
3956
3957 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3958 << FDecl << ParamValueKind << ArgValueKind;
3959
3960 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003961 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003962 return;
3963}
3964
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003965//===--- CHECK: Standard memory functions ---------------------------------===//
3966
Nico Weber0e6daef2013-12-26 23:38:39 +00003967/// \brief Takes the expression passed to the size_t parameter of functions
3968/// such as memcmp, strncat, etc and warns if it's a comparison.
3969///
3970/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3971static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3972 IdentifierInfo *FnName,
3973 SourceLocation FnLoc,
3974 SourceLocation RParenLoc) {
3975 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3976 if (!Size)
3977 return false;
3978
3979 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3980 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3981 return false;
3982
Nico Weber0e6daef2013-12-26 23:38:39 +00003983 SourceRange SizeRange = Size->getSourceRange();
3984 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3985 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00003986 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00003987 << FnName << FixItHint::CreateInsertion(
3988 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00003989 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00003990 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00003991 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00003992 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
3993 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00003994
3995 return true;
3996}
3997
Reid Kleckner5fb5b122014-06-27 23:58:21 +00003998/// \brief Determine whether the given type is or contains a dynamic class type
3999/// (e.g., whether it has a vtable).
4000static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4001 bool &IsContained) {
4002 // Look through array types while ignoring qualifiers.
4003 const Type *Ty = T->getBaseElementTypeUnsafe();
4004 IsContained = false;
4005
4006 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4007 RD = RD ? RD->getDefinition() : nullptr;
4008 if (!RD)
4009 return nullptr;
4010
4011 if (RD->isDynamicClass())
4012 return RD;
4013
4014 // Check all the fields. If any bases were dynamic, the class is dynamic.
4015 // It's impossible for a class to transitively contain itself by value, so
4016 // infinite recursion is impossible.
4017 for (auto *FD : RD->fields()) {
4018 bool SubContained;
4019 if (const CXXRecordDecl *ContainedRD =
4020 getContainedDynamicClass(FD->getType(), SubContained)) {
4021 IsContained = true;
4022 return ContainedRD;
4023 }
4024 }
4025
4026 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004027}
4028
Chandler Carruth889ed862011-06-21 23:04:20 +00004029/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004030/// otherwise returns NULL.
4031static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004032 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004033 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4034 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4035 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004036
Craig Topperc3ec1492014-05-26 06:22:03 +00004037 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004038}
4039
Chandler Carruth889ed862011-06-21 23:04:20 +00004040/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004041static QualType getSizeOfArgType(const Expr* E) {
4042 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4043 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4044 if (SizeOf->getKind() == clang::UETT_SizeOf)
4045 return SizeOf->getTypeOfArgument();
4046
4047 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004048}
4049
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004050/// \brief Check for dangerous or invalid arguments to memset().
4051///
Chandler Carruthac687262011-06-03 06:23:57 +00004052/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004053/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4054/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004055///
4056/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004057void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004058 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004059 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004060 assert(BId != 0);
4061
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004062 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004063 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004064 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004065 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004066 return;
4067
Anna Zaks22122702012-01-17 00:37:07 +00004068 unsigned LastArg = (BId == Builtin::BImemset ||
4069 BId == Builtin::BIstrndup ? 1 : 2);
4070 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004071 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004072
Nico Weber0e6daef2013-12-26 23:38:39 +00004073 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4074 Call->getLocStart(), Call->getRParenLoc()))
4075 return;
4076
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004077 // We have special checking when the length is a sizeof expression.
4078 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4079 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4080 llvm::FoldingSetNodeID SizeOfArgID;
4081
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004082 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4083 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004084 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004085
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004086 QualType DestTy = Dest->getType();
4087 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4088 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004089
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004090 // Never warn about void type pointers. This can be used to suppress
4091 // false positives.
4092 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004093 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004094
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004095 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4096 // actually comparing the expressions for equality. Because computing the
4097 // expression IDs can be expensive, we only do this if the diagnostic is
4098 // enabled.
4099 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004100 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4101 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004102 // We only compute IDs for expressions if the warning is enabled, and
4103 // cache the sizeof arg's ID.
4104 if (SizeOfArgID == llvm::FoldingSetNodeID())
4105 SizeOfArg->Profile(SizeOfArgID, Context, true);
4106 llvm::FoldingSetNodeID DestID;
4107 Dest->Profile(DestID, Context, true);
4108 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004109 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4110 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004111 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004112 StringRef ReadableName = FnName->getName();
4113
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004114 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004115 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004116 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004117 if (!PointeeTy->isIncompleteType() &&
4118 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004119 ActionIdx = 2; // If the pointee's size is sizeof(char),
4120 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004121
4122 // If the function is defined as a builtin macro, do not show macro
4123 // expansion.
4124 SourceLocation SL = SizeOfArg->getExprLoc();
4125 SourceRange DSR = Dest->getSourceRange();
4126 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004127 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004128
4129 if (SM.isMacroArgExpansion(SL)) {
4130 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4131 SL = SM.getSpellingLoc(SL);
4132 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4133 SM.getSpellingLoc(DSR.getEnd()));
4134 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4135 SM.getSpellingLoc(SSR.getEnd()));
4136 }
4137
Anna Zaksd08d9152012-05-30 23:14:52 +00004138 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004139 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004140 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004141 << PointeeTy
4142 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004143 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004144 << SSR);
4145 DiagRuntimeBehavior(SL, SizeOfArg,
4146 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4147 << ActionIdx
4148 << SSR);
4149
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004150 break;
4151 }
4152 }
4153
4154 // Also check for cases where the sizeof argument is the exact same
4155 // type as the memory argument, and where it points to a user-defined
4156 // record type.
4157 if (SizeOfArgTy != QualType()) {
4158 if (PointeeTy->isRecordType() &&
4159 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4160 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4161 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4162 << FnName << SizeOfArgTy << ArgIdx
4163 << PointeeTy << Dest->getSourceRange()
4164 << LenExpr->getSourceRange());
4165 break;
4166 }
Nico Weberc5e73862011-06-14 16:14:58 +00004167 }
4168
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004169 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004170 bool IsContained;
4171 if (const CXXRecordDecl *ContainedRD =
4172 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004173
4174 unsigned OperationType = 0;
4175 // "overwritten" if we're warning about the destination for any call
4176 // but memcmp; otherwise a verb appropriate to the call.
4177 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4178 if (BId == Builtin::BImemcpy)
4179 OperationType = 1;
4180 else if(BId == Builtin::BImemmove)
4181 OperationType = 2;
4182 else if (BId == Builtin::BImemcmp)
4183 OperationType = 3;
4184 }
4185
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004186 DiagRuntimeBehavior(
4187 Dest->getExprLoc(), Dest,
4188 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004189 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004190 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004191 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004192 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4193 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004194 DiagRuntimeBehavior(
4195 Dest->getExprLoc(), Dest,
4196 PDiag(diag::warn_arc_object_memaccess)
4197 << ArgIdx << FnName << PointeeTy
4198 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004199 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004200 continue;
John McCall31168b02011-06-15 23:02:42 +00004201
4202 DiagRuntimeBehavior(
4203 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004204 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004205 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4206 break;
4207 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004208 }
4209}
4210
Ted Kremenek6865f772011-08-18 20:55:45 +00004211// A little helper routine: ignore addition and subtraction of integer literals.
4212// This intentionally does not ignore all integer constant expressions because
4213// we don't want to remove sizeof().
4214static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4215 Ex = Ex->IgnoreParenCasts();
4216
4217 for (;;) {
4218 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4219 if (!BO || !BO->isAdditiveOp())
4220 break;
4221
4222 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4223 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4224
4225 if (isa<IntegerLiteral>(RHS))
4226 Ex = LHS;
4227 else if (isa<IntegerLiteral>(LHS))
4228 Ex = RHS;
4229 else
4230 break;
4231 }
4232
4233 return Ex;
4234}
4235
Anna Zaks13b08572012-08-08 21:42:23 +00004236static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4237 ASTContext &Context) {
4238 // Only handle constant-sized or VLAs, but not flexible members.
4239 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4240 // Only issue the FIXIT for arrays of size > 1.
4241 if (CAT->getSize().getSExtValue() <= 1)
4242 return false;
4243 } else if (!Ty->isVariableArrayType()) {
4244 return false;
4245 }
4246 return true;
4247}
4248
Ted Kremenek6865f772011-08-18 20:55:45 +00004249// Warn if the user has made the 'size' argument to strlcpy or strlcat
4250// be the size of the source, instead of the destination.
4251void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4252 IdentifierInfo *FnName) {
4253
4254 // Don't crash if the user has the wrong number of arguments
4255 if (Call->getNumArgs() != 3)
4256 return;
4257
4258 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4259 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004260 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004261
4262 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4263 Call->getLocStart(), Call->getRParenLoc()))
4264 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004265
4266 // Look for 'strlcpy(dst, x, sizeof(x))'
4267 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4268 CompareWithSrc = Ex;
4269 else {
4270 // Look for 'strlcpy(dst, x, strlen(x))'
4271 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004272 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4273 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004274 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4275 }
4276 }
4277
4278 if (!CompareWithSrc)
4279 return;
4280
4281 // Determine if the argument to sizeof/strlen is equal to the source
4282 // argument. In principle there's all kinds of things you could do
4283 // here, for instance creating an == expression and evaluating it with
4284 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4285 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4286 if (!SrcArgDRE)
4287 return;
4288
4289 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4290 if (!CompareWithSrcDRE ||
4291 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4292 return;
4293
4294 const Expr *OriginalSizeArg = Call->getArg(2);
4295 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4296 << OriginalSizeArg->getSourceRange() << FnName;
4297
4298 // Output a FIXIT hint if the destination is an array (rather than a
4299 // pointer to an array). This could be enhanced to handle some
4300 // pointers if we know the actual size, like if DstArg is 'array+2'
4301 // we could say 'sizeof(array)-2'.
4302 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004303 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004304 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004305
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004306 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004307 llvm::raw_svector_ostream OS(sizeString);
4308 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004309 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004310 OS << ")";
4311
4312 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4313 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4314 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004315}
4316
Anna Zaks314cd092012-02-01 19:08:57 +00004317/// Check if two expressions refer to the same declaration.
4318static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4319 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4320 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4321 return D1->getDecl() == D2->getDecl();
4322 return false;
4323}
4324
4325static const Expr *getStrlenExprArg(const Expr *E) {
4326 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4327 const FunctionDecl *FD = CE->getDirectCallee();
4328 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004329 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004330 return CE->getArg(0)->IgnoreParenCasts();
4331 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004332 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004333}
4334
4335// Warn on anti-patterns as the 'size' argument to strncat.
4336// The correct size argument should look like following:
4337// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4338void Sema::CheckStrncatArguments(const CallExpr *CE,
4339 IdentifierInfo *FnName) {
4340 // Don't crash if the user has the wrong number of arguments.
4341 if (CE->getNumArgs() < 3)
4342 return;
4343 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4344 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4345 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4346
Nico Weber0e6daef2013-12-26 23:38:39 +00004347 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4348 CE->getRParenLoc()))
4349 return;
4350
Anna Zaks314cd092012-02-01 19:08:57 +00004351 // Identify common expressions, which are wrongly used as the size argument
4352 // to strncat and may lead to buffer overflows.
4353 unsigned PatternType = 0;
4354 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4355 // - sizeof(dst)
4356 if (referToTheSameDecl(SizeOfArg, DstArg))
4357 PatternType = 1;
4358 // - sizeof(src)
4359 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4360 PatternType = 2;
4361 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4362 if (BE->getOpcode() == BO_Sub) {
4363 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4364 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4365 // - sizeof(dst) - strlen(dst)
4366 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4367 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4368 PatternType = 1;
4369 // - sizeof(src) - (anything)
4370 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4371 PatternType = 2;
4372 }
4373 }
4374
4375 if (PatternType == 0)
4376 return;
4377
Anna Zaks5069aa32012-02-03 01:27:37 +00004378 // Generate the diagnostic.
4379 SourceLocation SL = LenArg->getLocStart();
4380 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004381 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004382
4383 // If the function is defined as a builtin macro, do not show macro expansion.
4384 if (SM.isMacroArgExpansion(SL)) {
4385 SL = SM.getSpellingLoc(SL);
4386 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4387 SM.getSpellingLoc(SR.getEnd()));
4388 }
4389
Anna Zaks13b08572012-08-08 21:42:23 +00004390 // Check if the destination is an array (rather than a pointer to an array).
4391 QualType DstTy = DstArg->getType();
4392 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4393 Context);
4394 if (!isKnownSizeArray) {
4395 if (PatternType == 1)
4396 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4397 else
4398 Diag(SL, diag::warn_strncat_src_size) << SR;
4399 return;
4400 }
4401
Anna Zaks314cd092012-02-01 19:08:57 +00004402 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004403 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004404 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004405 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004406
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004407 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004408 llvm::raw_svector_ostream OS(sizeString);
4409 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004410 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004411 OS << ") - ";
4412 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004413 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004414 OS << ") - 1";
4415
Anna Zaks5069aa32012-02-03 01:27:37 +00004416 Diag(SL, diag::note_strncat_wrong_size)
4417 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004418}
4419
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004420//===--- CHECK: Return Address of Stack Variable --------------------------===//
4421
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004422static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4423 Decl *ParentDecl);
4424static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4425 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004426
4427/// CheckReturnStackAddr - Check if a return statement returns the address
4428/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004429static void
4430CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4431 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004432
Craig Topperc3ec1492014-05-26 06:22:03 +00004433 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004434 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004435
4436 // Perform checking for returned stack addresses, local blocks,
4437 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004438 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004439 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004440 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004441 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004442 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004443 }
4444
Craig Topperc3ec1492014-05-26 06:22:03 +00004445 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004446 return; // Nothing suspicious was found.
4447
4448 SourceLocation diagLoc;
4449 SourceRange diagRange;
4450 if (refVars.empty()) {
4451 diagLoc = stackE->getLocStart();
4452 diagRange = stackE->getSourceRange();
4453 } else {
4454 // We followed through a reference variable. 'stackE' contains the
4455 // problematic expression but we will warn at the return statement pointing
4456 // at the reference variable. We will later display the "trail" of
4457 // reference variables using notes.
4458 diagLoc = refVars[0]->getLocStart();
4459 diagRange = refVars[0]->getSourceRange();
4460 }
4461
4462 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004463 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004464 : diag::warn_ret_stack_addr)
4465 << DR->getDecl()->getDeclName() << diagRange;
4466 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004467 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004468 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004469 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004470 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004471 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4472 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004473 << diagRange;
4474 }
4475
4476 // Display the "trail" of reference variables that we followed until we
4477 // found the problematic expression using notes.
4478 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4479 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4480 // If this var binds to another reference var, show the range of the next
4481 // var, otherwise the var binds to the problematic expression, in which case
4482 // show the range of the expression.
4483 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4484 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004485 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4486 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004487 }
4488}
4489
4490/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4491/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004492/// to a location on the stack, a local block, an address of a label, or a
4493/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004494/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004495/// encounter a subexpression that (1) clearly does not lead to one of the
4496/// above problematic expressions (2) is something we cannot determine leads to
4497/// a problematic expression based on such local checking.
4498///
4499/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4500/// the expression that they point to. Such variables are added to the
4501/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004502///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004503/// EvalAddr processes expressions that are pointers that are used as
4504/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004505/// At the base case of the recursion is a check for the above problematic
4506/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004507///
4508/// This implementation handles:
4509///
4510/// * pointer-to-pointer casts
4511/// * implicit conversions from array references to pointers
4512/// * taking the address of fields
4513/// * arbitrary interplay between "&" and "*" operators
4514/// * pointer arithmetic from an address of a stack variable
4515/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004516static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4517 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004518 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004519 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004520
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004521 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004522 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004523 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004524 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004525 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004526
Peter Collingbourne91147592011-04-15 00:35:48 +00004527 E = E->IgnoreParens();
4528
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004529 // Our "symbolic interpreter" is just a dispatch off the currently
4530 // viewed AST node. We then recursively traverse the AST by calling
4531 // EvalAddr and EvalVal appropriately.
4532 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004533 case Stmt::DeclRefExprClass: {
4534 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4535
Richard Smith40f08eb2014-01-30 22:05:38 +00004536 // If we leave the immediate function, the lifetime isn't about to end.
4537 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004538 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004539
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004540 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4541 // If this is a reference variable, follow through to the expression that
4542 // it points to.
4543 if (V->hasLocalStorage() &&
4544 V->getType()->isReferenceType() && V->hasInit()) {
4545 // Add the reference variable to the "trail".
4546 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004547 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004548 }
4549
Craig Topperc3ec1492014-05-26 06:22:03 +00004550 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004551 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004552
Chris Lattner934edb22007-12-28 05:31:15 +00004553 case Stmt::UnaryOperatorClass: {
4554 // The only unary operator that make sense to handle here
4555 // is AddrOf. All others don't make sense as pointers.
4556 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004557
John McCalle3027922010-08-25 11:45:40 +00004558 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004559 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004560 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004561 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004562 }
Mike Stump11289f42009-09-09 15:08:12 +00004563
Chris Lattner934edb22007-12-28 05:31:15 +00004564 case Stmt::BinaryOperatorClass: {
4565 // Handle pointer arithmetic. All other binary operators are not valid
4566 // in this context.
4567 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004568 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004569
John McCalle3027922010-08-25 11:45:40 +00004570 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004571 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004572
Chris Lattner934edb22007-12-28 05:31:15 +00004573 Expr *Base = B->getLHS();
4574
4575 // Determine which argument is the real pointer base. It could be
4576 // the RHS argument instead of the LHS.
4577 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004578
Chris Lattner934edb22007-12-28 05:31:15 +00004579 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004580 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004581 }
Steve Naroff2752a172008-09-10 19:17:48 +00004582
Chris Lattner934edb22007-12-28 05:31:15 +00004583 // For conditional operators we need to see if either the LHS or RHS are
4584 // valid DeclRefExpr*s. If one of them is valid, we return it.
4585 case Stmt::ConditionalOperatorClass: {
4586 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004587
Chris Lattner934edb22007-12-28 05:31:15 +00004588 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004589 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4590 if (Expr *LHSExpr = C->getLHS()) {
4591 // In C++, we can have a throw-expression, which has 'void' type.
4592 if (!LHSExpr->getType()->isVoidType())
4593 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004594 return LHS;
4595 }
Chris Lattner934edb22007-12-28 05:31:15 +00004596
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004597 // In C++, we can have a throw-expression, which has 'void' type.
4598 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004599 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004600
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004601 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004602 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004603
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004604 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004605 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004606 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004607 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004608
4609 case Stmt::AddrLabelExprClass:
4610 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004611
John McCall28fc7092011-11-10 05:35:25 +00004612 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004613 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4614 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004615
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004616 // For casts, we need to handle conversions from arrays to
4617 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004618 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004619 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004620 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004621 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004622 case Stmt::CXXStaticCastExprClass:
4623 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004624 case Stmt::CXXConstCastExprClass:
4625 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004626 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4627 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00004628 case CK_LValueToRValue:
4629 case CK_NoOp:
4630 case CK_BaseToDerived:
4631 case CK_DerivedToBase:
4632 case CK_UncheckedDerivedToBase:
4633 case CK_Dynamic:
4634 case CK_CPointerToObjCPointerCast:
4635 case CK_BlockPointerToObjCPointerCast:
4636 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004637 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004638
4639 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004640 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004641
Richard Trieudadefde2014-07-02 04:39:38 +00004642 case CK_BitCast:
4643 if (SubExpr->getType()->isAnyPointerType() ||
4644 SubExpr->getType()->isBlockPointerType() ||
4645 SubExpr->getType()->isObjCQualifiedIdType())
4646 return EvalAddr(SubExpr, refVars, ParentDecl);
4647 else
4648 return nullptr;
4649
Eli Friedman8195ad72012-02-23 23:04:32 +00004650 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004651 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004652 }
Chris Lattner934edb22007-12-28 05:31:15 +00004653 }
Mike Stump11289f42009-09-09 15:08:12 +00004654
Douglas Gregorfe314812011-06-21 17:03:29 +00004655 case Stmt::MaterializeTemporaryExprClass:
4656 if (Expr *Result = EvalAddr(
4657 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004658 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004659 return Result;
4660
4661 return E;
4662
Chris Lattner934edb22007-12-28 05:31:15 +00004663 // Everything else: we simply don't reason about them.
4664 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004665 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004666 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004667}
Mike Stump11289f42009-09-09 15:08:12 +00004668
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004669
4670/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4671/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004672static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4673 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004674do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004675 // We should only be called for evaluating non-pointer expressions, or
4676 // expressions with a pointer type that are not used as references but instead
4677 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004678
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004679 // Our "symbolic interpreter" is just a dispatch off the currently
4680 // viewed AST node. We then recursively traverse the AST by calling
4681 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004682
4683 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004684 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004685 case Stmt::ImplicitCastExprClass: {
4686 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004687 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004688 E = IE->getSubExpr();
4689 continue;
4690 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004691 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004692 }
4693
John McCall28fc7092011-11-10 05:35:25 +00004694 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004695 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004696
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004697 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004698 // When we hit a DeclRefExpr we are looking at code that refers to a
4699 // variable's name. If it's not a reference variable we check if it has
4700 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004701 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004702
Richard Smith40f08eb2014-01-30 22:05:38 +00004703 // If we leave the immediate function, the lifetime isn't about to end.
4704 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004705 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004706
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004707 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4708 // Check if it refers to itself, e.g. "int& i = i;".
4709 if (V == ParentDecl)
4710 return DR;
4711
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004712 if (V->hasLocalStorage()) {
4713 if (!V->getType()->isReferenceType())
4714 return DR;
4715
4716 // Reference variable, follow through to the expression that
4717 // it points to.
4718 if (V->hasInit()) {
4719 // Add the reference variable to the "trail".
4720 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004721 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004722 }
4723 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004724 }
Mike Stump11289f42009-09-09 15:08:12 +00004725
Craig Topperc3ec1492014-05-26 06:22:03 +00004726 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004727 }
Mike Stump11289f42009-09-09 15:08:12 +00004728
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004729 case Stmt::UnaryOperatorClass: {
4730 // The only unary operator that make sense to handle here
4731 // is Deref. All others don't resolve to a "name." This includes
4732 // handling all sorts of rvalues passed to a unary operator.
4733 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004734
John McCalle3027922010-08-25 11:45:40 +00004735 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004736 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004737
Craig Topperc3ec1492014-05-26 06:22:03 +00004738 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004739 }
Mike Stump11289f42009-09-09 15:08:12 +00004740
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004741 case Stmt::ArraySubscriptExprClass: {
4742 // Array subscripts are potential references to data on the stack. We
4743 // retrieve the DeclRefExpr* for the array variable if it indeed
4744 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004745 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004746 }
Mike Stump11289f42009-09-09 15:08:12 +00004747
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004748 case Stmt::ConditionalOperatorClass: {
4749 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004750 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004751 ConditionalOperator *C = cast<ConditionalOperator>(E);
4752
Anders Carlsson801c5c72007-11-30 19:04:31 +00004753 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004754 if (Expr *LHSExpr = C->getLHS()) {
4755 // In C++, we can have a throw-expression, which has 'void' type.
4756 if (!LHSExpr->getType()->isVoidType())
4757 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4758 return LHS;
4759 }
4760
4761 // In C++, we can have a throw-expression, which has 'void' type.
4762 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004763 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004764
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004765 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004766 }
Mike Stump11289f42009-09-09 15:08:12 +00004767
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004768 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004769 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004770 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004771
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004772 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004773 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00004774 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004775
4776 // Check whether the member type is itself a reference, in which case
4777 // we're not going to refer to the member, but to what the member refers to.
4778 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004779 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004780
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004781 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004782 }
Mike Stump11289f42009-09-09 15:08:12 +00004783
Douglas Gregorfe314812011-06-21 17:03:29 +00004784 case Stmt::MaterializeTemporaryExprClass:
4785 if (Expr *Result = EvalVal(
4786 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004787 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004788 return Result;
4789
4790 return E;
4791
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004792 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004793 // Check that we don't return or take the address of a reference to a
4794 // temporary. This is only useful in C++.
4795 if (!E->isTypeDependent() && E->isRValue())
4796 return E;
4797
4798 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00004799 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004800 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004801} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004802}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004803
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004804void
4805Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4806 SourceLocation ReturnLoc,
4807 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004808 const AttrVec *Attrs,
4809 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004810 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4811
4812 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004813 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4814 CheckNonNullExpr(*this, RetValExp))
4815 Diag(ReturnLoc, diag::warn_null_ret)
4816 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004817
4818 // C++11 [basic.stc.dynamic.allocation]p4:
4819 // If an allocation function declared with a non-throwing
4820 // exception-specification fails to allocate storage, it shall return
4821 // a null pointer. Any other allocation function that fails to allocate
4822 // storage shall indicate failure only by throwing an exception [...]
4823 if (FD) {
4824 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4825 if (Op == OO_New || Op == OO_Array_New) {
4826 const FunctionProtoType *Proto
4827 = FD->getType()->castAs<FunctionProtoType>();
4828 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4829 CheckNonNullExpr(*this, RetValExp))
4830 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4831 << FD << getLangOpts().CPlusPlus11;
4832 }
4833 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004834}
4835
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004836//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4837
4838/// Check for comparisons of floating point operands using != and ==.
4839/// Issue a warning if these are no self-comparisons, as they are not likely
4840/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004841void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004842 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4843 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004844
4845 // Special case: check for x == x (which is OK).
4846 // Do not emit warnings for such cases.
4847 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4848 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4849 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004850 return;
Mike Stump11289f42009-09-09 15:08:12 +00004851
4852
Ted Kremenekeda40e22007-11-29 00:59:04 +00004853 // Special case: check for comparisons against literals that can be exactly
4854 // represented by APFloat. In such cases, do not emit a warning. This
4855 // is a heuristic: often comparison against such literals are used to
4856 // detect if a value in a variable has not changed. This clearly can
4857 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004858 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4859 if (FLL->isExact())
4860 return;
4861 } else
4862 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4863 if (FLR->isExact())
4864 return;
Mike Stump11289f42009-09-09 15:08:12 +00004865
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004866 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004867 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004868 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004869 return;
Mike Stump11289f42009-09-09 15:08:12 +00004870
David Blaikie1f4ff152012-07-16 20:47:22 +00004871 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004872 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004873 return;
Mike Stump11289f42009-09-09 15:08:12 +00004874
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004875 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004876 Diag(Loc, diag::warn_floatingpoint_eq)
4877 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004878}
John McCallca01b222010-01-04 23:21:16 +00004879
John McCall70aa5392010-01-06 05:24:50 +00004880//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4881//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004882
John McCall70aa5392010-01-06 05:24:50 +00004883namespace {
John McCallca01b222010-01-04 23:21:16 +00004884
John McCall70aa5392010-01-06 05:24:50 +00004885/// Structure recording the 'active' range of an integer-valued
4886/// expression.
4887struct IntRange {
4888 /// The number of bits active in the int.
4889 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004890
John McCall70aa5392010-01-06 05:24:50 +00004891 /// True if the int is known not to have negative values.
4892 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004893
John McCall70aa5392010-01-06 05:24:50 +00004894 IntRange(unsigned Width, bool NonNegative)
4895 : Width(Width), NonNegative(NonNegative)
4896 {}
John McCallca01b222010-01-04 23:21:16 +00004897
John McCall817d4af2010-11-10 23:38:19 +00004898 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004899 static IntRange forBoolType() {
4900 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004901 }
4902
John McCall817d4af2010-11-10 23:38:19 +00004903 /// Returns the range of an opaque value of the given integral type.
4904 static IntRange forValueOfType(ASTContext &C, QualType T) {
4905 return forValueOfCanonicalType(C,
4906 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004907 }
4908
John McCall817d4af2010-11-10 23:38:19 +00004909 /// Returns the range of an opaque value of a canonical integral type.
4910 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004911 assert(T->isCanonicalUnqualified());
4912
4913 if (const VectorType *VT = dyn_cast<VectorType>(T))
4914 T = VT->getElementType().getTypePtr();
4915 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4916 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004917
David Majnemer6a426652013-06-07 22:07:20 +00004918 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004919 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004920 EnumDecl *Enum = ET->getDecl();
4921 if (!Enum->isCompleteDefinition())
4922 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004923
David Majnemer6a426652013-06-07 22:07:20 +00004924 unsigned NumPositive = Enum->getNumPositiveBits();
4925 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004926
David Majnemer6a426652013-06-07 22:07:20 +00004927 if (NumNegative == 0)
4928 return IntRange(NumPositive, true/*NonNegative*/);
4929 else
4930 return IntRange(std::max(NumPositive + 1, NumNegative),
4931 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004932 }
John McCall70aa5392010-01-06 05:24:50 +00004933
4934 const BuiltinType *BT = cast<BuiltinType>(T);
4935 assert(BT->isInteger());
4936
4937 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4938 }
4939
John McCall817d4af2010-11-10 23:38:19 +00004940 /// Returns the "target" range of a canonical integral type, i.e.
4941 /// the range of values expressible in the type.
4942 ///
4943 /// This matches forValueOfCanonicalType except that enums have the
4944 /// full range of their type, not the range of their enumerators.
4945 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4946 assert(T->isCanonicalUnqualified());
4947
4948 if (const VectorType *VT = dyn_cast<VectorType>(T))
4949 T = VT->getElementType().getTypePtr();
4950 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4951 T = CT->getElementType().getTypePtr();
4952 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004953 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004954
4955 const BuiltinType *BT = cast<BuiltinType>(T);
4956 assert(BT->isInteger());
4957
4958 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4959 }
4960
4961 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004962 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004963 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004964 L.NonNegative && R.NonNegative);
4965 }
4966
John McCall817d4af2010-11-10 23:38:19 +00004967 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004968 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004969 return IntRange(std::min(L.Width, R.Width),
4970 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004971 }
4972};
4973
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004974static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4975 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004976 if (value.isSigned() && value.isNegative())
4977 return IntRange(value.getMinSignedBits(), false);
4978
4979 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004980 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004981
4982 // isNonNegative() just checks the sign bit without considering
4983 // signedness.
4984 return IntRange(value.getActiveBits(), true);
4985}
4986
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004987static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4988 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004989 if (result.isInt())
4990 return GetValueRange(C, result.getInt(), MaxWidth);
4991
4992 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004993 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4994 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4995 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4996 R = IntRange::join(R, El);
4997 }
John McCall70aa5392010-01-06 05:24:50 +00004998 return R;
4999 }
5000
5001 if (result.isComplexInt()) {
5002 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5003 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5004 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005005 }
5006
5007 // This can happen with lossless casts to intptr_t of "based" lvalues.
5008 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005009 // FIXME: The only reason we need to pass the type in here is to get
5010 // the sign right on this one case. It would be nice if APValue
5011 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005012 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005013 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005014}
John McCall70aa5392010-01-06 05:24:50 +00005015
Eli Friedmane6d33952013-07-08 20:20:06 +00005016static QualType GetExprType(Expr *E) {
5017 QualType Ty = E->getType();
5018 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5019 Ty = AtomicRHS->getValueType();
5020 return Ty;
5021}
5022
John McCall70aa5392010-01-06 05:24:50 +00005023/// Pseudo-evaluate the given integer expression, estimating the
5024/// range of values it might take.
5025///
5026/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005027static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005028 E = E->IgnoreParens();
5029
5030 // Try a full evaluation first.
5031 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005032 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005033 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005034
5035 // I think we only want to look through implicit casts here; if the
5036 // user has an explicit widening cast, we should treat the value as
5037 // being of the new, wider type.
5038 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005039 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005040 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5041
Eli Friedmane6d33952013-07-08 20:20:06 +00005042 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005043
John McCalle3027922010-08-25 11:45:40 +00005044 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005045
John McCall70aa5392010-01-06 05:24:50 +00005046 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005047 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005048 return OutputTypeRange;
5049
5050 IntRange SubRange
5051 = GetExprRange(C, CE->getSubExpr(),
5052 std::min(MaxWidth, OutputTypeRange.Width));
5053
5054 // Bail out if the subexpr's range is as wide as the cast type.
5055 if (SubRange.Width >= OutputTypeRange.Width)
5056 return OutputTypeRange;
5057
5058 // Otherwise, we take the smaller width, and we're non-negative if
5059 // either the output type or the subexpr is.
5060 return IntRange(SubRange.Width,
5061 SubRange.NonNegative || OutputTypeRange.NonNegative);
5062 }
5063
5064 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5065 // If we can fold the condition, just take that operand.
5066 bool CondResult;
5067 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5068 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5069 : CO->getFalseExpr(),
5070 MaxWidth);
5071
5072 // Otherwise, conservatively merge.
5073 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5074 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5075 return IntRange::join(L, R);
5076 }
5077
5078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5079 switch (BO->getOpcode()) {
5080
5081 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005082 case BO_LAnd:
5083 case BO_LOr:
5084 case BO_LT:
5085 case BO_GT:
5086 case BO_LE:
5087 case BO_GE:
5088 case BO_EQ:
5089 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005090 return IntRange::forBoolType();
5091
John McCallc3688382011-07-13 06:35:24 +00005092 // The type of the assignments is the type of the LHS, so the RHS
5093 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005094 case BO_MulAssign:
5095 case BO_DivAssign:
5096 case BO_RemAssign:
5097 case BO_AddAssign:
5098 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005099 case BO_XorAssign:
5100 case BO_OrAssign:
5101 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005102 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005103
John McCallc3688382011-07-13 06:35:24 +00005104 // Simple assignments just pass through the RHS, which will have
5105 // been coerced to the LHS type.
5106 case BO_Assign:
5107 // TODO: bitfields?
5108 return GetExprRange(C, BO->getRHS(), MaxWidth);
5109
John McCall70aa5392010-01-06 05:24:50 +00005110 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005111 case BO_PtrMemD:
5112 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005113 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005114
John McCall2ce81ad2010-01-06 22:07:33 +00005115 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005116 case BO_And:
5117 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005118 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5119 GetExprRange(C, BO->getRHS(), MaxWidth));
5120
John McCall70aa5392010-01-06 05:24:50 +00005121 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005122 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005123 // ...except that we want to treat '1 << (blah)' as logically
5124 // positive. It's an important idiom.
5125 if (IntegerLiteral *I
5126 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5127 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005128 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005129 return IntRange(R.Width, /*NonNegative*/ true);
5130 }
5131 }
5132 // fallthrough
5133
John McCalle3027922010-08-25 11:45:40 +00005134 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005135 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005136
John McCall2ce81ad2010-01-06 22:07:33 +00005137 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005138 case BO_Shr:
5139 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005140 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5141
5142 // If the shift amount is a positive constant, drop the width by
5143 // that much.
5144 llvm::APSInt shift;
5145 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5146 shift.isNonNegative()) {
5147 unsigned zext = shift.getZExtValue();
5148 if (zext >= L.Width)
5149 L.Width = (L.NonNegative ? 0 : 1);
5150 else
5151 L.Width -= zext;
5152 }
5153
5154 return L;
5155 }
5156
5157 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005158 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005159 return GetExprRange(C, BO->getRHS(), MaxWidth);
5160
John McCall2ce81ad2010-01-06 22:07:33 +00005161 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005162 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005163 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005164 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005165 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005166
John McCall51431812011-07-14 22:39:48 +00005167 // The width of a division result is mostly determined by the size
5168 // of the LHS.
5169 case BO_Div: {
5170 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005171 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005172 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5173
5174 // If the divisor is constant, use that.
5175 llvm::APSInt divisor;
5176 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5177 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5178 if (log2 >= L.Width)
5179 L.Width = (L.NonNegative ? 0 : 1);
5180 else
5181 L.Width = std::min(L.Width - log2, MaxWidth);
5182 return L;
5183 }
5184
5185 // Otherwise, just use the LHS's width.
5186 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5187 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5188 }
5189
5190 // The result of a remainder can't be larger than the result of
5191 // either side.
5192 case BO_Rem: {
5193 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005194 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005195 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5196 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5197
5198 IntRange meet = IntRange::meet(L, R);
5199 meet.Width = std::min(meet.Width, MaxWidth);
5200 return meet;
5201 }
5202
5203 // The default behavior is okay for these.
5204 case BO_Mul:
5205 case BO_Add:
5206 case BO_Xor:
5207 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005208 break;
5209 }
5210
John McCall51431812011-07-14 22:39:48 +00005211 // The default case is to treat the operation as if it were closed
5212 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005213 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5214 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5215 return IntRange::join(L, R);
5216 }
5217
5218 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5219 switch (UO->getOpcode()) {
5220 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005221 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005222 return IntRange::forBoolType();
5223
5224 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005225 case UO_Deref:
5226 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005227 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005228
5229 default:
5230 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5231 }
5232 }
5233
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005234 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5235 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5236
John McCalld25db7e2013-05-06 21:39:12 +00005237 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005238 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005239 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005240
Eli Friedmane6d33952013-07-08 20:20:06 +00005241 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005242}
John McCall263a48b2010-01-04 23:31:57 +00005243
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005244static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005245 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005246}
5247
John McCall263a48b2010-01-04 23:31:57 +00005248/// Checks whether the given value, which currently has the given
5249/// source semantics, has the same value when coerced through the
5250/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005251static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5252 const llvm::fltSemantics &Src,
5253 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005254 llvm::APFloat truncated = value;
5255
5256 bool ignored;
5257 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5258 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5259
5260 return truncated.bitwiseIsEqual(value);
5261}
5262
5263/// Checks whether the given value, which currently has the given
5264/// source semantics, has the same value when coerced through the
5265/// target semantics.
5266///
5267/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005268static bool IsSameFloatAfterCast(const APValue &value,
5269 const llvm::fltSemantics &Src,
5270 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005271 if (value.isFloat())
5272 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5273
5274 if (value.isVector()) {
5275 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5276 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5277 return false;
5278 return true;
5279 }
5280
5281 assert(value.isComplexFloat());
5282 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5283 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5284}
5285
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005286static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005287
Ted Kremenek6274be42010-09-23 21:43:44 +00005288static bool IsZero(Sema &S, Expr *E) {
5289 // Suppress cases where we are comparing against an enum constant.
5290 if (const DeclRefExpr *DR =
5291 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5292 if (isa<EnumConstantDecl>(DR->getDecl()))
5293 return false;
5294
5295 // Suppress cases where the '0' value is expanded from a macro.
5296 if (E->getLocStart().isMacroID())
5297 return false;
5298
John McCallcc7e5bf2010-05-06 08:58:33 +00005299 llvm::APSInt Value;
5300 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5301}
5302
John McCall2551c1b2010-10-06 00:25:24 +00005303static bool HasEnumType(Expr *E) {
5304 // Strip off implicit integral promotions.
5305 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005306 if (ICE->getCastKind() != CK_IntegralCast &&
5307 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005308 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005309 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005310 }
5311
5312 return E->getType()->isEnumeralType();
5313}
5314
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005315static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005316 // Disable warning in template instantiations.
5317 if (!S.ActiveTemplateInstantiations.empty())
5318 return;
5319
John McCalle3027922010-08-25 11:45:40 +00005320 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005321 if (E->isValueDependent())
5322 return;
5323
John McCalle3027922010-08-25 11:45:40 +00005324 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005325 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005326 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005327 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005328 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005329 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005330 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005331 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005332 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005333 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005334 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005335 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005336 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005337 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005338 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005339 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5340 }
5341}
5342
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005343static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005344 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005345 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005346 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005347 // Disable warning in template instantiations.
5348 if (!S.ActiveTemplateInstantiations.empty())
5349 return;
5350
Richard Trieu0f097742014-04-04 04:13:47 +00005351 // TODO: Investigate using GetExprRange() to get tighter bounds
5352 // on the bit ranges.
5353 QualType OtherT = Other->getType();
5354 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5355 unsigned OtherWidth = OtherRange.Width;
5356
5357 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5358
Richard Trieu560910c2012-11-14 22:50:24 +00005359 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005360 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005361 return;
5362
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005363 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005364 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005365
Richard Trieu0f097742014-04-04 04:13:47 +00005366 // Used for diagnostic printout.
5367 enum {
5368 LiteralConstant = 0,
5369 CXXBoolLiteralTrue,
5370 CXXBoolLiteralFalse
5371 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005372
Richard Trieu0f097742014-04-04 04:13:47 +00005373 if (!OtherIsBooleanType) {
5374 QualType ConstantT = Constant->getType();
5375 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005376
Richard Trieu0f097742014-04-04 04:13:47 +00005377 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5378 return;
5379 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5380 "comparison with non-integer type");
5381
5382 bool ConstantSigned = ConstantT->isSignedIntegerType();
5383 bool CommonSigned = CommonT->isSignedIntegerType();
5384
5385 bool EqualityOnly = false;
5386
5387 if (CommonSigned) {
5388 // The common type is signed, therefore no signed to unsigned conversion.
5389 if (!OtherRange.NonNegative) {
5390 // Check that the constant is representable in type OtherT.
5391 if (ConstantSigned) {
5392 if (OtherWidth >= Value.getMinSignedBits())
5393 return;
5394 } else { // !ConstantSigned
5395 if (OtherWidth >= Value.getActiveBits() + 1)
5396 return;
5397 }
5398 } else { // !OtherSigned
5399 // Check that the constant is representable in type OtherT.
5400 // Negative values are out of range.
5401 if (ConstantSigned) {
5402 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5403 return;
5404 } else { // !ConstantSigned
5405 if (OtherWidth >= Value.getActiveBits())
5406 return;
5407 }
Richard Trieu560910c2012-11-14 22:50:24 +00005408 }
Richard Trieu0f097742014-04-04 04:13:47 +00005409 } else { // !CommonSigned
5410 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005411 if (OtherWidth >= Value.getActiveBits())
5412 return;
Craig Toppercf360162014-06-18 05:13:11 +00005413 } else { // OtherSigned
5414 assert(!ConstantSigned &&
5415 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005416 // Check to see if the constant is representable in OtherT.
5417 if (OtherWidth > Value.getActiveBits())
5418 return;
5419 // Check to see if the constant is equivalent to a negative value
5420 // cast to CommonT.
5421 if (S.Context.getIntWidth(ConstantT) ==
5422 S.Context.getIntWidth(CommonT) &&
5423 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5424 return;
5425 // The constant value rests between values that OtherT can represent
5426 // after conversion. Relational comparison still works, but equality
5427 // comparisons will be tautological.
5428 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005429 }
5430 }
Richard Trieu0f097742014-04-04 04:13:47 +00005431
5432 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5433
5434 if (op == BO_EQ || op == BO_NE) {
5435 IsTrue = op == BO_NE;
5436 } else if (EqualityOnly) {
5437 return;
5438 } else if (RhsConstant) {
5439 if (op == BO_GT || op == BO_GE)
5440 IsTrue = !PositiveConstant;
5441 else // op == BO_LT || op == BO_LE
5442 IsTrue = PositiveConstant;
5443 } else {
5444 if (op == BO_LT || op == BO_LE)
5445 IsTrue = !PositiveConstant;
5446 else // op == BO_GT || op == BO_GE
5447 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005448 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005449 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005450 // Other isKnownToHaveBooleanValue
5451 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5452 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5453 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5454
5455 static const struct LinkedConditions {
5456 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5457 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5458 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5459 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5460 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5461 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5462
5463 } TruthTable = {
5464 // Constant on LHS. | Constant on RHS. |
5465 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5466 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5467 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5468 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5469 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5470 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5471 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5472 };
5473
5474 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5475
5476 enum ConstantValue ConstVal = Zero;
5477 if (Value.isUnsigned() || Value.isNonNegative()) {
5478 if (Value == 0) {
5479 LiteralOrBoolConstant =
5480 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5481 ConstVal = Zero;
5482 } else if (Value == 1) {
5483 LiteralOrBoolConstant =
5484 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5485 ConstVal = One;
5486 } else {
5487 LiteralOrBoolConstant = LiteralConstant;
5488 ConstVal = GT_One;
5489 }
5490 } else {
5491 ConstVal = LT_Zero;
5492 }
5493
5494 CompareBoolWithConstantResult CmpRes;
5495
5496 switch (op) {
5497 case BO_LT:
5498 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5499 break;
5500 case BO_GT:
5501 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5502 break;
5503 case BO_LE:
5504 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5505 break;
5506 case BO_GE:
5507 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5508 break;
5509 case BO_EQ:
5510 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5511 break;
5512 case BO_NE:
5513 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5514 break;
5515 default:
5516 CmpRes = Unkwn;
5517 break;
5518 }
5519
5520 if (CmpRes == AFals) {
5521 IsTrue = false;
5522 } else if (CmpRes == ATrue) {
5523 IsTrue = true;
5524 } else {
5525 return;
5526 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005527 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005528
5529 // If this is a comparison to an enum constant, include that
5530 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005531 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005532 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5533 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5534
5535 SmallString<64> PrettySourceValue;
5536 llvm::raw_svector_ostream OS(PrettySourceValue);
5537 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005538 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005539 else
5540 OS << Value;
5541
Richard Trieu0f097742014-04-04 04:13:47 +00005542 S.DiagRuntimeBehavior(
5543 E->getOperatorLoc(), E,
5544 S.PDiag(diag::warn_out_of_range_compare)
5545 << OS.str() << LiteralOrBoolConstant
5546 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5547 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005548}
5549
John McCallcc7e5bf2010-05-06 08:58:33 +00005550/// Analyze the operands of the given comparison. Implements the
5551/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005552static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005553 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5554 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005555}
John McCall263a48b2010-01-04 23:31:57 +00005556
John McCallca01b222010-01-04 23:21:16 +00005557/// \brief Implements -Wsign-compare.
5558///
Richard Trieu82402a02011-09-15 21:56:47 +00005559/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005560static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005561 // The type the comparison is being performed in.
5562 QualType T = E->getLHS()->getType();
5563 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5564 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005565 if (E->isValueDependent())
5566 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005567
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005568 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5569 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005570
5571 bool IsComparisonConstant = false;
5572
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005573 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005574 // of 'true' or 'false'.
5575 if (T->isIntegralType(S.Context)) {
5576 llvm::APSInt RHSValue;
5577 bool IsRHSIntegralLiteral =
5578 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5579 llvm::APSInt LHSValue;
5580 bool IsLHSIntegralLiteral =
5581 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5582 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5583 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5584 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5585 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5586 else
5587 IsComparisonConstant =
5588 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005589 } else if (!T->hasUnsignedIntegerRepresentation())
5590 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005591
John McCallcc7e5bf2010-05-06 08:58:33 +00005592 // We don't do anything special if this isn't an unsigned integral
5593 // comparison: we're only interested in integral comparisons, and
5594 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005595 //
5596 // We also don't care about value-dependent expressions or expressions
5597 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005598 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005599 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005600
John McCallcc7e5bf2010-05-06 08:58:33 +00005601 // Check to see if one of the (unmodified) operands is of different
5602 // signedness.
5603 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005604 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5605 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005606 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005607 signedOperand = LHS;
5608 unsignedOperand = RHS;
5609 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5610 signedOperand = RHS;
5611 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005612 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005613 CheckTrivialUnsignedComparison(S, E);
5614 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005615 }
5616
John McCallcc7e5bf2010-05-06 08:58:33 +00005617 // Otherwise, calculate the effective range of the signed operand.
5618 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005619
John McCallcc7e5bf2010-05-06 08:58:33 +00005620 // Go ahead and analyze implicit conversions in the operands. Note
5621 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005622 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5623 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005624
John McCallcc7e5bf2010-05-06 08:58:33 +00005625 // If the signed range is non-negative, -Wsign-compare won't fire,
5626 // but we should still check for comparisons which are always true
5627 // or false.
5628 if (signedRange.NonNegative)
5629 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005630
5631 // For (in)equality comparisons, if the unsigned operand is a
5632 // constant which cannot collide with a overflowed signed operand,
5633 // then reinterpreting the signed operand as unsigned will not
5634 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005635 if (E->isEqualityOp()) {
5636 unsigned comparisonWidth = S.Context.getIntWidth(T);
5637 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005638
John McCallcc7e5bf2010-05-06 08:58:33 +00005639 // We should never be unable to prove that the unsigned operand is
5640 // non-negative.
5641 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5642
5643 if (unsignedRange.Width < comparisonWidth)
5644 return;
5645 }
5646
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005647 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5648 S.PDiag(diag::warn_mixed_sign_comparison)
5649 << LHS->getType() << RHS->getType()
5650 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005651}
5652
John McCall1f425642010-11-11 03:21:53 +00005653/// Analyzes an attempt to assign the given value to a bitfield.
5654///
5655/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005656static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5657 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005658 assert(Bitfield->isBitField());
5659 if (Bitfield->isInvalidDecl())
5660 return false;
5661
John McCalldeebbcf2010-11-11 05:33:51 +00005662 // White-list bool bitfields.
5663 if (Bitfield->getType()->isBooleanType())
5664 return false;
5665
Douglas Gregor789adec2011-02-04 13:09:01 +00005666 // Ignore value- or type-dependent expressions.
5667 if (Bitfield->getBitWidth()->isValueDependent() ||
5668 Bitfield->getBitWidth()->isTypeDependent() ||
5669 Init->isValueDependent() ||
5670 Init->isTypeDependent())
5671 return false;
5672
John McCall1f425642010-11-11 03:21:53 +00005673 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5674
Richard Smith5fab0c92011-12-28 19:48:30 +00005675 llvm::APSInt Value;
5676 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005677 return false;
5678
John McCall1f425642010-11-11 03:21:53 +00005679 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005680 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005681
5682 if (OriginalWidth <= FieldWidth)
5683 return false;
5684
Eli Friedmanc267a322012-01-26 23:11:39 +00005685 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005686 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005687 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005688
Eli Friedmanc267a322012-01-26 23:11:39 +00005689 // Check whether the stored value is equal to the original value.
5690 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005691 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005692 return false;
5693
Eli Friedmanc267a322012-01-26 23:11:39 +00005694 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005695 // therefore don't strictly fit into a signed bitfield of width 1.
5696 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005697 return false;
5698
John McCall1f425642010-11-11 03:21:53 +00005699 std::string PrettyValue = Value.toString(10);
5700 std::string PrettyTrunc = TruncatedValue.toString(10);
5701
5702 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5703 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5704 << Init->getSourceRange();
5705
5706 return true;
5707}
5708
John McCalld2a53122010-11-09 23:24:47 +00005709/// Analyze the given simple or compound assignment for warning-worthy
5710/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005711static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005712 // Just recurse on the LHS.
5713 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5714
5715 // We want to recurse on the RHS as normal unless we're assigning to
5716 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005717 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005718 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005719 E->getOperatorLoc())) {
5720 // Recurse, ignoring any implicit conversions on the RHS.
5721 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5722 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005723 }
5724 }
5725
5726 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5727}
5728
John McCall263a48b2010-01-04 23:31:57 +00005729/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005730static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005731 SourceLocation CContext, unsigned diag,
5732 bool pruneControlFlow = false) {
5733 if (pruneControlFlow) {
5734 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5735 S.PDiag(diag)
5736 << SourceType << T << E->getSourceRange()
5737 << SourceRange(CContext));
5738 return;
5739 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005740 S.Diag(E->getExprLoc(), diag)
5741 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5742}
5743
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005744/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005745static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005746 SourceLocation CContext, unsigned diag,
5747 bool pruneControlFlow = false) {
5748 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005749}
5750
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005751/// Diagnose an implicit cast from a literal expression. Does not warn when the
5752/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005753void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5754 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005755 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005756 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005757 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005758 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5759 T->hasUnsignedIntegerRepresentation());
5760 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005761 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005762 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005763 return;
5764
Eli Friedman07185912013-08-29 23:44:43 +00005765 // FIXME: Force the precision of the source value down so we don't print
5766 // digits which are usually useless (we don't really care here if we
5767 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5768 // would automatically print the shortest representation, but it's a bit
5769 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005770 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005771 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5772 precision = (precision * 59 + 195) / 196;
5773 Value.toString(PrettySourceValue, precision);
5774
David Blaikie9b88cc02012-05-15 17:18:27 +00005775 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005776 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5777 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5778 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005779 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005780
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005781 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005782 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5783 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005784}
5785
John McCall18a2c2c2010-11-09 22:22:12 +00005786std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5787 if (!Range.Width) return "0";
5788
5789 llvm::APSInt ValueInRange = Value;
5790 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005791 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005792 return ValueInRange.toString(10);
5793}
5794
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005795static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5796 if (!isa<ImplicitCastExpr>(Ex))
5797 return false;
5798
5799 Expr *InnerE = Ex->IgnoreParenImpCasts();
5800 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5801 const Type *Source =
5802 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5803 if (Target->isDependentType())
5804 return false;
5805
5806 const BuiltinType *FloatCandidateBT =
5807 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5808 const Type *BoolCandidateType = ToBool ? Target : Source;
5809
5810 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5811 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5812}
5813
5814void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5815 SourceLocation CC) {
5816 unsigned NumArgs = TheCall->getNumArgs();
5817 for (unsigned i = 0; i < NumArgs; ++i) {
5818 Expr *CurrA = TheCall->getArg(i);
5819 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5820 continue;
5821
5822 bool IsSwapped = ((i > 0) &&
5823 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5824 IsSwapped |= ((i < (NumArgs - 1)) &&
5825 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5826 if (IsSwapped) {
5827 // Warn on this floating-point to bool conversion.
5828 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5829 CurrA->getType(), CC,
5830 diag::warn_impcast_floating_point_to_bool);
5831 }
5832 }
5833}
5834
John McCallcc7e5bf2010-05-06 08:58:33 +00005835void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00005836 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005837 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005838
John McCallcc7e5bf2010-05-06 08:58:33 +00005839 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5840 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5841 if (Source == Target) return;
5842 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005843
Chandler Carruthc22845a2011-07-26 05:40:03 +00005844 // If the conversion context location is invalid don't complain. We also
5845 // don't want to emit a warning if the issue occurs from the expansion of
5846 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5847 // delay this check as long as possible. Once we detect we are in that
5848 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005849 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005850 return;
5851
Richard Trieu021baa32011-09-23 20:10:00 +00005852 // Diagnose implicit casts to bool.
5853 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5854 if (isa<StringLiteral>(E))
5855 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005856 // and expressions, for instance, assert(0 && "error here"), are
5857 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005858 return DiagnoseImpCast(S, E, T, CC,
5859 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005860 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5861 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5862 // This covers the literal expressions that evaluate to Objective-C
5863 // objects.
5864 return DiagnoseImpCast(S, E, T, CC,
5865 diag::warn_impcast_objective_c_literal_to_bool);
5866 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005867 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5868 // Warn on pointer to bool conversion that is always true.
5869 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5870 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005871 }
Richard Trieu021baa32011-09-23 20:10:00 +00005872 }
John McCall263a48b2010-01-04 23:31:57 +00005873
5874 // Strip vector types.
5875 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005876 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005877 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005878 return;
John McCallacf0ee52010-10-08 02:01:28 +00005879 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005880 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005881
5882 // If the vector cast is cast between two vectors of the same size, it is
5883 // a bitcast, not a conversion.
5884 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5885 return;
John McCall263a48b2010-01-04 23:31:57 +00005886
5887 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5888 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5889 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00005890 if (auto VecTy = dyn_cast<VectorType>(Target))
5891 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00005892
5893 // Strip complex types.
5894 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005895 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005896 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005897 return;
5898
John McCallacf0ee52010-10-08 02:01:28 +00005899 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005900 }
John McCall263a48b2010-01-04 23:31:57 +00005901
5902 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5903 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5904 }
5905
5906 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5907 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5908
5909 // If the source is floating point...
5910 if (SourceBT && SourceBT->isFloatingPoint()) {
5911 // ...and the target is floating point...
5912 if (TargetBT && TargetBT->isFloatingPoint()) {
5913 // ...then warn if we're dropping FP rank.
5914
5915 // Builtin FP kinds are ordered by increasing FP rank.
5916 if (SourceBT->getKind() > TargetBT->getKind()) {
5917 // Don't warn about float constants that are precisely
5918 // representable in the target type.
5919 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005920 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005921 // Value might be a float, a float vector, or a float complex.
5922 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005923 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5924 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005925 return;
5926 }
5927
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005928 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005929 return;
5930
John McCallacf0ee52010-10-08 02:01:28 +00005931 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005932 }
5933 return;
5934 }
5935
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005936 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005937 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005938 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005939 return;
5940
Chandler Carruth22c7a792011-02-17 11:05:49 +00005941 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005942 // We also want to warn on, e.g., "int i = -1.234"
5943 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5944 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5945 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5946
Chandler Carruth016ef402011-04-10 08:36:24 +00005947 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5948 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005949 } else {
5950 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5951 }
5952 }
John McCall263a48b2010-01-04 23:31:57 +00005953
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005954 // If the target is bool, warn if expr is a function or method call.
5955 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5956 isa<CallExpr>(E)) {
5957 // Check last argument of function call to see if it is an
5958 // implicit cast from a type matching the type the result
5959 // is being cast to.
5960 CallExpr *CEx = cast<CallExpr>(E);
5961 unsigned NumArgs = CEx->getNumArgs();
5962 if (NumArgs > 0) {
5963 Expr *LastA = CEx->getArg(NumArgs - 1);
5964 Expr *InnerE = LastA->IgnoreParenImpCasts();
5965 const Type *InnerType =
5966 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5967 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5968 // Warn on this floating-point to bool conversion
5969 DiagnoseImpCast(S, E, T, CC,
5970 diag::warn_impcast_floating_point_to_bool);
5971 }
5972 }
5973 }
John McCall263a48b2010-01-04 23:31:57 +00005974 return;
5975 }
5976
Richard Trieubeaf3452011-05-29 19:59:02 +00005977 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005978 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005979 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005980 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005981 SourceLocation Loc = E->getSourceRange().getBegin();
5982 if (Loc.isMacroID())
5983 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005984 if (!Loc.isMacroID() || CC.isMacroID())
5985 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5986 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005987 << FixItHint::CreateReplacement(Loc,
5988 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005989 }
5990
David Blaikie9366d2b2012-06-19 21:19:06 +00005991 if (!Source->isIntegerType() || !Target->isIntegerType())
5992 return;
5993
David Blaikie7555b6a2012-05-15 16:56:36 +00005994 // TODO: remove this early return once the false positives for constant->bool
5995 // in templates, macros, etc, are reduced or removed.
5996 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5997 return;
5998
John McCallcc7e5bf2010-05-06 08:58:33 +00005999 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006000 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006001
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006002 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006003 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006004 // TODO: this should happen for bitfield stores, too.
6005 llvm::APSInt Value(32);
6006 if (E->isIntegerConstantExpr(Value, S.Context)) {
6007 if (S.SourceMgr.isInSystemMacro(CC))
6008 return;
6009
John McCall18a2c2c2010-11-09 22:22:12 +00006010 std::string PrettySourceValue = Value.toString(10);
6011 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006012
Ted Kremenek33ba9952011-10-22 02:37:33 +00006013 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6014 S.PDiag(diag::warn_impcast_integer_precision_constant)
6015 << PrettySourceValue << PrettyTargetValue
6016 << E->getType() << T << E->getSourceRange()
6017 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006018 return;
6019 }
6020
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006021 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6022 if (S.SourceMgr.isInSystemMacro(CC))
6023 return;
6024
David Blaikie9455da02012-04-12 22:40:54 +00006025 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006026 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6027 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006028 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006029 }
6030
6031 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6032 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6033 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006034
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006035 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006036 return;
6037
John McCallcc7e5bf2010-05-06 08:58:33 +00006038 unsigned DiagID = diag::warn_impcast_integer_sign;
6039
6040 // Traditionally, gcc has warned about this under -Wsign-compare.
6041 // We also want to warn about it in -Wconversion.
6042 // So if -Wconversion is off, use a completely identical diagnostic
6043 // in the sign-compare group.
6044 // The conditional-checking code will
6045 if (ICContext) {
6046 DiagID = diag::warn_impcast_integer_sign_conditional;
6047 *ICContext = true;
6048 }
6049
John McCallacf0ee52010-10-08 02:01:28 +00006050 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006051 }
6052
Douglas Gregora78f1932011-02-22 02:45:07 +00006053 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006054 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6055 // type, to give us better diagnostics.
6056 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006057 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006058 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6059 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6060 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6061 SourceType = S.Context.getTypeDeclType(Enum);
6062 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6063 }
6064 }
6065
Douglas Gregora78f1932011-02-22 02:45:07 +00006066 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6067 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006068 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6069 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006070 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006071 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006072 return;
6073
Douglas Gregor364f7db2011-03-12 00:14:31 +00006074 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006075 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006076 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006077
John McCall263a48b2010-01-04 23:31:57 +00006078 return;
6079}
6080
David Blaikie18e9ac72012-05-15 21:57:38 +00006081void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6082 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006083
6084void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006085 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006086 E = E->IgnoreParenImpCasts();
6087
6088 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006089 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006090
John McCallacf0ee52010-10-08 02:01:28 +00006091 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006092 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006093 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006094 return;
6095}
6096
David Blaikie18e9ac72012-05-15 21:57:38 +00006097void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6098 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00006099 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006100
6101 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006102 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6103 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006104
6105 // If -Wconversion would have warned about either of the candidates
6106 // for a signedness conversion to the context type...
6107 if (!Suspicious) return;
6108
6109 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006110 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006111 return;
6112
John McCallcc7e5bf2010-05-06 08:58:33 +00006113 // ...then check whether it would have warned about either of the
6114 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006115 if (E->getType() == T) return;
6116
6117 Suspicious = false;
6118 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6119 E->getType(), CC, &Suspicious);
6120 if (!Suspicious)
6121 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006122 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006123}
6124
6125/// AnalyzeImplicitConversions - Find and report any interesting
6126/// implicit conversions in the given expression. There are a couple
6127/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006128void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006129 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006130 Expr *E = OrigE->IgnoreParenImpCasts();
6131
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006132 if (E->isTypeDependent() || E->isValueDependent())
6133 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006134
John McCallcc7e5bf2010-05-06 08:58:33 +00006135 // For conditional operators, we analyze the arguments as if they
6136 // were being fed directly into the output.
6137 if (isa<ConditionalOperator>(E)) {
6138 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006139 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006140 return;
6141 }
6142
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006143 // Check implicit argument conversions for function calls.
6144 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6145 CheckImplicitArgumentConversions(S, Call, CC);
6146
John McCallcc7e5bf2010-05-06 08:58:33 +00006147 // Go ahead and check any implicit conversions we might have skipped.
6148 // The non-canonical typecheck is just an optimization;
6149 // CheckImplicitConversion will filter out dead implicit conversions.
6150 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006151 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006152
6153 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006154
6155 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006156 if (POE->getResultExpr())
6157 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006158 }
6159
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006160 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6161 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6162
John McCallcc7e5bf2010-05-06 08:58:33 +00006163 // Skip past explicit casts.
6164 if (isa<ExplicitCastExpr>(E)) {
6165 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006166 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006167 }
6168
John McCalld2a53122010-11-09 23:24:47 +00006169 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6170 // Do a somewhat different check with comparison operators.
6171 if (BO->isComparisonOp())
6172 return AnalyzeComparison(S, BO);
6173
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006174 // And with simple assignments.
6175 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006176 return AnalyzeAssignment(S, BO);
6177 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006178
6179 // These break the otherwise-useful invariant below. Fortunately,
6180 // we don't really need to recurse into them, because any internal
6181 // expressions should have been analyzed already when they were
6182 // built into statements.
6183 if (isa<StmtExpr>(E)) return;
6184
6185 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006186 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006187
6188 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006189 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006190 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006191 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006192 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006193 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006194 if (!ChildExpr)
6195 continue;
6196
Richard Trieu955231d2014-01-25 01:10:35 +00006197 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006198 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006199 // Ignore checking string literals that are in logical and operators.
6200 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006201 continue;
6202 AnalyzeImplicitConversions(S, ChildExpr, CC);
6203 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006204}
6205
6206} // end anonymous namespace
6207
Richard Trieu3bb8b562014-02-26 02:36:06 +00006208enum {
6209 AddressOf,
6210 FunctionPointer,
6211 ArrayPointer
6212};
6213
Richard Trieuc1888e02014-06-28 23:25:37 +00006214// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6215// Returns true when emitting a warning about taking the address of a reference.
6216static bool CheckForReference(Sema &SemaRef, const Expr *E,
6217 PartialDiagnostic PD) {
6218 E = E->IgnoreParenImpCasts();
6219
6220 const FunctionDecl *FD = nullptr;
6221
6222 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6223 if (!DRE->getDecl()->getType()->isReferenceType())
6224 return false;
6225 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6226 if (!M->getMemberDecl()->getType()->isReferenceType())
6227 return false;
6228 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6229 if (!Call->getCallReturnType()->isReferenceType())
6230 return false;
6231 FD = Call->getDirectCallee();
6232 } else {
6233 return false;
6234 }
6235
6236 SemaRef.Diag(E->getExprLoc(), PD);
6237
6238 // If possible, point to location of function.
6239 if (FD) {
6240 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6241 }
6242
6243 return true;
6244}
6245
Richard Trieu3bb8b562014-02-26 02:36:06 +00006246/// \brief Diagnose pointers that are always non-null.
6247/// \param E the expression containing the pointer
6248/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6249/// compared to a null pointer
6250/// \param IsEqual True when the comparison is equal to a null pointer
6251/// \param Range Extra SourceRange to highlight in the diagnostic
6252void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6253 Expr::NullPointerConstantKind NullKind,
6254 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006255 if (!E)
6256 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006257
6258 // Don't warn inside macros.
6259 if (E->getExprLoc().isMacroID())
6260 return;
6261 E = E->IgnoreImpCasts();
6262
6263 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6264
Richard Trieuf7432752014-06-06 21:39:26 +00006265 if (isa<CXXThisExpr>(E)) {
6266 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6267 : diag::warn_this_bool_conversion;
6268 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6269 return;
6270 }
6271
Richard Trieu3bb8b562014-02-26 02:36:06 +00006272 bool IsAddressOf = false;
6273
6274 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6275 if (UO->getOpcode() != UO_AddrOf)
6276 return;
6277 IsAddressOf = true;
6278 E = UO->getSubExpr();
6279 }
6280
Richard Trieuc1888e02014-06-28 23:25:37 +00006281 if (IsAddressOf) {
6282 unsigned DiagID = IsCompare
6283 ? diag::warn_address_of_reference_null_compare
6284 : diag::warn_address_of_reference_bool_conversion;
6285 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6286 << IsEqual;
6287 if (CheckForReference(*this, E, PD)) {
6288 return;
6289 }
6290 }
6291
Richard Trieu3bb8b562014-02-26 02:36:06 +00006292 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006293 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006294 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6295 D = R->getDecl();
6296 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6297 D = M->getMemberDecl();
6298 }
6299
6300 // Weak Decls can be null.
6301 if (!D || D->isWeak())
6302 return;
6303
6304 QualType T = D->getType();
6305 const bool IsArray = T->isArrayType();
6306 const bool IsFunction = T->isFunctionType();
6307
Richard Trieuc1888e02014-06-28 23:25:37 +00006308 // Address of function is used to silence the function warning.
6309 if (IsAddressOf && IsFunction) {
6310 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006311 }
6312
6313 // Found nothing.
6314 if (!IsAddressOf && !IsFunction && !IsArray)
6315 return;
6316
6317 // Pretty print the expression for the diagnostic.
6318 std::string Str;
6319 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006320 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006321
6322 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6323 : diag::warn_impcast_pointer_to_bool;
6324 unsigned DiagType;
6325 if (IsAddressOf)
6326 DiagType = AddressOf;
6327 else if (IsFunction)
6328 DiagType = FunctionPointer;
6329 else if (IsArray)
6330 DiagType = ArrayPointer;
6331 else
6332 llvm_unreachable("Could not determine diagnostic.");
6333 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6334 << Range << IsEqual;
6335
6336 if (!IsFunction)
6337 return;
6338
6339 // Suggest '&' to silence the function warning.
6340 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6341 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6342
6343 // Check to see if '()' fixit should be emitted.
6344 QualType ReturnType;
6345 UnresolvedSet<4> NonTemplateOverloads;
6346 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6347 if (ReturnType.isNull())
6348 return;
6349
6350 if (IsCompare) {
6351 // There are two cases here. If there is null constant, the only suggest
6352 // for a pointer return type. If the null is 0, then suggest if the return
6353 // type is a pointer or an integer type.
6354 if (!ReturnType->isPointerType()) {
6355 if (NullKind == Expr::NPCK_ZeroExpression ||
6356 NullKind == Expr::NPCK_ZeroLiteral) {
6357 if (!ReturnType->isIntegerType())
6358 return;
6359 } else {
6360 return;
6361 }
6362 }
6363 } else { // !IsCompare
6364 // For function to bool, only suggest if the function pointer has bool
6365 // return type.
6366 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6367 return;
6368 }
6369 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006370 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006371}
6372
6373
John McCallcc7e5bf2010-05-06 08:58:33 +00006374/// Diagnoses "dangerous" implicit conversions within the given
6375/// expression (which is a full expression). Implements -Wconversion
6376/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006377///
6378/// \param CC the "context" location of the implicit conversion, i.e.
6379/// the most location of the syntactic entity requiring the implicit
6380/// conversion
6381void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006382 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006383 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006384 return;
6385
6386 // Don't diagnose for value- or type-dependent expressions.
6387 if (E->isTypeDependent() || E->isValueDependent())
6388 return;
6389
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006390 // Check for array bounds violations in cases where the check isn't triggered
6391 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6392 // ArraySubscriptExpr is on the RHS of a variable initialization.
6393 CheckArrayAccess(E);
6394
John McCallacf0ee52010-10-08 02:01:28 +00006395 // This is not the right CC for (e.g.) a variable initialization.
6396 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006397}
6398
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006399/// Diagnose when expression is an integer constant expression and its evaluation
6400/// results in integer overflow
6401void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006402 if (isa<BinaryOperator>(E->IgnoreParens()))
6403 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006404}
6405
Richard Smithc406cb72013-01-17 01:17:56 +00006406namespace {
6407/// \brief Visitor for expressions which looks for unsequenced operations on the
6408/// same object.
6409class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006410 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6411
Richard Smithc406cb72013-01-17 01:17:56 +00006412 /// \brief A tree of sequenced regions within an expression. Two regions are
6413 /// unsequenced if one is an ancestor or a descendent of the other. When we
6414 /// finish processing an expression with sequencing, such as a comma
6415 /// expression, we fold its tree nodes into its parent, since they are
6416 /// unsequenced with respect to nodes we will visit later.
6417 class SequenceTree {
6418 struct Value {
6419 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6420 unsigned Parent : 31;
6421 bool Merged : 1;
6422 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006423 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006424
6425 public:
6426 /// \brief A region within an expression which may be sequenced with respect
6427 /// to some other region.
6428 class Seq {
6429 explicit Seq(unsigned N) : Index(N) {}
6430 unsigned Index;
6431 friend class SequenceTree;
6432 public:
6433 Seq() : Index(0) {}
6434 };
6435
6436 SequenceTree() { Values.push_back(Value(0)); }
6437 Seq root() const { return Seq(0); }
6438
6439 /// \brief Create a new sequence of operations, which is an unsequenced
6440 /// subset of \p Parent. This sequence of operations is sequenced with
6441 /// respect to other children of \p Parent.
6442 Seq allocate(Seq Parent) {
6443 Values.push_back(Value(Parent.Index));
6444 return Seq(Values.size() - 1);
6445 }
6446
6447 /// \brief Merge a sequence of operations into its parent.
6448 void merge(Seq S) {
6449 Values[S.Index].Merged = true;
6450 }
6451
6452 /// \brief Determine whether two operations are unsequenced. This operation
6453 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6454 /// should have been merged into its parent as appropriate.
6455 bool isUnsequenced(Seq Cur, Seq Old) {
6456 unsigned C = representative(Cur.Index);
6457 unsigned Target = representative(Old.Index);
6458 while (C >= Target) {
6459 if (C == Target)
6460 return true;
6461 C = Values[C].Parent;
6462 }
6463 return false;
6464 }
6465
6466 private:
6467 /// \brief Pick a representative for a sequence.
6468 unsigned representative(unsigned K) {
6469 if (Values[K].Merged)
6470 // Perform path compression as we go.
6471 return Values[K].Parent = representative(Values[K].Parent);
6472 return K;
6473 }
6474 };
6475
6476 /// An object for which we can track unsequenced uses.
6477 typedef NamedDecl *Object;
6478
6479 /// Different flavors of object usage which we track. We only track the
6480 /// least-sequenced usage of each kind.
6481 enum UsageKind {
6482 /// A read of an object. Multiple unsequenced reads are OK.
6483 UK_Use,
6484 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006485 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006486 UK_ModAsValue,
6487 /// A modification of an object which is not sequenced before the value
6488 /// computation of the expression, such as n++.
6489 UK_ModAsSideEffect,
6490
6491 UK_Count = UK_ModAsSideEffect + 1
6492 };
6493
6494 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006495 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006496 Expr *Use;
6497 SequenceTree::Seq Seq;
6498 };
6499
6500 struct UsageInfo {
6501 UsageInfo() : Diagnosed(false) {}
6502 Usage Uses[UK_Count];
6503 /// Have we issued a diagnostic for this variable already?
6504 bool Diagnosed;
6505 };
6506 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6507
6508 Sema &SemaRef;
6509 /// Sequenced regions within the expression.
6510 SequenceTree Tree;
6511 /// Declaration modifications and references which we have seen.
6512 UsageInfoMap UsageMap;
6513 /// The region we are currently within.
6514 SequenceTree::Seq Region;
6515 /// Filled in with declarations which were modified as a side-effect
6516 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006517 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006518 /// Expressions to check later. We defer checking these to reduce
6519 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006520 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006521
6522 /// RAII object wrapping the visitation of a sequenced subexpression of an
6523 /// expression. At the end of this process, the side-effects of the evaluation
6524 /// become sequenced with respect to the value computation of the result, so
6525 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6526 /// UK_ModAsValue.
6527 struct SequencedSubexpression {
6528 SequencedSubexpression(SequenceChecker &Self)
6529 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6530 Self.ModAsSideEffect = &ModAsSideEffect;
6531 }
6532 ~SequencedSubexpression() {
6533 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6534 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6535 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6536 Self.addUsage(U, ModAsSideEffect[I].first,
6537 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6538 }
6539 Self.ModAsSideEffect = OldModAsSideEffect;
6540 }
6541
6542 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006543 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6544 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006545 };
6546
Richard Smith40238f02013-06-20 22:21:56 +00006547 /// RAII object wrapping the visitation of a subexpression which we might
6548 /// choose to evaluate as a constant. If any subexpression is evaluated and
6549 /// found to be non-constant, this allows us to suppress the evaluation of
6550 /// the outer expression.
6551 class EvaluationTracker {
6552 public:
6553 EvaluationTracker(SequenceChecker &Self)
6554 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6555 Self.EvalTracker = this;
6556 }
6557 ~EvaluationTracker() {
6558 Self.EvalTracker = Prev;
6559 if (Prev)
6560 Prev->EvalOK &= EvalOK;
6561 }
6562
6563 bool evaluate(const Expr *E, bool &Result) {
6564 if (!EvalOK || E->isValueDependent())
6565 return false;
6566 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6567 return EvalOK;
6568 }
6569
6570 private:
6571 SequenceChecker &Self;
6572 EvaluationTracker *Prev;
6573 bool EvalOK;
6574 } *EvalTracker;
6575
Richard Smithc406cb72013-01-17 01:17:56 +00006576 /// \brief Find the object which is produced by the specified expression,
6577 /// if any.
6578 Object getObject(Expr *E, bool Mod) const {
6579 E = E->IgnoreParenCasts();
6580 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6581 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6582 return getObject(UO->getSubExpr(), Mod);
6583 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6584 if (BO->getOpcode() == BO_Comma)
6585 return getObject(BO->getRHS(), Mod);
6586 if (Mod && BO->isAssignmentOp())
6587 return getObject(BO->getLHS(), Mod);
6588 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6589 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6590 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6591 return ME->getMemberDecl();
6592 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6593 // FIXME: If this is a reference, map through to its value.
6594 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006595 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006596 }
6597
6598 /// \brief Note that an object was modified or used by an expression.
6599 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6600 Usage &U = UI.Uses[UK];
6601 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6602 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6603 ModAsSideEffect->push_back(std::make_pair(O, U));
6604 U.Use = Ref;
6605 U.Seq = Region;
6606 }
6607 }
6608 /// \brief Check whether a modification or use conflicts with a prior usage.
6609 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6610 bool IsModMod) {
6611 if (UI.Diagnosed)
6612 return;
6613
6614 const Usage &U = UI.Uses[OtherKind];
6615 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6616 return;
6617
6618 Expr *Mod = U.Use;
6619 Expr *ModOrUse = Ref;
6620 if (OtherKind == UK_Use)
6621 std::swap(Mod, ModOrUse);
6622
6623 SemaRef.Diag(Mod->getExprLoc(),
6624 IsModMod ? diag::warn_unsequenced_mod_mod
6625 : diag::warn_unsequenced_mod_use)
6626 << O << SourceRange(ModOrUse->getExprLoc());
6627 UI.Diagnosed = true;
6628 }
6629
6630 void notePreUse(Object O, Expr *Use) {
6631 UsageInfo &U = UsageMap[O];
6632 // Uses conflict with other modifications.
6633 checkUsage(O, U, Use, UK_ModAsValue, false);
6634 }
6635 void notePostUse(Object O, Expr *Use) {
6636 UsageInfo &U = UsageMap[O];
6637 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6638 addUsage(U, O, Use, UK_Use);
6639 }
6640
6641 void notePreMod(Object O, Expr *Mod) {
6642 UsageInfo &U = UsageMap[O];
6643 // Modifications conflict with other modifications and with uses.
6644 checkUsage(O, U, Mod, UK_ModAsValue, true);
6645 checkUsage(O, U, Mod, UK_Use, false);
6646 }
6647 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6648 UsageInfo &U = UsageMap[O];
6649 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6650 addUsage(U, O, Use, UK);
6651 }
6652
6653public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006654 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006655 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6656 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006657 Visit(E);
6658 }
6659
6660 void VisitStmt(Stmt *S) {
6661 // Skip all statements which aren't expressions for now.
6662 }
6663
6664 void VisitExpr(Expr *E) {
6665 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006666 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006667 }
6668
6669 void VisitCastExpr(CastExpr *E) {
6670 Object O = Object();
6671 if (E->getCastKind() == CK_LValueToRValue)
6672 O = getObject(E->getSubExpr(), false);
6673
6674 if (O)
6675 notePreUse(O, E);
6676 VisitExpr(E);
6677 if (O)
6678 notePostUse(O, E);
6679 }
6680
6681 void VisitBinComma(BinaryOperator *BO) {
6682 // C++11 [expr.comma]p1:
6683 // Every value computation and side effect associated with the left
6684 // expression is sequenced before every value computation and side
6685 // effect associated with the right expression.
6686 SequenceTree::Seq LHS = Tree.allocate(Region);
6687 SequenceTree::Seq RHS = Tree.allocate(Region);
6688 SequenceTree::Seq OldRegion = Region;
6689
6690 {
6691 SequencedSubexpression SeqLHS(*this);
6692 Region = LHS;
6693 Visit(BO->getLHS());
6694 }
6695
6696 Region = RHS;
6697 Visit(BO->getRHS());
6698
6699 Region = OldRegion;
6700
6701 // Forget that LHS and RHS are sequenced. They are both unsequenced
6702 // with respect to other stuff.
6703 Tree.merge(LHS);
6704 Tree.merge(RHS);
6705 }
6706
6707 void VisitBinAssign(BinaryOperator *BO) {
6708 // The modification is sequenced after the value computation of the LHS
6709 // and RHS, so check it before inspecting the operands and update the
6710 // map afterwards.
6711 Object O = getObject(BO->getLHS(), true);
6712 if (!O)
6713 return VisitExpr(BO);
6714
6715 notePreMod(O, BO);
6716
6717 // C++11 [expr.ass]p7:
6718 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6719 // only once.
6720 //
6721 // Therefore, for a compound assignment operator, O is considered used
6722 // everywhere except within the evaluation of E1 itself.
6723 if (isa<CompoundAssignOperator>(BO))
6724 notePreUse(O, BO);
6725
6726 Visit(BO->getLHS());
6727
6728 if (isa<CompoundAssignOperator>(BO))
6729 notePostUse(O, BO);
6730
6731 Visit(BO->getRHS());
6732
Richard Smith83e37bee2013-06-26 23:16:51 +00006733 // C++11 [expr.ass]p1:
6734 // the assignment is sequenced [...] before the value computation of the
6735 // assignment expression.
6736 // C11 6.5.16/3 has no such rule.
6737 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6738 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006739 }
6740 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6741 VisitBinAssign(CAO);
6742 }
6743
6744 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6745 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6746 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6747 Object O = getObject(UO->getSubExpr(), true);
6748 if (!O)
6749 return VisitExpr(UO);
6750
6751 notePreMod(O, UO);
6752 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006753 // C++11 [expr.pre.incr]p1:
6754 // the expression ++x is equivalent to x+=1
6755 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6756 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006757 }
6758
6759 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6760 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6761 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6762 Object O = getObject(UO->getSubExpr(), true);
6763 if (!O)
6764 return VisitExpr(UO);
6765
6766 notePreMod(O, UO);
6767 Visit(UO->getSubExpr());
6768 notePostMod(O, UO, UK_ModAsSideEffect);
6769 }
6770
6771 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6772 void VisitBinLOr(BinaryOperator *BO) {
6773 // The side-effects of the LHS of an '&&' are sequenced before the
6774 // value computation of the RHS, and hence before the value computation
6775 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6776 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006777 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006778 {
6779 SequencedSubexpression Sequenced(*this);
6780 Visit(BO->getLHS());
6781 }
6782
6783 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006784 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006785 if (!Result)
6786 Visit(BO->getRHS());
6787 } else {
6788 // Check for unsequenced operations in the RHS, treating it as an
6789 // entirely separate evaluation.
6790 //
6791 // FIXME: If there are operations in the RHS which are unsequenced
6792 // with respect to operations outside the RHS, and those operations
6793 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006794 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006795 }
Richard Smithc406cb72013-01-17 01:17:56 +00006796 }
6797 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006798 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006799 {
6800 SequencedSubexpression Sequenced(*this);
6801 Visit(BO->getLHS());
6802 }
6803
6804 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006805 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006806 if (Result)
6807 Visit(BO->getRHS());
6808 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006809 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006810 }
Richard Smithc406cb72013-01-17 01:17:56 +00006811 }
6812
6813 // Only visit the condition, unless we can be sure which subexpression will
6814 // be chosen.
6815 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006816 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006817 {
6818 SequencedSubexpression Sequenced(*this);
6819 Visit(CO->getCond());
6820 }
Richard Smithc406cb72013-01-17 01:17:56 +00006821
6822 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006823 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006824 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006825 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006826 WorkList.push_back(CO->getTrueExpr());
6827 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006828 }
Richard Smithc406cb72013-01-17 01:17:56 +00006829 }
6830
Richard Smithe3dbfe02013-06-30 10:40:20 +00006831 void VisitCallExpr(CallExpr *CE) {
6832 // C++11 [intro.execution]p15:
6833 // When calling a function [...], every value computation and side effect
6834 // associated with any argument expression, or with the postfix expression
6835 // designating the called function, is sequenced before execution of every
6836 // expression or statement in the body of the function [and thus before
6837 // the value computation of its result].
6838 SequencedSubexpression Sequenced(*this);
6839 Base::VisitCallExpr(CE);
6840
6841 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6842 }
6843
Richard Smithc406cb72013-01-17 01:17:56 +00006844 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006845 // This is a call, so all subexpressions are sequenced before the result.
6846 SequencedSubexpression Sequenced(*this);
6847
Richard Smithc406cb72013-01-17 01:17:56 +00006848 if (!CCE->isListInitialization())
6849 return VisitExpr(CCE);
6850
6851 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006852 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006853 SequenceTree::Seq Parent = Region;
6854 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6855 E = CCE->arg_end();
6856 I != E; ++I) {
6857 Region = Tree.allocate(Parent);
6858 Elts.push_back(Region);
6859 Visit(*I);
6860 }
6861
6862 // Forget that the initializers are sequenced.
6863 Region = Parent;
6864 for (unsigned I = 0; I < Elts.size(); ++I)
6865 Tree.merge(Elts[I]);
6866 }
6867
6868 void VisitInitListExpr(InitListExpr *ILE) {
6869 if (!SemaRef.getLangOpts().CPlusPlus11)
6870 return VisitExpr(ILE);
6871
6872 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006873 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006874 SequenceTree::Seq Parent = Region;
6875 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6876 Expr *E = ILE->getInit(I);
6877 if (!E) continue;
6878 Region = Tree.allocate(Parent);
6879 Elts.push_back(Region);
6880 Visit(E);
6881 }
6882
6883 // Forget that the initializers are sequenced.
6884 Region = Parent;
6885 for (unsigned I = 0; I < Elts.size(); ++I)
6886 Tree.merge(Elts[I]);
6887 }
6888};
6889}
6890
6891void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006892 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006893 WorkList.push_back(E);
6894 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006895 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006896 SequenceChecker(*this, Item, WorkList);
6897 }
Richard Smithc406cb72013-01-17 01:17:56 +00006898}
6899
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006900void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6901 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006902 CheckImplicitConversions(E, CheckLoc);
6903 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006904 if (!IsConstexpr && !E->isValueDependent())
6905 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006906}
6907
John McCall1f425642010-11-11 03:21:53 +00006908void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6909 FieldDecl *BitField,
6910 Expr *Init) {
6911 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6912}
6913
Mike Stump0c2ec772010-01-21 03:59:47 +00006914/// CheckParmsForFunctionDef - Check that the parameters of the given
6915/// function are appropriate for the definition of a function. This
6916/// takes care of any checks that cannot be performed on the
6917/// declaration itself, e.g., that the types of each of the function
6918/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006919bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6920 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006921 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006922 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006923 for (; P != PEnd; ++P) {
6924 ParmVarDecl *Param = *P;
6925
Mike Stump0c2ec772010-01-21 03:59:47 +00006926 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6927 // function declarator that is part of a function definition of
6928 // that function shall not have incomplete type.
6929 //
6930 // This is also C++ [dcl.fct]p6.
6931 if (!Param->isInvalidDecl() &&
6932 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006933 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006934 Param->setInvalidDecl();
6935 HasInvalidParm = true;
6936 }
6937
6938 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6939 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006940 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00006941 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006942 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006943 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006944 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006945
6946 // C99 6.7.5.3p12:
6947 // If the function declarator is not part of a definition of that
6948 // function, parameters may have incomplete type and may use the [*]
6949 // notation in their sequences of declarator specifiers to specify
6950 // variable length array types.
6951 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006952 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006953 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006954 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006955 // information is added for it.
6956 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006957 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006958 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006959 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006960 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006961
6962 // MSVC destroys objects passed by value in the callee. Therefore a
6963 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006964 // object's destructor. However, we don't perform any direct access check
6965 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006966 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6967 .getCXXABI()
6968 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006969 if (!Param->isInvalidDecl()) {
6970 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6971 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6972 if (!ClassDecl->isInvalidDecl() &&
6973 !ClassDecl->hasIrrelevantDestructor() &&
6974 !ClassDecl->isDependentContext()) {
6975 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6976 MarkFunctionReferenced(Param->getLocation(), Destructor);
6977 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6978 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006979 }
6980 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006981 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006982 }
6983
6984 return HasInvalidParm;
6985}
John McCall2b5c1b22010-08-12 21:44:57 +00006986
6987/// CheckCastAlign - Implements -Wcast-align, which warns when a
6988/// pointer cast increases the alignment requirements.
6989void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6990 // This is actually a lot of work to potentially be doing on every
6991 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006992 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00006993 return;
6994
6995 // Ignore dependent types.
6996 if (T->isDependentType() || Op->getType()->isDependentType())
6997 return;
6998
6999 // Require that the destination be a pointer type.
7000 const PointerType *DestPtr = T->getAs<PointerType>();
7001 if (!DestPtr) return;
7002
7003 // If the destination has alignment 1, we're done.
7004 QualType DestPointee = DestPtr->getPointeeType();
7005 if (DestPointee->isIncompleteType()) return;
7006 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7007 if (DestAlign.isOne()) return;
7008
7009 // Require that the source be a pointer type.
7010 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7011 if (!SrcPtr) return;
7012 QualType SrcPointee = SrcPtr->getPointeeType();
7013
7014 // Whitelist casts from cv void*. We already implicitly
7015 // whitelisted casts to cv void*, since they have alignment 1.
7016 // Also whitelist casts involving incomplete types, which implicitly
7017 // includes 'void'.
7018 if (SrcPointee->isIncompleteType()) return;
7019
7020 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7021 if (SrcAlign >= DestAlign) return;
7022
7023 Diag(TRange.getBegin(), diag::warn_cast_align)
7024 << Op->getType() << T
7025 << static_cast<unsigned>(SrcAlign.getQuantity())
7026 << static_cast<unsigned>(DestAlign.getQuantity())
7027 << TRange << Op->getSourceRange();
7028}
7029
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007030static const Type* getElementType(const Expr *BaseExpr) {
7031 const Type* EltType = BaseExpr->getType().getTypePtr();
7032 if (EltType->isAnyPointerType())
7033 return EltType->getPointeeType().getTypePtr();
7034 else if (EltType->isArrayType())
7035 return EltType->getBaseElementTypeUnsafe();
7036 return EltType;
7037}
7038
Chandler Carruth28389f02011-08-05 09:10:50 +00007039/// \brief Check whether this array fits the idiom of a size-one tail padded
7040/// array member of a struct.
7041///
7042/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7043/// commonly used to emulate flexible arrays in C89 code.
7044static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7045 const NamedDecl *ND) {
7046 if (Size != 1 || !ND) return false;
7047
7048 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7049 if (!FD) return false;
7050
7051 // Don't consider sizes resulting from macro expansions or template argument
7052 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007053
7054 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007055 while (TInfo) {
7056 TypeLoc TL = TInfo->getTypeLoc();
7057 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007058 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7059 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007060 TInfo = TDL->getTypeSourceInfo();
7061 continue;
7062 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007063 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7064 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007065 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7066 return false;
7067 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007068 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007069 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007070
7071 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007072 if (!RD) return false;
7073 if (RD->isUnion()) return false;
7074 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7075 if (!CRD->isStandardLayout()) return false;
7076 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007077
Benjamin Kramer8c543672011-08-06 03:04:42 +00007078 // See if this is the last field decl in the record.
7079 const Decl *D = FD;
7080 while ((D = D->getNextDeclInContext()))
7081 if (isa<FieldDecl>(D))
7082 return false;
7083 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007084}
7085
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007086void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007087 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007088 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007089 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007090 if (IndexExpr->isValueDependent())
7091 return;
7092
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007093 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007094 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007095 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007096 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007097 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007098 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007099
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007100 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007101 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007102 return;
Richard Smith13f67182011-12-16 19:31:14 +00007103 if (IndexNegated)
7104 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007105
Craig Topperc3ec1492014-05-26 06:22:03 +00007106 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007107 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7108 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007109 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007110 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007111
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007112 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007113 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007114 if (!size.isStrictlyPositive())
7115 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007116
7117 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007118 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007119 // Make sure we're comparing apples to apples when comparing index to size
7120 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7121 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007122 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007123 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007124 if (ptrarith_typesize != array_typesize) {
7125 // There's a cast to a different size type involved
7126 uint64_t ratio = array_typesize / ptrarith_typesize;
7127 // TODO: Be smarter about handling cases where array_typesize is not a
7128 // multiple of ptrarith_typesize
7129 if (ptrarith_typesize * ratio == array_typesize)
7130 size *= llvm::APInt(size.getBitWidth(), ratio);
7131 }
7132 }
7133
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007134 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007135 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007136 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007137 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007138
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007139 // For array subscripting the index must be less than size, but for pointer
7140 // arithmetic also allow the index (offset) to be equal to size since
7141 // computing the next address after the end of the array is legal and
7142 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007143 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007144 return;
7145
7146 // Also don't warn for arrays of size 1 which are members of some
7147 // structure. These are often used to approximate flexible arrays in C89
7148 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007149 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007150 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007151
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007152 // Suppress the warning if the subscript expression (as identified by the
7153 // ']' location) and the index expression are both from macro expansions
7154 // within a system header.
7155 if (ASE) {
7156 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7157 ASE->getRBracketLoc());
7158 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7159 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7160 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007161 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007162 return;
7163 }
7164 }
7165
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007166 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007167 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007168 DiagID = diag::warn_array_index_exceeds_bounds;
7169
7170 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7171 PDiag(DiagID) << index.toString(10, true)
7172 << size.toString(10, true)
7173 << (unsigned)size.getLimitedValue(~0U)
7174 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007175 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007176 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007177 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007178 DiagID = diag::warn_ptr_arith_precedes_bounds;
7179 if (index.isNegative()) index = -index;
7180 }
7181
7182 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7183 PDiag(DiagID) << index.toString(10, true)
7184 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007185 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007186
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007187 if (!ND) {
7188 // Try harder to find a NamedDecl to point at in the note.
7189 while (const ArraySubscriptExpr *ASE =
7190 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7191 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7192 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7193 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7194 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7195 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7196 }
7197
Chandler Carruth1af88f12011-02-17 21:10:52 +00007198 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007199 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7200 PDiag(diag::note_array_index_out_of_bounds)
7201 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007202}
7203
Ted Kremenekdf26df72011-03-01 18:41:00 +00007204void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007205 int AllowOnePastEnd = 0;
7206 while (expr) {
7207 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007208 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007209 case Stmt::ArraySubscriptExprClass: {
7210 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007211 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007212 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007213 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007214 }
7215 case Stmt::UnaryOperatorClass: {
7216 // Only unwrap the * and & unary operators
7217 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7218 expr = UO->getSubExpr();
7219 switch (UO->getOpcode()) {
7220 case UO_AddrOf:
7221 AllowOnePastEnd++;
7222 break;
7223 case UO_Deref:
7224 AllowOnePastEnd--;
7225 break;
7226 default:
7227 return;
7228 }
7229 break;
7230 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007231 case Stmt::ConditionalOperatorClass: {
7232 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7233 if (const Expr *lhs = cond->getLHS())
7234 CheckArrayAccess(lhs);
7235 if (const Expr *rhs = cond->getRHS())
7236 CheckArrayAccess(rhs);
7237 return;
7238 }
7239 default:
7240 return;
7241 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007242 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007243}
John McCall31168b02011-06-15 23:02:42 +00007244
7245//===--- CHECK: Objective-C retain cycles ----------------------------------//
7246
7247namespace {
7248 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007249 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007250 VarDecl *Variable;
7251 SourceRange Range;
7252 SourceLocation Loc;
7253 bool Indirect;
7254
7255 void setLocsFrom(Expr *e) {
7256 Loc = e->getExprLoc();
7257 Range = e->getSourceRange();
7258 }
7259 };
7260}
7261
7262/// Consider whether capturing the given variable can possibly lead to
7263/// a retain cycle.
7264static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007265 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007266 // lifetime. In MRR, it's captured strongly if the variable is
7267 // __block and has an appropriate type.
7268 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7269 return false;
7270
7271 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007272 if (ref)
7273 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007274 return true;
7275}
7276
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007277static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007278 while (true) {
7279 e = e->IgnoreParens();
7280 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7281 switch (cast->getCastKind()) {
7282 case CK_BitCast:
7283 case CK_LValueBitCast:
7284 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007285 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007286 e = cast->getSubExpr();
7287 continue;
7288
John McCall31168b02011-06-15 23:02:42 +00007289 default:
7290 return false;
7291 }
7292 }
7293
7294 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7295 ObjCIvarDecl *ivar = ref->getDecl();
7296 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7297 return false;
7298
7299 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007300 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007301 return false;
7302
7303 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7304 owner.Indirect = true;
7305 return true;
7306 }
7307
7308 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7309 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7310 if (!var) return false;
7311 return considerVariable(var, ref, owner);
7312 }
7313
John McCall31168b02011-06-15 23:02:42 +00007314 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7315 if (member->isArrow()) return false;
7316
7317 // Don't count this as an indirect ownership.
7318 e = member->getBase();
7319 continue;
7320 }
7321
John McCallfe96e0b2011-11-06 09:01:30 +00007322 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7323 // Only pay attention to pseudo-objects on property references.
7324 ObjCPropertyRefExpr *pre
7325 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7326 ->IgnoreParens());
7327 if (!pre) return false;
7328 if (pre->isImplicitProperty()) return false;
7329 ObjCPropertyDecl *property = pre->getExplicitProperty();
7330 if (!property->isRetaining() &&
7331 !(property->getPropertyIvarDecl() &&
7332 property->getPropertyIvarDecl()->getType()
7333 .getObjCLifetime() == Qualifiers::OCL_Strong))
7334 return false;
7335
7336 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007337 if (pre->isSuperReceiver()) {
7338 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7339 if (!owner.Variable)
7340 return false;
7341 owner.Loc = pre->getLocation();
7342 owner.Range = pre->getSourceRange();
7343 return true;
7344 }
John McCallfe96e0b2011-11-06 09:01:30 +00007345 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7346 ->getSourceExpr());
7347 continue;
7348 }
7349
John McCall31168b02011-06-15 23:02:42 +00007350 // Array ivars?
7351
7352 return false;
7353 }
7354}
7355
7356namespace {
7357 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7358 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7359 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007360 Context(Context), Variable(variable), Capturer(nullptr),
7361 VarWillBeReased(false) {}
7362 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007363 VarDecl *Variable;
7364 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007365 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007366
7367 void VisitDeclRefExpr(DeclRefExpr *ref) {
7368 if (ref->getDecl() == Variable && !Capturer)
7369 Capturer = ref;
7370 }
7371
John McCall31168b02011-06-15 23:02:42 +00007372 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7373 if (Capturer) return;
7374 Visit(ref->getBase());
7375 if (Capturer && ref->isFreeIvar())
7376 Capturer = ref;
7377 }
7378
7379 void VisitBlockExpr(BlockExpr *block) {
7380 // Look inside nested blocks
7381 if (block->getBlockDecl()->capturesVariable(Variable))
7382 Visit(block->getBlockDecl()->getBody());
7383 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007384
7385 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7386 if (Capturer) return;
7387 if (OVE->getSourceExpr())
7388 Visit(OVE->getSourceExpr());
7389 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007390 void VisitBinaryOperator(BinaryOperator *BinOp) {
7391 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7392 return;
7393 Expr *LHS = BinOp->getLHS();
7394 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7395 if (DRE->getDecl() != Variable)
7396 return;
7397 if (Expr *RHS = BinOp->getRHS()) {
7398 RHS = RHS->IgnoreParenCasts();
7399 llvm::APSInt Value;
7400 VarWillBeReased =
7401 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7402 }
7403 }
7404 }
John McCall31168b02011-06-15 23:02:42 +00007405 };
7406}
7407
7408/// Check whether the given argument is a block which captures a
7409/// variable.
7410static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7411 assert(owner.Variable && owner.Loc.isValid());
7412
7413 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007414
7415 // Look through [^{...} copy] and Block_copy(^{...}).
7416 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7417 Selector Cmd = ME->getSelector();
7418 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7419 e = ME->getInstanceReceiver();
7420 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007421 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007422 e = e->IgnoreParenCasts();
7423 }
7424 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7425 if (CE->getNumArgs() == 1) {
7426 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007427 if (Fn) {
7428 const IdentifierInfo *FnI = Fn->getIdentifier();
7429 if (FnI && FnI->isStr("_Block_copy")) {
7430 e = CE->getArg(0)->IgnoreParenCasts();
7431 }
7432 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007433 }
7434 }
7435
John McCall31168b02011-06-15 23:02:42 +00007436 BlockExpr *block = dyn_cast<BlockExpr>(e);
7437 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007438 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007439
7440 FindCaptureVisitor visitor(S.Context, owner.Variable);
7441 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007442 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007443}
7444
7445static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7446 RetainCycleOwner &owner) {
7447 assert(capturer);
7448 assert(owner.Variable && owner.Loc.isValid());
7449
7450 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7451 << owner.Variable << capturer->getSourceRange();
7452 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7453 << owner.Indirect << owner.Range;
7454}
7455
7456/// Check for a keyword selector that starts with the word 'add' or
7457/// 'set'.
7458static bool isSetterLikeSelector(Selector sel) {
7459 if (sel.isUnarySelector()) return false;
7460
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007461 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007462 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007463 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007464 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007465 else if (str.startswith("add")) {
7466 // Specially whitelist 'addOperationWithBlock:'.
7467 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7468 return false;
7469 str = str.substr(3);
7470 }
John McCall31168b02011-06-15 23:02:42 +00007471 else
7472 return false;
7473
7474 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007475 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007476}
7477
7478/// Check a message send to see if it's likely to cause a retain cycle.
7479void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7480 // Only check instance methods whose selector looks like a setter.
7481 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7482 return;
7483
7484 // Try to find a variable that the receiver is strongly owned by.
7485 RetainCycleOwner owner;
7486 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007487 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007488 return;
7489 } else {
7490 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7491 owner.Variable = getCurMethodDecl()->getSelfDecl();
7492 owner.Loc = msg->getSuperLoc();
7493 owner.Range = msg->getSuperLoc();
7494 }
7495
7496 // Check whether the receiver is captured by any of the arguments.
7497 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7498 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7499 return diagnoseRetainCycle(*this, capturer, owner);
7500}
7501
7502/// Check a property assign to see if it's likely to cause a retain cycle.
7503void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7504 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007505 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007506 return;
7507
7508 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7509 diagnoseRetainCycle(*this, capturer, owner);
7510}
7511
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007512void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7513 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007514 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007515 return;
7516
7517 // Because we don't have an expression for the variable, we have to set the
7518 // location explicitly here.
7519 Owner.Loc = Var->getLocation();
7520 Owner.Range = Var->getSourceRange();
7521
7522 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7523 diagnoseRetainCycle(*this, Capturer, Owner);
7524}
7525
Ted Kremenek9304da92012-12-21 08:04:28 +00007526static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7527 Expr *RHS, bool isProperty) {
7528 // Check if RHS is an Objective-C object literal, which also can get
7529 // immediately zapped in a weak reference. Note that we explicitly
7530 // allow ObjCStringLiterals, since those are designed to never really die.
7531 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007532
Ted Kremenek64873352012-12-21 22:46:35 +00007533 // This enum needs to match with the 'select' in
7534 // warn_objc_arc_literal_assign (off-by-1).
7535 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7536 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7537 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007538
7539 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007540 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007541 << (isProperty ? 0 : 1)
7542 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007543
7544 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007545}
7546
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007547static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7548 Qualifiers::ObjCLifetime LT,
7549 Expr *RHS, bool isProperty) {
7550 // Strip off any implicit cast added to get to the one ARC-specific.
7551 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7552 if (cast->getCastKind() == CK_ARCConsumeObject) {
7553 S.Diag(Loc, diag::warn_arc_retained_assign)
7554 << (LT == Qualifiers::OCL_ExplicitNone)
7555 << (isProperty ? 0 : 1)
7556 << RHS->getSourceRange();
7557 return true;
7558 }
7559 RHS = cast->getSubExpr();
7560 }
7561
7562 if (LT == Qualifiers::OCL_Weak &&
7563 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7564 return true;
7565
7566 return false;
7567}
7568
Ted Kremenekb36234d2012-12-21 08:04:20 +00007569bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7570 QualType LHS, Expr *RHS) {
7571 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7572
7573 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7574 return false;
7575
7576 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7577 return true;
7578
7579 return false;
7580}
7581
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007582void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7583 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007584 QualType LHSType;
7585 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007586 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007587 ObjCPropertyRefExpr *PRE
7588 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7589 if (PRE && !PRE->isImplicitProperty()) {
7590 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7591 if (PD)
7592 LHSType = PD->getType();
7593 }
7594
7595 if (LHSType.isNull())
7596 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007597
7598 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7599
7600 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007601 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007602 getCurFunction()->markSafeWeakUse(LHS);
7603 }
7604
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007605 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7606 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007607
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007608 // FIXME. Check for other life times.
7609 if (LT != Qualifiers::OCL_None)
7610 return;
7611
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007612 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007613 if (PRE->isImplicitProperty())
7614 return;
7615 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7616 if (!PD)
7617 return;
7618
Bill Wendling44426052012-12-20 19:22:21 +00007619 unsigned Attributes = PD->getPropertyAttributes();
7620 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007621 // when 'assign' attribute was not explicitly specified
7622 // by user, ignore it and rely on property type itself
7623 // for lifetime info.
7624 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7625 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7626 LHSType->isObjCRetainableType())
7627 return;
7628
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007629 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007630 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007631 Diag(Loc, diag::warn_arc_retained_property_assign)
7632 << RHS->getSourceRange();
7633 return;
7634 }
7635 RHS = cast->getSubExpr();
7636 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007637 }
Bill Wendling44426052012-12-20 19:22:21 +00007638 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007639 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7640 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007641 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007642 }
7643}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007644
7645//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7646
7647namespace {
7648bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7649 SourceLocation StmtLoc,
7650 const NullStmt *Body) {
7651 // Do not warn if the body is a macro that expands to nothing, e.g:
7652 //
7653 // #define CALL(x)
7654 // if (condition)
7655 // CALL(0);
7656 //
7657 if (Body->hasLeadingEmptyMacro())
7658 return false;
7659
7660 // Get line numbers of statement and body.
7661 bool StmtLineInvalid;
7662 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7663 &StmtLineInvalid);
7664 if (StmtLineInvalid)
7665 return false;
7666
7667 bool BodyLineInvalid;
7668 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7669 &BodyLineInvalid);
7670 if (BodyLineInvalid)
7671 return false;
7672
7673 // Warn if null statement and body are on the same line.
7674 if (StmtLine != BodyLine)
7675 return false;
7676
7677 return true;
7678}
7679} // Unnamed namespace
7680
7681void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7682 const Stmt *Body,
7683 unsigned DiagID) {
7684 // Since this is a syntactic check, don't emit diagnostic for template
7685 // instantiations, this just adds noise.
7686 if (CurrentInstantiationScope)
7687 return;
7688
7689 // The body should be a null statement.
7690 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7691 if (!NBody)
7692 return;
7693
7694 // Do the usual checks.
7695 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7696 return;
7697
7698 Diag(NBody->getSemiLoc(), DiagID);
7699 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7700}
7701
7702void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7703 const Stmt *PossibleBody) {
7704 assert(!CurrentInstantiationScope); // Ensured by caller
7705
7706 SourceLocation StmtLoc;
7707 const Stmt *Body;
7708 unsigned DiagID;
7709 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7710 StmtLoc = FS->getRParenLoc();
7711 Body = FS->getBody();
7712 DiagID = diag::warn_empty_for_body;
7713 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7714 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7715 Body = WS->getBody();
7716 DiagID = diag::warn_empty_while_body;
7717 } else
7718 return; // Neither `for' nor `while'.
7719
7720 // The body should be a null statement.
7721 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7722 if (!NBody)
7723 return;
7724
7725 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007726 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007727 return;
7728
7729 // Do the usual checks.
7730 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7731 return;
7732
7733 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7734 // noise level low, emit diagnostics only if for/while is followed by a
7735 // CompoundStmt, e.g.:
7736 // for (int i = 0; i < n; i++);
7737 // {
7738 // a(i);
7739 // }
7740 // or if for/while is followed by a statement with more indentation
7741 // than for/while itself:
7742 // for (int i = 0; i < n; i++);
7743 // a(i);
7744 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7745 if (!ProbableTypo) {
7746 bool BodyColInvalid;
7747 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7748 PossibleBody->getLocStart(),
7749 &BodyColInvalid);
7750 if (BodyColInvalid)
7751 return;
7752
7753 bool StmtColInvalid;
7754 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7755 S->getLocStart(),
7756 &StmtColInvalid);
7757 if (StmtColInvalid)
7758 return;
7759
7760 if (BodyCol > StmtCol)
7761 ProbableTypo = true;
7762 }
7763
7764 if (ProbableTypo) {
7765 Diag(NBody->getSemiLoc(), DiagID);
7766 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7767 }
7768}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007769
7770//===--- Layout compatibility ----------------------------------------------//
7771
7772namespace {
7773
7774bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7775
7776/// \brief Check if two enumeration types are layout-compatible.
7777bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7778 // C++11 [dcl.enum] p8:
7779 // Two enumeration types are layout-compatible if they have the same
7780 // underlying type.
7781 return ED1->isComplete() && ED2->isComplete() &&
7782 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7783}
7784
7785/// \brief Check if two fields are layout-compatible.
7786bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7787 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7788 return false;
7789
7790 if (Field1->isBitField() != Field2->isBitField())
7791 return false;
7792
7793 if (Field1->isBitField()) {
7794 // Make sure that the bit-fields are the same length.
7795 unsigned Bits1 = Field1->getBitWidthValue(C);
7796 unsigned Bits2 = Field2->getBitWidthValue(C);
7797
7798 if (Bits1 != Bits2)
7799 return false;
7800 }
7801
7802 return true;
7803}
7804
7805/// \brief Check if two standard-layout structs are layout-compatible.
7806/// (C++11 [class.mem] p17)
7807bool isLayoutCompatibleStruct(ASTContext &C,
7808 RecordDecl *RD1,
7809 RecordDecl *RD2) {
7810 // If both records are C++ classes, check that base classes match.
7811 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7812 // If one of records is a CXXRecordDecl we are in C++ mode,
7813 // thus the other one is a CXXRecordDecl, too.
7814 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7815 // Check number of base classes.
7816 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7817 return false;
7818
7819 // Check the base classes.
7820 for (CXXRecordDecl::base_class_const_iterator
7821 Base1 = D1CXX->bases_begin(),
7822 BaseEnd1 = D1CXX->bases_end(),
7823 Base2 = D2CXX->bases_begin();
7824 Base1 != BaseEnd1;
7825 ++Base1, ++Base2) {
7826 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7827 return false;
7828 }
7829 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7830 // If only RD2 is a C++ class, it should have zero base classes.
7831 if (D2CXX->getNumBases() > 0)
7832 return false;
7833 }
7834
7835 // Check the fields.
7836 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7837 Field2End = RD2->field_end(),
7838 Field1 = RD1->field_begin(),
7839 Field1End = RD1->field_end();
7840 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7841 if (!isLayoutCompatible(C, *Field1, *Field2))
7842 return false;
7843 }
7844 if (Field1 != Field1End || Field2 != Field2End)
7845 return false;
7846
7847 return true;
7848}
7849
7850/// \brief Check if two standard-layout unions are layout-compatible.
7851/// (C++11 [class.mem] p18)
7852bool isLayoutCompatibleUnion(ASTContext &C,
7853 RecordDecl *RD1,
7854 RecordDecl *RD2) {
7855 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007856 for (auto *Field2 : RD2->fields())
7857 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007858
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007859 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007860 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7861 I = UnmatchedFields.begin(),
7862 E = UnmatchedFields.end();
7863
7864 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007865 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007866 bool Result = UnmatchedFields.erase(*I);
7867 (void) Result;
7868 assert(Result);
7869 break;
7870 }
7871 }
7872 if (I == E)
7873 return false;
7874 }
7875
7876 return UnmatchedFields.empty();
7877}
7878
7879bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7880 if (RD1->isUnion() != RD2->isUnion())
7881 return false;
7882
7883 if (RD1->isUnion())
7884 return isLayoutCompatibleUnion(C, RD1, RD2);
7885 else
7886 return isLayoutCompatibleStruct(C, RD1, RD2);
7887}
7888
7889/// \brief Check if two types are layout-compatible in C++11 sense.
7890bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7891 if (T1.isNull() || T2.isNull())
7892 return false;
7893
7894 // C++11 [basic.types] p11:
7895 // If two types T1 and T2 are the same type, then T1 and T2 are
7896 // layout-compatible types.
7897 if (C.hasSameType(T1, T2))
7898 return true;
7899
7900 T1 = T1.getCanonicalType().getUnqualifiedType();
7901 T2 = T2.getCanonicalType().getUnqualifiedType();
7902
7903 const Type::TypeClass TC1 = T1->getTypeClass();
7904 const Type::TypeClass TC2 = T2->getTypeClass();
7905
7906 if (TC1 != TC2)
7907 return false;
7908
7909 if (TC1 == Type::Enum) {
7910 return isLayoutCompatible(C,
7911 cast<EnumType>(T1)->getDecl(),
7912 cast<EnumType>(T2)->getDecl());
7913 } else if (TC1 == Type::Record) {
7914 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7915 return false;
7916
7917 return isLayoutCompatible(C,
7918 cast<RecordType>(T1)->getDecl(),
7919 cast<RecordType>(T2)->getDecl());
7920 }
7921
7922 return false;
7923}
7924}
7925
7926//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7927
7928namespace {
7929/// \brief Given a type tag expression find the type tag itself.
7930///
7931/// \param TypeExpr Type tag expression, as it appears in user's code.
7932///
7933/// \param VD Declaration of an identifier that appears in a type tag.
7934///
7935/// \param MagicValue Type tag magic value.
7936bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7937 const ValueDecl **VD, uint64_t *MagicValue) {
7938 while(true) {
7939 if (!TypeExpr)
7940 return false;
7941
7942 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7943
7944 switch (TypeExpr->getStmtClass()) {
7945 case Stmt::UnaryOperatorClass: {
7946 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7947 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7948 TypeExpr = UO->getSubExpr();
7949 continue;
7950 }
7951 return false;
7952 }
7953
7954 case Stmt::DeclRefExprClass: {
7955 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7956 *VD = DRE->getDecl();
7957 return true;
7958 }
7959
7960 case Stmt::IntegerLiteralClass: {
7961 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7962 llvm::APInt MagicValueAPInt = IL->getValue();
7963 if (MagicValueAPInt.getActiveBits() <= 64) {
7964 *MagicValue = MagicValueAPInt.getZExtValue();
7965 return true;
7966 } else
7967 return false;
7968 }
7969
7970 case Stmt::BinaryConditionalOperatorClass:
7971 case Stmt::ConditionalOperatorClass: {
7972 const AbstractConditionalOperator *ACO =
7973 cast<AbstractConditionalOperator>(TypeExpr);
7974 bool Result;
7975 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7976 if (Result)
7977 TypeExpr = ACO->getTrueExpr();
7978 else
7979 TypeExpr = ACO->getFalseExpr();
7980 continue;
7981 }
7982 return false;
7983 }
7984
7985 case Stmt::BinaryOperatorClass: {
7986 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7987 if (BO->getOpcode() == BO_Comma) {
7988 TypeExpr = BO->getRHS();
7989 continue;
7990 }
7991 return false;
7992 }
7993
7994 default:
7995 return false;
7996 }
7997 }
7998}
7999
8000/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8001///
8002/// \param TypeExpr Expression that specifies a type tag.
8003///
8004/// \param MagicValues Registered magic values.
8005///
8006/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8007/// kind.
8008///
8009/// \param TypeInfo Information about the corresponding C type.
8010///
8011/// \returns true if the corresponding C type was found.
8012bool GetMatchingCType(
8013 const IdentifierInfo *ArgumentKind,
8014 const Expr *TypeExpr, const ASTContext &Ctx,
8015 const llvm::DenseMap<Sema::TypeTagMagicValue,
8016 Sema::TypeTagData> *MagicValues,
8017 bool &FoundWrongKind,
8018 Sema::TypeTagData &TypeInfo) {
8019 FoundWrongKind = false;
8020
8021 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008022 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008023
8024 uint64_t MagicValue;
8025
8026 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8027 return false;
8028
8029 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008030 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008031 if (I->getArgumentKind() != ArgumentKind) {
8032 FoundWrongKind = true;
8033 return false;
8034 }
8035 TypeInfo.Type = I->getMatchingCType();
8036 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8037 TypeInfo.MustBeNull = I->getMustBeNull();
8038 return true;
8039 }
8040 return false;
8041 }
8042
8043 if (!MagicValues)
8044 return false;
8045
8046 llvm::DenseMap<Sema::TypeTagMagicValue,
8047 Sema::TypeTagData>::const_iterator I =
8048 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8049 if (I == MagicValues->end())
8050 return false;
8051
8052 TypeInfo = I->second;
8053 return true;
8054}
8055} // unnamed namespace
8056
8057void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8058 uint64_t MagicValue, QualType Type,
8059 bool LayoutCompatible,
8060 bool MustBeNull) {
8061 if (!TypeTagForDatatypeMagicValues)
8062 TypeTagForDatatypeMagicValues.reset(
8063 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8064
8065 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8066 (*TypeTagForDatatypeMagicValues)[Magic] =
8067 TypeTagData(Type, LayoutCompatible, MustBeNull);
8068}
8069
8070namespace {
8071bool IsSameCharType(QualType T1, QualType T2) {
8072 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8073 if (!BT1)
8074 return false;
8075
8076 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8077 if (!BT2)
8078 return false;
8079
8080 BuiltinType::Kind T1Kind = BT1->getKind();
8081 BuiltinType::Kind T2Kind = BT2->getKind();
8082
8083 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8084 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8085 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8086 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8087}
8088} // unnamed namespace
8089
8090void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8091 const Expr * const *ExprArgs) {
8092 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8093 bool IsPointerAttr = Attr->getIsPointer();
8094
8095 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8096 bool FoundWrongKind;
8097 TypeTagData TypeInfo;
8098 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8099 TypeTagForDatatypeMagicValues.get(),
8100 FoundWrongKind, TypeInfo)) {
8101 if (FoundWrongKind)
8102 Diag(TypeTagExpr->getExprLoc(),
8103 diag::warn_type_tag_for_datatype_wrong_kind)
8104 << TypeTagExpr->getSourceRange();
8105 return;
8106 }
8107
8108 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8109 if (IsPointerAttr) {
8110 // Skip implicit cast of pointer to `void *' (as a function argument).
8111 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008112 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008113 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008114 ArgumentExpr = ICE->getSubExpr();
8115 }
8116 QualType ArgumentType = ArgumentExpr->getType();
8117
8118 // Passing a `void*' pointer shouldn't trigger a warning.
8119 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8120 return;
8121
8122 if (TypeInfo.MustBeNull) {
8123 // Type tag with matching void type requires a null pointer.
8124 if (!ArgumentExpr->isNullPointerConstant(Context,
8125 Expr::NPC_ValueDependentIsNotNull)) {
8126 Diag(ArgumentExpr->getExprLoc(),
8127 diag::warn_type_safety_null_pointer_required)
8128 << ArgumentKind->getName()
8129 << ArgumentExpr->getSourceRange()
8130 << TypeTagExpr->getSourceRange();
8131 }
8132 return;
8133 }
8134
8135 QualType RequiredType = TypeInfo.Type;
8136 if (IsPointerAttr)
8137 RequiredType = Context.getPointerType(RequiredType);
8138
8139 bool mismatch = false;
8140 if (!TypeInfo.LayoutCompatible) {
8141 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8142
8143 // C++11 [basic.fundamental] p1:
8144 // Plain char, signed char, and unsigned char are three distinct types.
8145 //
8146 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8147 // char' depending on the current char signedness mode.
8148 if (mismatch)
8149 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8150 RequiredType->getPointeeType())) ||
8151 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8152 mismatch = false;
8153 } else
8154 if (IsPointerAttr)
8155 mismatch = !isLayoutCompatible(Context,
8156 ArgumentType->getPointeeType(),
8157 RequiredType->getPointeeType());
8158 else
8159 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8160
8161 if (mismatch)
8162 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008163 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008164 << TypeInfo.LayoutCompatible << RequiredType
8165 << ArgumentExpr->getSourceRange()
8166 << TypeTagExpr->getSourceRange();
8167}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008168