blob: e1adfd48396c77487e6ceb806cda06289256773f [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000016#include "clang/Sema/SemaInternal.h"
John McCall781472f2010-08-25 08:40:02 +000017#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000018#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000019#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000020#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000021#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000023#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000024#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000025#include "clang/AST/DeclObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000028#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000029#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000031#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000032#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000033#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000034#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000035#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000036using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000037using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000038
Chris Lattner60800082009-02-18 17:49:48 +000039SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
40 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000041 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
42 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000043}
Chris Lattner08f92e32010-11-17 07:37:15 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045
Ryan Flynn4403a5e2009-08-06 03:00:50 +000046/// CheckablePrintfAttr - does a function call have a "printf" attribute
47/// and arguments that merit checking?
48bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
49 if (Format->getType() == "printf") return true;
50 if (Format->getType() == "printf0") {
51 // printf0 allows null "format" string; if so don't check format/args
52 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000053 // Does the index refer to the implicit object argument?
54 if (isa<CXXMemberCallExpr>(TheCall)) {
55 if (format_idx == 0)
56 return false;
57 --format_idx;
58 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000059 if (format_idx < TheCall->getNumArgs()) {
60 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000061 if (!Format->isNullPointerConstant(Context,
62 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000063 return true;
64 }
65 }
66 return false;
67}
Chris Lattner60800082009-02-18 17:49:48 +000068
John McCall8e10f3b2011-02-26 05:39:39 +000069/// Checks that a call expression's argument count is the desired number.
70/// This is useful when doing custom type-checking. Returns true on error.
71static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
72 unsigned argCount = call->getNumArgs();
73 if (argCount == desiredArgCount) return false;
74
75 if (argCount < desiredArgCount)
76 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
77 << 0 /*function call*/ << desiredArgCount << argCount
78 << call->getSourceRange();
79
80 // Highlight all the excess arguments.
81 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
82 call->getArg(argCount - 1)->getLocEnd());
83
84 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
85 << 0 /*function call*/ << desiredArgCount << argCount
86 << call->getArg(1)->getSourceRange();
87}
88
John McCall60d7b3a2010-08-24 06:29:42 +000089ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000090Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000091 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000092
Chris Lattner946928f2010-10-01 23:23:24 +000093 // Find out if any arguments are required to be integer constant expressions.
94 unsigned ICEArguments = 0;
95 ASTContext::GetBuiltinTypeError Error;
96 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
97 if (Error != ASTContext::GE_None)
98 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
99
100 // If any arguments are required to be ICE's, check and diagnose.
101 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
102 // Skip arguments not required to be ICE's.
103 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
104
105 llvm::APSInt Result;
106 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
107 return true;
108 ICEArguments &= ~(1 << ArgNo);
109 }
110
Anders Carlssond406bf02009-08-16 01:56:34 +0000111 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000112 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000113 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000114 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000115 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000116 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000117 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000118 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000119 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000120 if (SemaBuiltinVAStart(TheCall))
121 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000122 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000123 case Builtin::BI__builtin_isgreater:
124 case Builtin::BI__builtin_isgreaterequal:
125 case Builtin::BI__builtin_isless:
126 case Builtin::BI__builtin_islessequal:
127 case Builtin::BI__builtin_islessgreater:
128 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 if (SemaBuiltinUnorderedCompare(TheCall))
130 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000131 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000132 case Builtin::BI__builtin_fpclassify:
133 if (SemaBuiltinFPClassification(TheCall, 6))
134 return ExprError();
135 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000136 case Builtin::BI__builtin_isfinite:
137 case Builtin::BI__builtin_isinf:
138 case Builtin::BI__builtin_isinf_sign:
139 case Builtin::BI__builtin_isnan:
140 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000141 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000142 return ExprError();
143 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000144 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 return SemaBuiltinShuffleVector(TheCall);
146 // TheCall will be freed by the smart pointer here, but that's fine, since
147 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000148 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000149 if (SemaBuiltinPrefetch(TheCall))
150 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000151 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000152 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000153 if (SemaBuiltinObjectSize(TheCall))
154 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000155 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000156 case Builtin::BI__builtin_longjmp:
157 if (SemaBuiltinLongjmp(TheCall))
158 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000159 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000160
161 case Builtin::BI__builtin_classify_type:
162 if (checkArgCount(*this, TheCall, 1)) return true;
163 TheCall->setType(Context.IntTy);
164 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000165 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000166 if (checkArgCount(*this, TheCall, 1)) return true;
167 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000168 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000169 case Builtin::BI__sync_fetch_and_add:
170 case Builtin::BI__sync_fetch_and_sub:
171 case Builtin::BI__sync_fetch_and_or:
172 case Builtin::BI__sync_fetch_and_and:
173 case Builtin::BI__sync_fetch_and_xor:
174 case Builtin::BI__sync_add_and_fetch:
175 case Builtin::BI__sync_sub_and_fetch:
176 case Builtin::BI__sync_and_and_fetch:
177 case Builtin::BI__sync_or_and_fetch:
178 case Builtin::BI__sync_xor_and_fetch:
179 case Builtin::BI__sync_val_compare_and_swap:
180 case Builtin::BI__sync_bool_compare_and_swap:
181 case Builtin::BI__sync_lock_test_and_set:
182 case Builtin::BI__sync_lock_release:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000183 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000184 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000185 }
186
187 // Since the target specific builtins for each arch overlap, only check those
188 // of the arch we are compiling for.
189 if (BuiltinID >= Builtin::FirstTSBuiltin) {
190 switch (Context.Target.getTriple().getArch()) {
191 case llvm::Triple::arm:
192 case llvm::Triple::thumb:
193 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
194 return ExprError();
195 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000196 default:
197 break;
198 }
199 }
200
201 return move(TheCallResult);
202}
203
Nate Begeman61eecf52010-06-14 05:21:25 +0000204// Get the valid immediate range for the specified NEON type code.
205static unsigned RFT(unsigned t, bool shift = false) {
206 bool quad = t & 0x10;
207
208 switch (t & 0x7) {
209 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000210 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000211 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000212 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000213 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000214 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000215 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000216 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000217 case 4: // f32
218 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000219 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000220 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000221 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000222 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000223 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000224 case 7: // float16
225 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000226 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000227 }
228 return 0;
229}
230
Nate Begeman26a31422010-06-08 02:47:44 +0000231bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000232 llvm::APSInt Result;
233
Nate Begeman0d15c532010-06-13 04:47:52 +0000234 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000235 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000236 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000237#define GET_NEON_OVERLOAD_CHECK
238#include "clang/Basic/arm_neon.inc"
239#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000240 }
241
Nate Begeman0d15c532010-06-13 04:47:52 +0000242 // For NEON intrinsics which are overloaded on vector element type, validate
243 // the immediate which specifies which variant to emit.
244 if (mask) {
245 unsigned ArgNo = TheCall->getNumArgs()-1;
246 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
247 return true;
248
Nate Begeman61eecf52010-06-14 05:21:25 +0000249 TV = Result.getLimitedValue(32);
250 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000251 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
252 << TheCall->getArg(ArgNo)->getSourceRange();
253 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000254
Nate Begeman0d15c532010-06-13 04:47:52 +0000255 // For NEON intrinsics which take an immediate value as part of the
256 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000257 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000258 switch (BuiltinID) {
259 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000260 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
261 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000262 case ARM::BI__builtin_arm_vcvtr_f:
263 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000264#define GET_NEON_IMMEDIATE_CHECK
265#include "clang/Basic/arm_neon.inc"
266#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000267 };
268
Nate Begeman61eecf52010-06-14 05:21:25 +0000269 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000270 if (SemaBuiltinConstantArg(TheCall, i, Result))
271 return true;
272
Nate Begeman61eecf52010-06-14 05:21:25 +0000273 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000274 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000275 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000276 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000277 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000278
Nate Begeman99c40bb2010-08-03 21:32:34 +0000279 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000280 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000281}
Daniel Dunbarde454282008-10-02 18:44:07 +0000282
Anders Carlssond406bf02009-08-16 01:56:34 +0000283/// CheckFunctionCall - Check a direct function call for various correctness
284/// and safety properties not strictly enforced by the C type system.
285bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
286 // Get the IdentifierInfo* for the called function.
287 IdentifierInfo *FnInfo = FDecl->getIdentifier();
288
289 // None of the checks below are needed for functions that don't have
290 // simple names (e.g., C++ conversion functions).
291 if (!FnInfo)
292 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Daniel Dunbarde454282008-10-02 18:44:07 +0000294 // FIXME: This mechanism should be abstracted to be less fragile and
295 // more efficient. For example, just map function ids to custom
296 // handlers.
297
Ted Kremenekc82faca2010-09-09 04:33:05 +0000298 // Printf and scanf checking.
299 for (specific_attr_iterator<FormatAttr>
300 i = FDecl->specific_attr_begin<FormatAttr>(),
301 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
302
303 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000304 const bool b = Format->getType() == "scanf";
305 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000306 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000307 CheckPrintfScanfArguments(TheCall, HasVAListArg,
308 Format->getFormatIdx() - 1,
309 HasVAListArg ? 0 : Format->getFirstArg() - 1,
310 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000311 }
Chris Lattner59907c42007-08-10 20:18:51 +0000312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Ted Kremenekc82faca2010-09-09 04:33:05 +0000314 for (specific_attr_iterator<NonNullAttr>
315 i = FDecl->specific_attr_begin<NonNullAttr>(),
316 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000317 CheckNonNullArguments(*i, TheCall->getArgs(),
318 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000319 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000320
Anders Carlssond406bf02009-08-16 01:56:34 +0000321 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000322}
323
Anders Carlssond406bf02009-08-16 01:56:34 +0000324bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000325 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000326 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000327 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000328 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000330 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
331 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000332 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000334 QualType Ty = V->getType();
335 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000336 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Ted Kremenek826a3452010-07-16 02:11:22 +0000338 const bool b = Format->getType() == "scanf";
339 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000340 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Anders Carlssond406bf02009-08-16 01:56:34 +0000342 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000343 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
344 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000345
346 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000347}
348
Chris Lattner5caa3702009-05-08 06:58:22 +0000349/// SemaBuiltinAtomicOverloaded - We have a call to a function like
350/// __sync_fetch_and_add, which is an overloaded function based on the pointer
351/// type of its first argument. The main ActOnCallExpr routines have already
352/// promoted the types of arguments because all of these calls are prototyped as
353/// void(...).
354///
355/// This function goes through and does final semantic checking for these
356/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000357ExprResult
358Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000359 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000360 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
361 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
362
363 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000364 if (TheCall->getNumArgs() < 1) {
365 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
366 << 0 << 1 << TheCall->getNumArgs()
367 << TheCall->getCallee()->getSourceRange();
368 return ExprError();
369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Chris Lattner5caa3702009-05-08 06:58:22 +0000371 // Inspect the first argument of the atomic builtin. This should always be
372 // a pointer type, whose element is an integral scalar or pointer type.
373 // Because it is a pointer type, we don't have to worry about any implicit
374 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000375 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000376 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruthd2014572010-07-09 18:59:35 +0000377 if (!FirstArg->getType()->isPointerType()) {
378 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
379 << FirstArg->getType() << FirstArg->getSourceRange();
380 return ExprError();
381 }
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Chandler Carruthd2014572010-07-09 18:59:35 +0000383 QualType ValType =
384 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000385 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000386 !ValType->isBlockPointerType()) {
387 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
388 << FirstArg->getType() << FirstArg->getSourceRange();
389 return ExprError();
390 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000391
Chandler Carruth8d13d222010-07-18 20:54:12 +0000392 // The majority of builtins return a value, but a few have special return
393 // types, so allow them to override appropriately below.
394 QualType ResultType = ValType;
395
Chris Lattner5caa3702009-05-08 06:58:22 +0000396 // We need to figure out which concrete builtin this maps onto. For example,
397 // __sync_fetch_and_add with a 2 byte object turns into
398 // __sync_fetch_and_add_2.
399#define BUILTIN_ROW(x) \
400 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
401 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chris Lattner5caa3702009-05-08 06:58:22 +0000403 static const unsigned BuiltinIndices[][5] = {
404 BUILTIN_ROW(__sync_fetch_and_add),
405 BUILTIN_ROW(__sync_fetch_and_sub),
406 BUILTIN_ROW(__sync_fetch_and_or),
407 BUILTIN_ROW(__sync_fetch_and_and),
408 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner5caa3702009-05-08 06:58:22 +0000410 BUILTIN_ROW(__sync_add_and_fetch),
411 BUILTIN_ROW(__sync_sub_and_fetch),
412 BUILTIN_ROW(__sync_and_and_fetch),
413 BUILTIN_ROW(__sync_or_and_fetch),
414 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattner5caa3702009-05-08 06:58:22 +0000416 BUILTIN_ROW(__sync_val_compare_and_swap),
417 BUILTIN_ROW(__sync_bool_compare_and_swap),
418 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000419 BUILTIN_ROW(__sync_lock_release),
420 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000421 };
Mike Stump1eb44332009-09-09 15:08:12 +0000422#undef BUILTIN_ROW
423
Chris Lattner5caa3702009-05-08 06:58:22 +0000424 // Determine the index of the size.
425 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000426 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000427 case 1: SizeIndex = 0; break;
428 case 2: SizeIndex = 1; break;
429 case 4: SizeIndex = 2; break;
430 case 8: SizeIndex = 3; break;
431 case 16: SizeIndex = 4; break;
432 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000433 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
434 << FirstArg->getType() << FirstArg->getSourceRange();
435 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000436 }
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattner5caa3702009-05-08 06:58:22 +0000438 // Each of these builtins has one pointer argument, followed by some number of
439 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
440 // that we ignore. Find out which row of BuiltinIndices to read from as well
441 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000442 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000443 unsigned BuiltinIndex, NumFixed = 1;
444 switch (BuiltinID) {
445 default: assert(0 && "Unknown overloaded atomic builtin!");
446 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
447 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
448 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
449 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
450 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000452 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
453 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
454 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
455 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
456 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Chris Lattner5caa3702009-05-08 06:58:22 +0000458 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000459 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000460 NumFixed = 2;
461 break;
462 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000463 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000464 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000465 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000466 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000467 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000468 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000469 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000470 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000471 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000472 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000473 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000474 }
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Chris Lattner5caa3702009-05-08 06:58:22 +0000476 // Now that we know how many fixed arguments we expect, first check that we
477 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000478 if (TheCall->getNumArgs() < 1+NumFixed) {
479 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
480 << 0 << 1+NumFixed << TheCall->getNumArgs()
481 << TheCall->getCallee()->getSourceRange();
482 return ExprError();
483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000485 // Get the decl for the concrete builtin from this, we can tell what the
486 // concrete integer type we should convert to is.
487 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
488 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
489 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000490 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000491 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
492 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000493
John McCallf871d0c2010-08-07 06:22:56 +0000494 // The first argument --- the pointer --- has a fixed type; we
495 // deduce the types of the rest of the arguments accordingly. Walk
496 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000497 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000498 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Chris Lattner5caa3702009-05-08 06:58:22 +0000500 // If the argument is an implicit cast, then there was a promotion due to
501 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000502 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000503 Arg = ICE->getSubExpr();
504 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000505 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Chris Lattner5caa3702009-05-08 06:58:22 +0000508 // GCC does an implicit conversion to the pointer or integer ValType. This
509 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000510 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000511 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000512 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000513 Arg = CheckCastTypes(Arg.get()->getSourceRange(), ValType, Arg.take(), Kind, VK, BasePath);
514 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000515 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Chris Lattner5caa3702009-05-08 06:58:22 +0000517 // Okay, we have something that *can* be converted to the right type. Check
518 // to see if there is a potentially weird extension going on here. This can
519 // happen when you do an atomic operation on something like an char* and
520 // pass in 42. The 42 gets converted to char. This is even more strange
521 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000522 // FIXME: Do this check.
John Wiegley429bb272011-04-08 18:41:53 +0000523 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
524 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000525 }
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner5caa3702009-05-08 06:58:22 +0000527 // Switch the DeclRefExpr to refer to the new decl.
528 DRE->setDecl(NewBuiltinDecl);
529 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner5caa3702009-05-08 06:58:22 +0000531 // Set the callee in the CallExpr.
532 // FIXME: This leaks the original parens and implicit casts.
John Wiegley429bb272011-04-08 18:41:53 +0000533 ExprResult PromotedCall = UsualUnaryConversions(DRE);
534 if (PromotedCall.isInvalid())
535 return ExprError();
536 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000538 // Change the result type of the call to match the original value type. This
539 // is arbitrary, but the codegen for these builtins ins design to handle it
540 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000541 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000542
543 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000544}
545
546
Chris Lattner69039812009-02-18 06:01:06 +0000547/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000548/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000549/// Note: It might also make sense to do the UTF-16 conversion here (would
550/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000551bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000552 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000553 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
554
555 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000556 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
557 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000558 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000559 }
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000561 if (Literal->containsNonAsciiOrNull()) {
562 llvm::StringRef String = Literal->getString();
563 unsigned NumBytes = String.size();
564 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
565 const UTF8 *FromPtr = (UTF8 *)String.data();
566 UTF16 *ToPtr = &ToBuf[0];
567
568 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
569 &ToPtr, ToPtr + NumBytes,
570 strictConversion);
571 // Check for conversion failure.
572 if (Result != conversionOK)
573 Diag(Arg->getLocStart(),
574 diag::warn_cfstring_truncated) << Arg->getSourceRange();
575 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000576 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000577}
578
Chris Lattnerc27c6652007-12-20 00:05:45 +0000579/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
580/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000581bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
582 Expr *Fn = TheCall->getCallee();
583 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000584 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000585 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000586 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
587 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000588 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000589 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000590 return true;
591 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000592
593 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000594 return Diag(TheCall->getLocEnd(),
595 diag::err_typecheck_call_too_few_args_at_least)
596 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000597 }
598
Chris Lattnerc27c6652007-12-20 00:05:45 +0000599 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000600 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000601 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000602 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000603 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000604 else if (FunctionDecl *FD = getCurFunctionDecl())
605 isVariadic = FD->isVariadic();
606 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000607 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattnerc27c6652007-12-20 00:05:45 +0000609 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000610 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
611 return true;
612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Chris Lattner30ce3442007-12-19 23:59:04 +0000614 // Verify that the second argument to the builtin is the last argument of the
615 // current function or method.
616 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000617 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Anders Carlsson88cf2262008-02-11 04:20:54 +0000619 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
620 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000621 // FIXME: This isn't correct for methods (results in bogus warning).
622 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000623 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000624 if (CurBlock)
625 LastArg = *(CurBlock->TheDecl->param_end()-1);
626 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000627 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000628 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000629 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000630 SecondArgIsLastNamedArgument = PV == LastArg;
631 }
632 }
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattner30ce3442007-12-19 23:59:04 +0000634 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000635 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000636 diag::warn_second_parameter_of_va_start_not_last_named_argument);
637 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000638}
Chris Lattner30ce3442007-12-19 23:59:04 +0000639
Chris Lattner1b9a0792007-12-20 00:26:33 +0000640/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
641/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000642bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
643 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000644 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000645 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000646 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000647 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000648 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000649 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000650 << SourceRange(TheCall->getArg(2)->getLocStart(),
651 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000652
John Wiegley429bb272011-04-08 18:41:53 +0000653 ExprResult OrigArg0 = TheCall->getArg(0);
654 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000655
Chris Lattner1b9a0792007-12-20 00:26:33 +0000656 // Do standard promotions between the two arguments, returning their common
657 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000658 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000659 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
660 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000661
662 // Make sure any conversions are pushed back into the call; this is
663 // type safe since unordered compare builtins are declared as "_Bool
664 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000665 TheCall->setArg(0, OrigArg0.get());
666 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000667
John Wiegley429bb272011-04-08 18:41:53 +0000668 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000669 return false;
670
Chris Lattner1b9a0792007-12-20 00:26:33 +0000671 // If the common type isn't a real floating type, then the arguments were
672 // invalid for this operation.
673 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000674 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000675 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000676 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
677 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Chris Lattner1b9a0792007-12-20 00:26:33 +0000679 return false;
680}
681
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000682/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
683/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000684/// to check everything. We expect the last argument to be a floating point
685/// value.
686bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
687 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000688 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000689 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000690 if (TheCall->getNumArgs() > NumArgs)
691 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000692 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000693 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000694 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000695 (*(TheCall->arg_end()-1))->getLocEnd());
696
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000697 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Eli Friedman9ac6f622009-08-31 20:06:00 +0000699 if (OrigArg->isTypeDependent())
700 return false;
701
Chris Lattner81368fb2010-05-06 05:50:07 +0000702 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000703 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000704 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000705 diag::err_typecheck_call_invalid_unary_fp)
706 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Chris Lattner81368fb2010-05-06 05:50:07 +0000708 // If this is an implicit conversion from float -> double, remove it.
709 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
710 Expr *CastArg = Cast->getSubExpr();
711 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
712 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
713 "promotion from float to double is the only expected cast here");
714 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000715 TheCall->setArg(NumArgs-1, CastArg);
716 OrigArg = CastArg;
717 }
718 }
719
Eli Friedman9ac6f622009-08-31 20:06:00 +0000720 return false;
721}
722
Eli Friedmand38617c2008-05-14 19:38:39 +0000723/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
724// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000725ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000726 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000727 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000728 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000729 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000730 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000731
Nate Begeman37b6a572010-06-08 00:16:34 +0000732 // Determine which of the following types of shufflevector we're checking:
733 // 1) unary, vector mask: (lhs, mask)
734 // 2) binary, vector mask: (lhs, rhs, mask)
735 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
736 QualType resType = TheCall->getArg(0)->getType();
737 unsigned numElements = 0;
738
Douglas Gregorcde01732009-05-19 22:10:17 +0000739 if (!TheCall->getArg(0)->isTypeDependent() &&
740 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000741 QualType LHSType = TheCall->getArg(0)->getType();
742 QualType RHSType = TheCall->getArg(1)->getType();
743
744 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000745 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000746 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000747 TheCall->getArg(1)->getLocEnd());
748 return ExprError();
749 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000750
751 numElements = LHSType->getAs<VectorType>()->getNumElements();
752 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Nate Begeman37b6a572010-06-08 00:16:34 +0000754 // Check to see if we have a call with 2 vector arguments, the unary shuffle
755 // with mask. If so, verify that RHS is an integer vector type with the
756 // same number of elts as lhs.
757 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000758 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000759 RHSType->getAs<VectorType>()->getNumElements() != numElements)
760 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
761 << SourceRange(TheCall->getArg(1)->getLocStart(),
762 TheCall->getArg(1)->getLocEnd());
763 numResElements = numElements;
764 }
765 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000766 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000767 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000768 TheCall->getArg(1)->getLocEnd());
769 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000770 } else if (numElements != numResElements) {
771 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000772 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000773 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000774 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000775 }
776
777 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000778 if (TheCall->getArg(i)->isTypeDependent() ||
779 TheCall->getArg(i)->isValueDependent())
780 continue;
781
Nate Begeman37b6a572010-06-08 00:16:34 +0000782 llvm::APSInt Result(32);
783 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
784 return ExprError(Diag(TheCall->getLocStart(),
785 diag::err_shufflevector_nonconstant_argument)
786 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000787
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000788 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000789 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000790 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000791 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000792 }
793
794 llvm::SmallVector<Expr*, 32> exprs;
795
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000796 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000797 exprs.push_back(TheCall->getArg(i));
798 TheCall->setArg(i, 0);
799 }
800
Nate Begemana88dc302009-08-12 02:10:25 +0000801 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000802 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000803 TheCall->getCallee()->getLocStart(),
804 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000805}
Chris Lattner30ce3442007-12-19 23:59:04 +0000806
Daniel Dunbar4493f792008-07-21 22:59:13 +0000807/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
808// This is declared to take (const void*, ...) and can take two
809// optional constant int args.
810bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000811 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000812
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000813 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000814 return Diag(TheCall->getLocEnd(),
815 diag::err_typecheck_call_too_many_args_at_most)
816 << 0 /*function call*/ << 3 << NumArgs
817 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000818
819 // Argument 0 is checked for us and the remaining arguments must be
820 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000821 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000822 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000823
Eli Friedman9aef7262009-12-04 00:30:06 +0000824 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000825 if (SemaBuiltinConstantArg(TheCall, i, Result))
826 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Daniel Dunbar4493f792008-07-21 22:59:13 +0000828 // FIXME: gcc issues a warning and rewrites these to 0. These
829 // seems especially odd for the third argument since the default
830 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000831 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000832 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000833 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000834 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000835 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000836 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000837 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000838 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000839 }
840 }
841
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000842 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000843}
844
Eric Christopher691ebc32010-04-17 02:26:23 +0000845/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
846/// TheCall is a constant expression.
847bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
848 llvm::APSInt &Result) {
849 Expr *Arg = TheCall->getArg(ArgNum);
850 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
851 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
852
853 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
854
855 if (!Arg->isIntegerConstantExpr(Result, Context))
856 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000857 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000858
Chris Lattner21fb98e2009-09-23 06:06:36 +0000859 return false;
860}
861
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000862/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
863/// int type). This simply type checks that type is one of the defined
864/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000865// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000866bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000867 llvm::APSInt Result;
868
869 // Check constant-ness first.
870 if (SemaBuiltinConstantArg(TheCall, 1, Result))
871 return true;
872
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000873 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000874 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000875 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
876 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000877 }
878
879 return false;
880}
881
Eli Friedman586d6a82009-05-03 06:04:26 +0000882/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000883/// This checks that val is a constant 1.
884bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
885 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000886 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000887
Eric Christopher691ebc32010-04-17 02:26:23 +0000888 // TODO: This is less than ideal. Overload this to take a value.
889 if (SemaBuiltinConstantArg(TheCall, 1, Result))
890 return true;
891
892 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000893 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
894 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
895
896 return false;
897}
898
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000899// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000900bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
901 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000902 unsigned format_idx, unsigned firstDataArg,
903 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000904 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000905 if (E->isTypeDependent() || E->isValueDependent())
906 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000907
908 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000909 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000910 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000911 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000912 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
913 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000914 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000915 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000916 }
917
Ted Kremenek95355bb2010-09-09 03:51:42 +0000918 case Stmt::IntegerLiteralClass:
919 // Technically -Wformat-nonliteral does not warn about this case.
920 // The behavior of printf and friends in this case is implementation
921 // dependent. Ideally if the format string cannot be null then
922 // it should have a 'nonnull' attribute in the function prototype.
923 return true;
924
Ted Kremenekd30ef872009-01-12 23:09:09 +0000925 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000926 E = cast<ImplicitCastExpr>(E)->getSubExpr();
927 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000928 }
929
930 case Stmt::ParenExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000931 E = cast<ParenExpr>(E)->getSubExpr();
932 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000933 }
Mike Stump1eb44332009-09-09 15:08:12 +0000934
John McCall56ca35d2011-02-17 10:25:35 +0000935 case Stmt::OpaqueValueExprClass:
936 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
937 E = src;
938 goto tryAgain;
939 }
940 return false;
941
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000942 case Stmt::PredefinedExprClass:
943 // While __func__, etc., are technically not string literals, they
944 // cannot contain format specifiers and thus are not a security
945 // liability.
946 return true;
947
Ted Kremenek082d9362009-03-20 21:35:28 +0000948 case Stmt::DeclRefExprClass: {
949 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Ted Kremenek082d9362009-03-20 21:35:28 +0000951 // As an exception, do not flag errors for variables binding to
952 // const string literals.
953 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
954 bool isConstant = false;
955 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000956
Ted Kremenek082d9362009-03-20 21:35:28 +0000957 if (const ArrayType *AT = Context.getAsArrayType(T)) {
958 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000959 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000960 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000961 PT->getPointeeType().isConstant(Context);
962 }
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Ted Kremenek082d9362009-03-20 21:35:28 +0000964 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000965 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000966 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000967 HasVAListArg, format_idx, firstDataArg,
968 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000969 }
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Anders Carlssond966a552009-06-28 19:55:58 +0000971 // For vprintf* functions (i.e., HasVAListArg==true), we add a
972 // special check to see if the format string is a function parameter
973 // of the function calling the printf function. If the function
974 // has an attribute indicating it is a printf-like function, then we
975 // should suppress warnings concerning non-literals being used in a call
976 // to a vprintf function. For example:
977 //
978 // void
979 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
980 // va_list ap;
981 // va_start(ap, fmt);
982 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
983 // ...
984 //
985 //
986 // FIXME: We don't have full attribute support yet, so just check to see
987 // if the argument is a DeclRefExpr that references a parameter. We'll
988 // add proper support for checking the attribute later.
989 if (HasVAListArg)
990 if (isa<ParmVarDecl>(VD))
991 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000992 }
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Ted Kremenek082d9362009-03-20 21:35:28 +0000994 return false;
995 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000996
Anders Carlsson8f031b32009-06-27 04:05:33 +0000997 case Stmt::CallExprClass: {
998 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000999 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001000 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1001 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1002 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001003 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001004 unsigned ArgIndex = FA->getFormatIdx();
1005 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001006
1007 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001008 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001009 }
1010 }
1011 }
1012 }
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Anders Carlsson8f031b32009-06-27 04:05:33 +00001014 return false;
1015 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001016 case Stmt::ObjCStringLiteralClass:
1017 case Stmt::StringLiteralClass: {
1018 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Ted Kremenek082d9362009-03-20 21:35:28 +00001020 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001021 StrE = ObjCFExpr->getString();
1022 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001023 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Ted Kremenekd30ef872009-01-12 23:09:09 +00001025 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001026 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1027 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001028 return true;
1029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Ted Kremenekd30ef872009-01-12 23:09:09 +00001031 return false;
1032 }
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Ted Kremenek082d9362009-03-20 21:35:28 +00001034 default:
1035 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001036 }
1037}
1038
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001039void
Mike Stump1eb44332009-09-09 15:08:12 +00001040Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001041 const Expr * const *ExprArgs,
1042 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001043 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1044 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001045 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001046 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001047 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001048 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001049 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001050 }
1051}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001052
Ted Kremenek826a3452010-07-16 02:11:22 +00001053/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1054/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001055void
Ted Kremenek826a3452010-07-16 02:11:22 +00001056Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1057 unsigned format_idx, unsigned firstDataArg,
1058 bool isPrintf) {
1059
Ted Kremenek082d9362009-03-20 21:35:28 +00001060 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001061
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001062 // The way the format attribute works in GCC, the implicit this argument
1063 // of member functions is counted. However, it doesn't appear in our own
1064 // lists, so decrement format_idx in that case.
1065 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001066 const CXXMethodDecl *method_decl =
1067 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1068 if (method_decl && method_decl->isInstance()) {
1069 // Catch a format attribute mistakenly referring to the object argument.
1070 if (format_idx == 0)
1071 return;
1072 --format_idx;
1073 if(firstDataArg != 0)
1074 --firstDataArg;
1075 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001076 }
1077
Ted Kremenek826a3452010-07-16 02:11:22 +00001078 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001079 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001080 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001081 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001082 return;
1083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Ted Kremenek082d9362009-03-20 21:35:28 +00001085 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Chris Lattner59907c42007-08-10 20:18:51 +00001087 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001088 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001089 // Dynamically generated format strings are difficult to
1090 // automatically vet at compile time. Requiring that format strings
1091 // are string literals: (1) permits the checking of format strings by
1092 // the compiler and thereby (2) can practically remove the source of
1093 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001094
Mike Stump1eb44332009-09-09 15:08:12 +00001095 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001096 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001097 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001098 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001099 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001100 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001101 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001102
Chris Lattner655f1412009-04-29 04:59:47 +00001103 // If there are no arguments specified, warn with -Wformat-security, otherwise
1104 // warn only with -Wformat-nonliteral.
1105 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001106 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001107 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001108 << OrigFormatExpr->getSourceRange();
1109 else
Mike Stump1eb44332009-09-09 15:08:12 +00001110 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001111 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001112 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001113}
Ted Kremenek71895b92007-08-14 17:39:48 +00001114
Ted Kremeneke0e53132010-01-28 23:39:18 +00001115namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001116class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1117protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001118 Sema &S;
1119 const StringLiteral *FExpr;
1120 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001121 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001122 const unsigned NumDataArgs;
1123 const bool IsObjCLiteral;
1124 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001125 const bool HasVAListArg;
1126 const CallExpr *TheCall;
1127 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001128 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001129 bool usesPositionalArgs;
1130 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001131public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001132 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001133 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001134 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001135 const char *beg, bool hasVAListArg,
1136 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001137 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001138 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001139 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001140 IsObjCLiteral(isObjCLiteral), Beg(beg),
1141 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001142 TheCall(theCall), FormatIdx(formatIdx),
1143 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001144 CoveredArgs.resize(numDataArgs);
1145 CoveredArgs.reset();
1146 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001147
Ted Kremenek07d161f2010-01-29 01:50:07 +00001148 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001149
Ted Kremenek826a3452010-07-16 02:11:22 +00001150 void HandleIncompleteSpecifier(const char *startSpecifier,
1151 unsigned specifierLen);
1152
Ted Kremenekefaff192010-02-27 01:41:03 +00001153 virtual void HandleInvalidPosition(const char *startSpecifier,
1154 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001155 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001156
1157 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1158
Ted Kremeneke0e53132010-01-28 23:39:18 +00001159 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001160
Ted Kremenek826a3452010-07-16 02:11:22 +00001161protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001162 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1163 const char *startSpec,
1164 unsigned specifierLen,
1165 const char *csStart, unsigned csLen);
1166
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001167 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001168 CharSourceRange getSpecifierRange(const char *startSpecifier,
1169 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001170 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001171
Ted Kremenek0d277352010-01-29 01:06:55 +00001172 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001173
1174 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1175 const analyze_format_string::ConversionSpecifier &CS,
1176 const char *startSpecifier, unsigned specifierLen,
1177 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001178};
1179}
1180
Ted Kremenek826a3452010-07-16 02:11:22 +00001181SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001182 return OrigFormatExpr->getSourceRange();
1183}
1184
Ted Kremenek826a3452010-07-16 02:11:22 +00001185CharSourceRange CheckFormatHandler::
1186getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001187 SourceLocation Start = getLocationOfByte(startSpecifier);
1188 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1189
1190 // Advance the end SourceLocation by one due to half-open ranges.
1191 End = End.getFileLocWithOffset(1);
1192
1193 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001194}
1195
Ted Kremenek826a3452010-07-16 02:11:22 +00001196SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001197 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001198}
1199
Ted Kremenek826a3452010-07-16 02:11:22 +00001200void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1201 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001202 SourceLocation Loc = getLocationOfByte(startSpecifier);
1203 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001204 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001205}
1206
Ted Kremenekefaff192010-02-27 01:41:03 +00001207void
Ted Kremenek826a3452010-07-16 02:11:22 +00001208CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1209 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001210 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001211 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1212 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001213}
1214
Ted Kremenek826a3452010-07-16 02:11:22 +00001215void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001216 unsigned posLen) {
1217 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001218 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1219 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001220}
1221
Ted Kremenek826a3452010-07-16 02:11:22 +00001222void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001223 if (!IsObjCLiteral) {
1224 // The presence of a null character is likely an error.
1225 S.Diag(getLocationOfByte(nullCharacter),
1226 diag::warn_printf_format_string_contains_null_char)
1227 << getFormatStringRange();
1228 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001229}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001230
Ted Kremenek826a3452010-07-16 02:11:22 +00001231const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1232 return TheCall->getArg(FirstDataArg + i);
1233}
1234
1235void CheckFormatHandler::DoneProcessing() {
1236 // Does the number of data arguments exceed the number of
1237 // format conversions in the format string?
1238 if (!HasVAListArg) {
1239 // Find any arguments that weren't covered.
1240 CoveredArgs.flip();
1241 signed notCoveredArg = CoveredArgs.find_first();
1242 if (notCoveredArg >= 0) {
1243 assert((unsigned)notCoveredArg < NumDataArgs);
1244 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1245 diag::warn_printf_data_arg_not_used)
1246 << getFormatStringRange();
1247 }
1248 }
1249}
1250
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001251bool
1252CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1253 SourceLocation Loc,
1254 const char *startSpec,
1255 unsigned specifierLen,
1256 const char *csStart,
1257 unsigned csLen) {
1258
1259 bool keepGoing = true;
1260 if (argIndex < NumDataArgs) {
1261 // Consider the argument coverered, even though the specifier doesn't
1262 // make sense.
1263 CoveredArgs.set(argIndex);
1264 }
1265 else {
1266 // If argIndex exceeds the number of data arguments we
1267 // don't issue a warning because that is just a cascade of warnings (and
1268 // they may have intended '%%' anyway). We don't want to continue processing
1269 // the format string after this point, however, as we will like just get
1270 // gibberish when trying to match arguments.
1271 keepGoing = false;
1272 }
1273
1274 S.Diag(Loc, diag::warn_format_invalid_conversion)
1275 << llvm::StringRef(csStart, csLen)
1276 << getSpecifierRange(startSpec, specifierLen);
1277
1278 return keepGoing;
1279}
1280
Ted Kremenek666a1972010-07-26 19:45:42 +00001281bool
1282CheckFormatHandler::CheckNumArgs(
1283 const analyze_format_string::FormatSpecifier &FS,
1284 const analyze_format_string::ConversionSpecifier &CS,
1285 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1286
1287 if (argIndex >= NumDataArgs) {
1288 if (FS.usesPositionalArg()) {
1289 S.Diag(getLocationOfByte(CS.getStart()),
1290 diag::warn_printf_positional_arg_exceeds_data_args)
1291 << (argIndex+1) << NumDataArgs
1292 << getSpecifierRange(startSpecifier, specifierLen);
1293 }
1294 else {
1295 S.Diag(getLocationOfByte(CS.getStart()),
1296 diag::warn_printf_insufficient_data_args)
1297 << getSpecifierRange(startSpecifier, specifierLen);
1298 }
1299
1300 return false;
1301 }
1302 return true;
1303}
1304
Ted Kremenek826a3452010-07-16 02:11:22 +00001305//===--- CHECK: Printf format string checking ------------------------------===//
1306
1307namespace {
1308class CheckPrintfHandler : public CheckFormatHandler {
1309public:
1310 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1311 const Expr *origFormatExpr, unsigned firstDataArg,
1312 unsigned numDataArgs, bool isObjCLiteral,
1313 const char *beg, bool hasVAListArg,
1314 const CallExpr *theCall, unsigned formatIdx)
1315 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1316 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1317 theCall, formatIdx) {}
1318
1319
1320 bool HandleInvalidPrintfConversionSpecifier(
1321 const analyze_printf::PrintfSpecifier &FS,
1322 const char *startSpecifier,
1323 unsigned specifierLen);
1324
1325 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1326 const char *startSpecifier,
1327 unsigned specifierLen);
1328
1329 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1330 const char *startSpecifier, unsigned specifierLen);
1331 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1332 const analyze_printf::OptionalAmount &Amt,
1333 unsigned type,
1334 const char *startSpecifier, unsigned specifierLen);
1335 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1336 const analyze_printf::OptionalFlag &flag,
1337 const char *startSpecifier, unsigned specifierLen);
1338 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1339 const analyze_printf::OptionalFlag &ignoredFlag,
1340 const analyze_printf::OptionalFlag &flag,
1341 const char *startSpecifier, unsigned specifierLen);
1342};
1343}
1344
1345bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1346 const analyze_printf::PrintfSpecifier &FS,
1347 const char *startSpecifier,
1348 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001349 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001350 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001351
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001352 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1353 getLocationOfByte(CS.getStart()),
1354 startSpecifier, specifierLen,
1355 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001356}
1357
Ted Kremenek826a3452010-07-16 02:11:22 +00001358bool CheckPrintfHandler::HandleAmount(
1359 const analyze_format_string::OptionalAmount &Amt,
1360 unsigned k, const char *startSpecifier,
1361 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001362
1363 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001364 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001365 unsigned argIndex = Amt.getArgIndex();
1366 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001367 S.Diag(getLocationOfByte(Amt.getStart()),
1368 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001369 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001370 // Don't do any more checking. We will just emit
1371 // spurious errors.
1372 return false;
1373 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001374
Ted Kremenek0d277352010-01-29 01:06:55 +00001375 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001376 // Although not in conformance with C99, we also allow the argument to be
1377 // an 'unsigned int' as that is a reasonably safe case. GCC also
1378 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001379 CoveredArgs.set(argIndex);
1380 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001381 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001382
1383 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1384 assert(ATR.isValid());
1385
1386 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001387 S.Diag(getLocationOfByte(Amt.getStart()),
1388 diag::warn_printf_asterisk_wrong_type)
1389 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001390 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001391 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001392 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001393 // Don't do any more checking. We will just emit
1394 // spurious errors.
1395 return false;
1396 }
1397 }
1398 }
1399 return true;
1400}
Ted Kremenek0d277352010-01-29 01:06:55 +00001401
Tom Caree4ee9662010-06-17 19:00:27 +00001402void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001403 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001404 const analyze_printf::OptionalAmount &Amt,
1405 unsigned type,
1406 const char *startSpecifier,
1407 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001408 const analyze_printf::PrintfConversionSpecifier &CS =
1409 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001410 switch (Amt.getHowSpecified()) {
1411 case analyze_printf::OptionalAmount::Constant:
1412 S.Diag(getLocationOfByte(Amt.getStart()),
1413 diag::warn_printf_nonsensical_optional_amount)
1414 << type
1415 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001416 << getSpecifierRange(startSpecifier, specifierLen)
1417 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001418 Amt.getConstantLength()));
1419 break;
1420
1421 default:
1422 S.Diag(getLocationOfByte(Amt.getStart()),
1423 diag::warn_printf_nonsensical_optional_amount)
1424 << type
1425 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001426 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001427 break;
1428 }
1429}
1430
Ted Kremenek826a3452010-07-16 02:11:22 +00001431void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001432 const analyze_printf::OptionalFlag &flag,
1433 const char *startSpecifier,
1434 unsigned specifierLen) {
1435 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001436 const analyze_printf::PrintfConversionSpecifier &CS =
1437 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001438 S.Diag(getLocationOfByte(flag.getPosition()),
1439 diag::warn_printf_nonsensical_flag)
1440 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001441 << getSpecifierRange(startSpecifier, specifierLen)
1442 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001443}
1444
1445void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001446 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001447 const analyze_printf::OptionalFlag &ignoredFlag,
1448 const analyze_printf::OptionalFlag &flag,
1449 const char *startSpecifier,
1450 unsigned specifierLen) {
1451 // Warn about ignored flag with a fixit removal.
1452 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1453 diag::warn_printf_ignored_flag)
1454 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001455 << getSpecifierRange(startSpecifier, specifierLen)
1456 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001457 ignoredFlag.getPosition(), 1));
1458}
1459
Ted Kremeneke0e53132010-01-28 23:39:18 +00001460bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001461CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001462 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001463 const char *startSpecifier,
1464 unsigned specifierLen) {
1465
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001466 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001467 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001468 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001469
Ted Kremenekbaa40062010-07-19 22:01:06 +00001470 if (FS.consumesDataArgument()) {
1471 if (atFirstArg) {
1472 atFirstArg = false;
1473 usesPositionalArgs = FS.usesPositionalArg();
1474 }
1475 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1476 // Cannot mix-and-match positional and non-positional arguments.
1477 S.Diag(getLocationOfByte(CS.getStart()),
1478 diag::warn_format_mix_positional_nonpositional_args)
1479 << getSpecifierRange(startSpecifier, specifierLen);
1480 return false;
1481 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001482 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001483
Ted Kremenekefaff192010-02-27 01:41:03 +00001484 // First check if the field width, precision, and conversion specifier
1485 // have matching data arguments.
1486 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1487 startSpecifier, specifierLen)) {
1488 return false;
1489 }
1490
1491 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1492 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001493 return false;
1494 }
1495
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001496 if (!CS.consumesDataArgument()) {
1497 // FIXME: Technically specifying a precision or field width here
1498 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001499 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001500 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001501
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001502 // Consume the argument.
1503 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001504 if (argIndex < NumDataArgs) {
1505 // The check to see if the argIndex is valid will come later.
1506 // We set the bit here because we may exit early from this
1507 // function if we encounter some other error.
1508 CoveredArgs.set(argIndex);
1509 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001510
1511 // Check for using an Objective-C specific conversion specifier
1512 // in a non-ObjC literal.
1513 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001514 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1515 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001516 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001517
Tom Caree4ee9662010-06-17 19:00:27 +00001518 // Check for invalid use of field width
1519 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001520 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001521 startSpecifier, specifierLen);
1522 }
1523
1524 // Check for invalid use of precision
1525 if (!FS.hasValidPrecision()) {
1526 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1527 startSpecifier, specifierLen);
1528 }
1529
1530 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001531 if (!FS.hasValidThousandsGroupingPrefix())
1532 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001533 if (!FS.hasValidLeadingZeros())
1534 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1535 if (!FS.hasValidPlusPrefix())
1536 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001537 if (!FS.hasValidSpacePrefix())
1538 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001539 if (!FS.hasValidAlternativeForm())
1540 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1541 if (!FS.hasValidLeftJustified())
1542 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1543
1544 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001545 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1546 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1547 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001548 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1549 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1550 startSpecifier, specifierLen);
1551
1552 // Check the length modifier is valid with the given conversion specifier.
1553 const LengthModifier &LM = FS.getLengthModifier();
1554 if (!FS.hasValidLengthModifier())
1555 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001556 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001557 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001558 << getSpecifierRange(startSpecifier, specifierLen)
1559 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001560 LM.getLength()));
1561
1562 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001563 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001564 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001565 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001566 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001567 // Continue checking the other format specifiers.
1568 return true;
1569 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001570
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001571 // The remaining checks depend on the data arguments.
1572 if (HasVAListArg)
1573 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001574
Ted Kremenek666a1972010-07-26 19:45:42 +00001575 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001576 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001577
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001578 // Now type check the data expression that matches the
1579 // format specifier.
1580 const Expr *Ex = getDataArg(argIndex);
1581 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1582 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1583 // Check if we didn't match because of an implicit cast from a 'char'
1584 // or 'short' to an 'int'. This is done because printf is a varargs
1585 // function.
1586 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001587 if (ICE->getType() == S.Context.IntTy) {
1588 // All further checking is done on the subexpression.
1589 Ex = ICE->getSubExpr();
1590 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001591 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001592 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001593
1594 // We may be able to offer a FixItHint if it is a supported type.
1595 PrintfSpecifier fixedFS = FS;
1596 bool success = fixedFS.fixType(Ex->getType());
1597
1598 if (success) {
1599 // Get the fix string from the fixed format specifier
1600 llvm::SmallString<128> buf;
1601 llvm::raw_svector_ostream os(buf);
1602 fixedFS.toString(os);
1603
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001604 // FIXME: getRepresentativeType() perhaps should return a string
1605 // instead of a QualType to better handle when the representative
1606 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001607 S.Diag(getLocationOfByte(CS.getStart()),
1608 diag::warn_printf_conversion_argument_type_mismatch)
1609 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1610 << getSpecifierRange(startSpecifier, specifierLen)
1611 << Ex->getSourceRange()
1612 << FixItHint::CreateReplacement(
1613 getSpecifierRange(startSpecifier, specifierLen),
1614 os.str());
1615 }
1616 else {
1617 S.Diag(getLocationOfByte(CS.getStart()),
1618 diag::warn_printf_conversion_argument_type_mismatch)
1619 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1620 << getSpecifierRange(startSpecifier, specifierLen)
1621 << Ex->getSourceRange();
1622 }
1623 }
1624
Ted Kremeneke0e53132010-01-28 23:39:18 +00001625 return true;
1626}
1627
Ted Kremenek826a3452010-07-16 02:11:22 +00001628//===--- CHECK: Scanf format string checking ------------------------------===//
1629
1630namespace {
1631class CheckScanfHandler : public CheckFormatHandler {
1632public:
1633 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1634 const Expr *origFormatExpr, unsigned firstDataArg,
1635 unsigned numDataArgs, bool isObjCLiteral,
1636 const char *beg, bool hasVAListArg,
1637 const CallExpr *theCall, unsigned formatIdx)
1638 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1639 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1640 theCall, formatIdx) {}
1641
1642 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1643 const char *startSpecifier,
1644 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001645
1646 bool HandleInvalidScanfConversionSpecifier(
1647 const analyze_scanf::ScanfSpecifier &FS,
1648 const char *startSpecifier,
1649 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001650
1651 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001652};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001653}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001654
Ted Kremenekb7c21012010-07-16 18:28:03 +00001655void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1656 const char *end) {
1657 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1658 << getSpecifierRange(start, end - start);
1659}
1660
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001661bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1662 const analyze_scanf::ScanfSpecifier &FS,
1663 const char *startSpecifier,
1664 unsigned specifierLen) {
1665
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001666 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001667 FS.getConversionSpecifier();
1668
1669 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1670 getLocationOfByte(CS.getStart()),
1671 startSpecifier, specifierLen,
1672 CS.getStart(), CS.getLength());
1673}
1674
Ted Kremenek826a3452010-07-16 02:11:22 +00001675bool CheckScanfHandler::HandleScanfSpecifier(
1676 const analyze_scanf::ScanfSpecifier &FS,
1677 const char *startSpecifier,
1678 unsigned specifierLen) {
1679
1680 using namespace analyze_scanf;
1681 using namespace analyze_format_string;
1682
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001683 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001684
Ted Kremenekbaa40062010-07-19 22:01:06 +00001685 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1686 // be used to decide if we are using positional arguments consistently.
1687 if (FS.consumesDataArgument()) {
1688 if (atFirstArg) {
1689 atFirstArg = false;
1690 usesPositionalArgs = FS.usesPositionalArg();
1691 }
1692 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1693 // Cannot mix-and-match positional and non-positional arguments.
1694 S.Diag(getLocationOfByte(CS.getStart()),
1695 diag::warn_format_mix_positional_nonpositional_args)
1696 << getSpecifierRange(startSpecifier, specifierLen);
1697 return false;
1698 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001699 }
1700
1701 // Check if the field with is non-zero.
1702 const OptionalAmount &Amt = FS.getFieldWidth();
1703 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1704 if (Amt.getConstantAmount() == 0) {
1705 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1706 Amt.getConstantLength());
1707 S.Diag(getLocationOfByte(Amt.getStart()),
1708 diag::warn_scanf_nonzero_width)
1709 << R << FixItHint::CreateRemoval(R);
1710 }
1711 }
1712
1713 if (!FS.consumesDataArgument()) {
1714 // FIXME: Technically specifying a precision or field width here
1715 // makes no sense. Worth issuing a warning at some point.
1716 return true;
1717 }
1718
1719 // Consume the argument.
1720 unsigned argIndex = FS.getArgIndex();
1721 if (argIndex < NumDataArgs) {
1722 // The check to see if the argIndex is valid will come later.
1723 // We set the bit here because we may exit early from this
1724 // function if we encounter some other error.
1725 CoveredArgs.set(argIndex);
1726 }
1727
Ted Kremenek1e51c202010-07-20 20:04:47 +00001728 // Check the length modifier is valid with the given conversion specifier.
1729 const LengthModifier &LM = FS.getLengthModifier();
1730 if (!FS.hasValidLengthModifier()) {
1731 S.Diag(getLocationOfByte(LM.getStart()),
1732 diag::warn_format_nonsensical_length)
1733 << LM.toString() << CS.toString()
1734 << getSpecifierRange(startSpecifier, specifierLen)
1735 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1736 LM.getLength()));
1737 }
1738
Ted Kremenek826a3452010-07-16 02:11:22 +00001739 // The remaining checks depend on the data arguments.
1740 if (HasVAListArg)
1741 return true;
1742
Ted Kremenek666a1972010-07-26 19:45:42 +00001743 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001744 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001745
1746 // FIXME: Check that the argument type matches the format specifier.
1747
1748 return true;
1749}
1750
1751void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001752 const Expr *OrigFormatExpr,
1753 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001754 unsigned format_idx, unsigned firstDataArg,
1755 bool isPrintf) {
1756
Ted Kremeneke0e53132010-01-28 23:39:18 +00001757 // CHECK: is the format string a wide literal?
1758 if (FExpr->isWide()) {
1759 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001760 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001761 << OrigFormatExpr->getSourceRange();
1762 return;
1763 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001764
Ted Kremeneke0e53132010-01-28 23:39:18 +00001765 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001766 llvm::StringRef StrRef = FExpr->getString();
1767 const char *Str = StrRef.data();
1768 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001769
Ted Kremeneke0e53132010-01-28 23:39:18 +00001770 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001771 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001772 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001773 << OrigFormatExpr->getSourceRange();
1774 return;
1775 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001776
1777 if (isPrintf) {
1778 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1779 TheCall->getNumArgs() - firstDataArg,
1780 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1781 HasVAListArg, TheCall, format_idx);
1782
1783 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1784 H.DoneProcessing();
1785 }
1786 else {
1787 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1788 TheCall->getNumArgs() - firstDataArg,
1789 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1790 HasVAListArg, TheCall, format_idx);
1791
1792 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1793 H.DoneProcessing();
1794 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001795}
1796
Ted Kremenek06de2762007-08-17 16:46:58 +00001797//===--- CHECK: Return Address of Stack Variable --------------------------===//
1798
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001799static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1800static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001801
1802/// CheckReturnStackAddr - Check if a return statement returns the address
1803/// of a stack variable.
1804void
1805Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1806 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001808 Expr *stackE = 0;
1809 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1810
1811 // Perform checking for returned stack addresses, local blocks,
1812 // label addresses or references to temporaries.
Steve Naroffdd972f22008-09-05 22:11:13 +00001813 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001814 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001815 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001816 stackE = EvalVal(RetValExp, refVars);
1817 }
1818
1819 if (stackE == 0)
1820 return; // Nothing suspicious was found.
1821
1822 SourceLocation diagLoc;
1823 SourceRange diagRange;
1824 if (refVars.empty()) {
1825 diagLoc = stackE->getLocStart();
1826 diagRange = stackE->getSourceRange();
1827 } else {
1828 // We followed through a reference variable. 'stackE' contains the
1829 // problematic expression but we will warn at the return statement pointing
1830 // at the reference variable. We will later display the "trail" of
1831 // reference variables using notes.
1832 diagLoc = refVars[0]->getLocStart();
1833 diagRange = refVars[0]->getSourceRange();
1834 }
1835
1836 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1837 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1838 : diag::warn_ret_stack_addr)
1839 << DR->getDecl()->getDeclName() << diagRange;
1840 } else if (isa<BlockExpr>(stackE)) { // local block.
1841 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1842 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1843 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1844 } else { // local temporary.
1845 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1846 : diag::warn_ret_local_temp_addr)
1847 << diagRange;
1848 }
1849
1850 // Display the "trail" of reference variables that we followed until we
1851 // found the problematic expression using notes.
1852 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1853 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1854 // If this var binds to another reference var, show the range of the next
1855 // var, otherwise the var binds to the problematic expression, in which case
1856 // show the range of the expression.
1857 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1858 : stackE->getSourceRange();
1859 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1860 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00001861 }
1862}
1863
1864/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1865/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001866/// to a location on the stack, a local block, an address of a label, or a
1867/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00001868/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001869/// encounter a subexpression that (1) clearly does not lead to one of the
1870/// above problematic expressions (2) is something we cannot determine leads to
1871/// a problematic expression based on such local checking.
1872///
1873/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1874/// the expression that they point to. Such variables are added to the
1875/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00001876///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001877/// EvalAddr processes expressions that are pointers that are used as
1878/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001879/// At the base case of the recursion is a check for the above problematic
1880/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00001881///
1882/// This implementation handles:
1883///
1884/// * pointer-to-pointer casts
1885/// * implicit conversions from array references to pointers
1886/// * taking the address of fields
1887/// * arbitrary interplay between "&" and "*" operators
1888/// * pointer arithmetic from an address of a stack variable
1889/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001890static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1891 if (E->isTypeDependent())
1892 return NULL;
1893
Ted Kremenek06de2762007-08-17 16:46:58 +00001894 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001895 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001896 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001897 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001898 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Ted Kremenek06de2762007-08-17 16:46:58 +00001900 // Our "symbolic interpreter" is just a dispatch off the currently
1901 // viewed AST node. We then recursively traverse the AST by calling
1902 // EvalAddr and EvalVal appropriately.
1903 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001904 case Stmt::ParenExprClass:
1905 // Ignore parentheses.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001906 return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1907
1908 case Stmt::DeclRefExprClass: {
1909 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1910
1911 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1912 // If this is a reference variable, follow through to the expression that
1913 // it points to.
1914 if (V->hasLocalStorage() &&
1915 V->getType()->isReferenceType() && V->hasInit()) {
1916 // Add the reference variable to the "trail".
1917 refVars.push_back(DR);
1918 return EvalAddr(V->getInit(), refVars);
1919 }
1920
1921 return NULL;
1922 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001923
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001924 case Stmt::UnaryOperatorClass: {
1925 // The only unary operator that make sense to handle here
1926 // is AddrOf. All others don't make sense as pointers.
1927 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001928
John McCall2de56d12010-08-25 11:45:40 +00001929 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001930 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001931 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001932 return NULL;
1933 }
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001935 case Stmt::BinaryOperatorClass: {
1936 // Handle pointer arithmetic. All other binary operators are not valid
1937 // in this context.
1938 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001939 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001940
John McCall2de56d12010-08-25 11:45:40 +00001941 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001942 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001944 Expr *Base = B->getLHS();
1945
1946 // Determine which argument is the real pointer base. It could be
1947 // the RHS argument instead of the LHS.
1948 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001950 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001951 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001952 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001953
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001954 // For conditional operators we need to see if either the LHS or RHS are
1955 // valid DeclRefExpr*s. If one of them is valid, we return it.
1956 case Stmt::ConditionalOperatorClass: {
1957 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001959 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001960 if (Expr *lhsExpr = C->getLHS()) {
1961 // In C++, we can have a throw-expression, which has 'void' type.
1962 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001963 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001964 return LHS;
1965 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001966
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001967 // In C++, we can have a throw-expression, which has 'void' type.
1968 if (C->getRHS()->getType()->isVoidType())
1969 return NULL;
1970
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001971 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001972 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001973
1974 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00001975 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001976 return E; // local block.
1977 return NULL;
1978
1979 case Stmt::AddrLabelExprClass:
1980 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Ted Kremenek54b52742008-08-07 00:49:01 +00001982 // For casts, we need to handle conversions from arrays to
1983 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001984 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001985 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001986 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001987 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001988 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Steve Naroffdd972f22008-09-05 22:11:13 +00001990 if (SubExpr->getType()->isPointerType() ||
1991 SubExpr->getType()->isBlockPointerType() ||
1992 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001993 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00001994 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001995 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001996 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001997 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001998 }
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002000 // C++ casts. For dynamic casts, static casts, and const casts, we
2001 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002002 // through the cast. In the case the dynamic cast doesn't fail (and
2003 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002004 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002005 // FIXME: The comment about is wrong; we're not always converting
2006 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002007 // handle references to objects.
2008 case Stmt::CXXStaticCastExprClass:
2009 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002010 case Stmt::CXXConstCastExprClass:
2011 case Stmt::CXXReinterpretCastExprClass: {
2012 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002013 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002014 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002015 else
2016 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002019 // Everything else: we simply don't reason about them.
2020 default:
2021 return NULL;
2022 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002023}
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Ted Kremenek06de2762007-08-17 16:46:58 +00002025
2026/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2027/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002028static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002029do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002030 // We should only be called for evaluating non-pointer expressions, or
2031 // expressions with a pointer type that are not used as references but instead
2032 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Ted Kremenek06de2762007-08-17 16:46:58 +00002034 // Our "symbolic interpreter" is just a dispatch off the currently
2035 // viewed AST node. We then recursively traverse the AST by calling
2036 // EvalAddr and EvalVal appropriately.
2037 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002038 case Stmt::ImplicitCastExprClass: {
2039 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002040 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002041 E = IE->getSubExpr();
2042 continue;
2043 }
2044 return NULL;
2045 }
2046
Douglas Gregora2813ce2009-10-23 18:54:35 +00002047 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002048 // When we hit a DeclRefExpr we are looking at code that refers to a
2049 // variable's name. If it's not a reference variable we check if it has
2050 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002051 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Ted Kremenek06de2762007-08-17 16:46:58 +00002053 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002054 if (V->hasLocalStorage()) {
2055 if (!V->getType()->isReferenceType())
2056 return DR;
2057
2058 // Reference variable, follow through to the expression that
2059 // it points to.
2060 if (V->hasInit()) {
2061 // Add the reference variable to the "trail".
2062 refVars.push_back(DR);
2063 return EvalVal(V->getInit(), refVars);
2064 }
2065 }
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Ted Kremenek06de2762007-08-17 16:46:58 +00002067 return NULL;
2068 }
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Ted Kremenek68957a92010-08-04 20:01:07 +00002070 case Stmt::ParenExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002071 // Ignore parentheses.
Ted Kremenek68957a92010-08-04 20:01:07 +00002072 E = cast<ParenExpr>(E)->getSubExpr();
2073 continue;
2074 }
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Ted Kremenek06de2762007-08-17 16:46:58 +00002076 case Stmt::UnaryOperatorClass: {
2077 // The only unary operator that make sense to handle here
2078 // is Deref. All others don't resolve to a "name." This includes
2079 // handling all sorts of rvalues passed to a unary operator.
2080 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002081
John McCall2de56d12010-08-25 11:45:40 +00002082 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002083 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002084
2085 return NULL;
2086 }
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Ted Kremenek06de2762007-08-17 16:46:58 +00002088 case Stmt::ArraySubscriptExprClass: {
2089 // Array subscripts are potential references to data on the stack. We
2090 // retrieve the DeclRefExpr* for the array variable if it indeed
2091 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002092 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Ted Kremenek06de2762007-08-17 16:46:58 +00002095 case Stmt::ConditionalOperatorClass: {
2096 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002097 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002098 ConditionalOperator *C = cast<ConditionalOperator>(E);
2099
Anders Carlsson39073232007-11-30 19:04:31 +00002100 // Handle the GNU extension for missing LHS.
2101 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002102 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002103 return LHS;
2104
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002105 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002106 }
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Ted Kremenek06de2762007-08-17 16:46:58 +00002108 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002109 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002110 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Ted Kremenek06de2762007-08-17 16:46:58 +00002112 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002113 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002114 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002115
2116 // Check whether the member type is itself a reference, in which case
2117 // we're not going to refer to the member, but to what the member refers to.
2118 if (M->getMemberDecl()->getType()->isReferenceType())
2119 return NULL;
2120
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002121 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002122 }
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Ted Kremenek06de2762007-08-17 16:46:58 +00002124 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002125 // Check that we don't return or take the address of a reference to a
2126 // temporary. This is only useful in C++.
2127 if (!E->isTypeDependent() && E->isRValue())
2128 return E;
2129
2130 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002131 return NULL;
2132 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002133} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002134}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002135
2136//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2137
2138/// Check for comparisons of floating point operands using != and ==.
2139/// Issue a warning if these are no self-comparisons, as they are not likely
2140/// to do what the programmer intended.
2141void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2142 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002143
John McCallf6a16482010-12-04 03:47:34 +00002144 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2145 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002146
2147 // Special case: check for x == x (which is OK).
2148 // Do not emit warnings for such cases.
2149 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2150 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2151 if (DRL->getDecl() == DRR->getDecl())
2152 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002153
2154
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002155 // Special case: check for comparisons against literals that can be exactly
2156 // represented by APFloat. In such cases, do not emit a warning. This
2157 // is a heuristic: often comparison against such literals are used to
2158 // detect if a value in a variable has not changed. This clearly can
2159 // lead to false negatives.
2160 if (EmitWarning) {
2161 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2162 if (FLL->isExact())
2163 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002164 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002165 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2166 if (FLR->isExact())
2167 EmitWarning = false;
2168 }
2169 }
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002171 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002172 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002173 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002174 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002175 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Sebastian Redl0eb23302009-01-19 00:08:26 +00002177 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002178 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002179 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002180 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002182 // Emit the diagnostic.
2183 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002184 Diag(loc, diag::warn_floatingpoint_eq)
2185 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002186}
John McCallba26e582010-01-04 23:21:16 +00002187
John McCallf2370c92010-01-06 05:24:50 +00002188//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2189//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002190
John McCallf2370c92010-01-06 05:24:50 +00002191namespace {
John McCallba26e582010-01-04 23:21:16 +00002192
John McCallf2370c92010-01-06 05:24:50 +00002193/// Structure recording the 'active' range of an integer-valued
2194/// expression.
2195struct IntRange {
2196 /// The number of bits active in the int.
2197 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002198
John McCallf2370c92010-01-06 05:24:50 +00002199 /// True if the int is known not to have negative values.
2200 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002201
John McCallf2370c92010-01-06 05:24:50 +00002202 IntRange(unsigned Width, bool NonNegative)
2203 : Width(Width), NonNegative(NonNegative)
2204 {}
John McCallba26e582010-01-04 23:21:16 +00002205
John McCall1844a6e2010-11-10 23:38:19 +00002206 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002207 static IntRange forBoolType() {
2208 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002209 }
2210
John McCall1844a6e2010-11-10 23:38:19 +00002211 /// Returns the range of an opaque value of the given integral type.
2212 static IntRange forValueOfType(ASTContext &C, QualType T) {
2213 return forValueOfCanonicalType(C,
2214 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002215 }
2216
John McCall1844a6e2010-11-10 23:38:19 +00002217 /// Returns the range of an opaque value of a canonical integral type.
2218 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002219 assert(T->isCanonicalUnqualified());
2220
2221 if (const VectorType *VT = dyn_cast<VectorType>(T))
2222 T = VT->getElementType().getTypePtr();
2223 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2224 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002225
John McCall091f23f2010-11-09 22:22:12 +00002226 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002227 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2228 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002229 if (!Enum->isDefinition())
2230 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2231
John McCall323ed742010-05-06 08:58:33 +00002232 unsigned NumPositive = Enum->getNumPositiveBits();
2233 unsigned NumNegative = Enum->getNumNegativeBits();
2234
2235 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2236 }
John McCallf2370c92010-01-06 05:24:50 +00002237
2238 const BuiltinType *BT = cast<BuiltinType>(T);
2239 assert(BT->isInteger());
2240
2241 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2242 }
2243
John McCall1844a6e2010-11-10 23:38:19 +00002244 /// Returns the "target" range of a canonical integral type, i.e.
2245 /// the range of values expressible in the type.
2246 ///
2247 /// This matches forValueOfCanonicalType except that enums have the
2248 /// full range of their type, not the range of their enumerators.
2249 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2250 assert(T->isCanonicalUnqualified());
2251
2252 if (const VectorType *VT = dyn_cast<VectorType>(T))
2253 T = VT->getElementType().getTypePtr();
2254 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2255 T = CT->getElementType().getTypePtr();
2256 if (const EnumType *ET = dyn_cast<EnumType>(T))
2257 T = ET->getDecl()->getIntegerType().getTypePtr();
2258
2259 const BuiltinType *BT = cast<BuiltinType>(T);
2260 assert(BT->isInteger());
2261
2262 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2263 }
2264
2265 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002266 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002267 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002268 L.NonNegative && R.NonNegative);
2269 }
2270
John McCall1844a6e2010-11-10 23:38:19 +00002271 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002272 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002273 return IntRange(std::min(L.Width, R.Width),
2274 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002275 }
2276};
2277
2278IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2279 if (value.isSigned() && value.isNegative())
2280 return IntRange(value.getMinSignedBits(), false);
2281
2282 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002283 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002284
2285 // isNonNegative() just checks the sign bit without considering
2286 // signedness.
2287 return IntRange(value.getActiveBits(), true);
2288}
2289
John McCall0acc3112010-01-06 22:57:21 +00002290IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002291 unsigned MaxWidth) {
2292 if (result.isInt())
2293 return GetValueRange(C, result.getInt(), MaxWidth);
2294
2295 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002296 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2297 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2298 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2299 R = IntRange::join(R, El);
2300 }
John McCallf2370c92010-01-06 05:24:50 +00002301 return R;
2302 }
2303
2304 if (result.isComplexInt()) {
2305 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2306 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2307 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002308 }
2309
2310 // This can happen with lossless casts to intptr_t of "based" lvalues.
2311 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002312 // FIXME: The only reason we need to pass the type in here is to get
2313 // the sign right on this one case. It would be nice if APValue
2314 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002315 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002316 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002317}
John McCallf2370c92010-01-06 05:24:50 +00002318
2319/// Pseudo-evaluate the given integer expression, estimating the
2320/// range of values it might take.
2321///
2322/// \param MaxWidth - the width to which the value will be truncated
2323IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2324 E = E->IgnoreParens();
2325
2326 // Try a full evaluation first.
2327 Expr::EvalResult result;
2328 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002329 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002330
2331 // I think we only want to look through implicit casts here; if the
2332 // user has an explicit widening cast, we should treat the value as
2333 // being of the new, wider type.
2334 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002335 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002336 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2337
John McCall1844a6e2010-11-10 23:38:19 +00002338 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002339
John McCall2de56d12010-08-25 11:45:40 +00002340 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002341
John McCallf2370c92010-01-06 05:24:50 +00002342 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002343 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002344 return OutputTypeRange;
2345
2346 IntRange SubRange
2347 = GetExprRange(C, CE->getSubExpr(),
2348 std::min(MaxWidth, OutputTypeRange.Width));
2349
2350 // Bail out if the subexpr's range is as wide as the cast type.
2351 if (SubRange.Width >= OutputTypeRange.Width)
2352 return OutputTypeRange;
2353
2354 // Otherwise, we take the smaller width, and we're non-negative if
2355 // either the output type or the subexpr is.
2356 return IntRange(SubRange.Width,
2357 SubRange.NonNegative || OutputTypeRange.NonNegative);
2358 }
2359
2360 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2361 // If we can fold the condition, just take that operand.
2362 bool CondResult;
2363 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2364 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2365 : CO->getFalseExpr(),
2366 MaxWidth);
2367
2368 // Otherwise, conservatively merge.
2369 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2370 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2371 return IntRange::join(L, R);
2372 }
2373
2374 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2375 switch (BO->getOpcode()) {
2376
2377 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002378 case BO_LAnd:
2379 case BO_LOr:
2380 case BO_LT:
2381 case BO_GT:
2382 case BO_LE:
2383 case BO_GE:
2384 case BO_EQ:
2385 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002386 return IntRange::forBoolType();
2387
John McCallc0cd21d2010-02-23 19:22:29 +00002388 // The type of these compound assignments is the type of the LHS,
2389 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002390 case BO_MulAssign:
2391 case BO_DivAssign:
2392 case BO_RemAssign:
2393 case BO_AddAssign:
2394 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002395 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002396
John McCallf2370c92010-01-06 05:24:50 +00002397 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002398 case BO_PtrMemD:
2399 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002400 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002401
John McCall60fad452010-01-06 22:07:33 +00002402 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002403 case BO_And:
2404 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002405 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2406 GetExprRange(C, BO->getRHS(), MaxWidth));
2407
John McCallf2370c92010-01-06 05:24:50 +00002408 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002409 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002410 // ...except that we want to treat '1 << (blah)' as logically
2411 // positive. It's an important idiom.
2412 if (IntegerLiteral *I
2413 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2414 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002415 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002416 return IntRange(R.Width, /*NonNegative*/ true);
2417 }
2418 }
2419 // fallthrough
2420
John McCall2de56d12010-08-25 11:45:40 +00002421 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002422 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002423
John McCall60fad452010-01-06 22:07:33 +00002424 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002425 case BO_Shr:
2426 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002427 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2428
2429 // If the shift amount is a positive constant, drop the width by
2430 // that much.
2431 llvm::APSInt shift;
2432 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2433 shift.isNonNegative()) {
2434 unsigned zext = shift.getZExtValue();
2435 if (zext >= L.Width)
2436 L.Width = (L.NonNegative ? 0 : 1);
2437 else
2438 L.Width -= zext;
2439 }
2440
2441 return L;
2442 }
2443
2444 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002445 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002446 return GetExprRange(C, BO->getRHS(), MaxWidth);
2447
John McCall60fad452010-01-06 22:07:33 +00002448 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002449 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002450 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002451 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002452 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002453
John McCallf2370c92010-01-06 05:24:50 +00002454 default:
2455 break;
2456 }
2457
2458 // Treat every other operator as if it were closed on the
2459 // narrowest type that encompasses both operands.
2460 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2461 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2462 return IntRange::join(L, R);
2463 }
2464
2465 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2466 switch (UO->getOpcode()) {
2467 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002468 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002469 return IntRange::forBoolType();
2470
2471 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002472 case UO_Deref:
2473 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002474 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002475
2476 default:
2477 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2478 }
2479 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002480
2481 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002482 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002483 }
John McCallf2370c92010-01-06 05:24:50 +00002484
2485 FieldDecl *BitField = E->getBitField();
2486 if (BitField) {
2487 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2488 unsigned BitWidth = BitWidthAP.getZExtValue();
2489
2490 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2491 }
2492
John McCall1844a6e2010-11-10 23:38:19 +00002493 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002494}
John McCall51313c32010-01-04 23:31:57 +00002495
John McCall323ed742010-05-06 08:58:33 +00002496IntRange GetExprRange(ASTContext &C, Expr *E) {
2497 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2498}
2499
John McCall51313c32010-01-04 23:31:57 +00002500/// Checks whether the given value, which currently has the given
2501/// source semantics, has the same value when coerced through the
2502/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002503bool IsSameFloatAfterCast(const llvm::APFloat &value,
2504 const llvm::fltSemantics &Src,
2505 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002506 llvm::APFloat truncated = value;
2507
2508 bool ignored;
2509 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2510 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2511
2512 return truncated.bitwiseIsEqual(value);
2513}
2514
2515/// Checks whether the given value, which currently has the given
2516/// source semantics, has the same value when coerced through the
2517/// target semantics.
2518///
2519/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002520bool IsSameFloatAfterCast(const APValue &value,
2521 const llvm::fltSemantics &Src,
2522 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002523 if (value.isFloat())
2524 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2525
2526 if (value.isVector()) {
2527 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2528 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2529 return false;
2530 return true;
2531 }
2532
2533 assert(value.isComplexFloat());
2534 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2535 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2536}
2537
John McCallb4eb64d2010-10-08 02:01:28 +00002538void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002539
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002540static bool IsZero(Sema &S, Expr *E) {
2541 // Suppress cases where we are comparing against an enum constant.
2542 if (const DeclRefExpr *DR =
2543 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2544 if (isa<EnumConstantDecl>(DR->getDecl()))
2545 return false;
2546
2547 // Suppress cases where the '0' value is expanded from a macro.
2548 if (E->getLocStart().isMacroID())
2549 return false;
2550
John McCall323ed742010-05-06 08:58:33 +00002551 llvm::APSInt Value;
2552 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2553}
2554
John McCall372e1032010-10-06 00:25:24 +00002555static bool HasEnumType(Expr *E) {
2556 // Strip off implicit integral promotions.
2557 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002558 if (ICE->getCastKind() != CK_IntegralCast &&
2559 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002560 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002561 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002562 }
2563
2564 return E->getType()->isEnumeralType();
2565}
2566
John McCall323ed742010-05-06 08:58:33 +00002567void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002568 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002569 if (E->isValueDependent())
2570 return;
2571
John McCall2de56d12010-08-25 11:45:40 +00002572 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002573 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002574 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002575 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002576 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002577 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002578 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002579 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002580 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002581 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002582 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002583 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002584 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002585 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002586 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002587 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2588 }
2589}
2590
2591/// Analyze the operands of the given comparison. Implements the
2592/// fallback case from AnalyzeComparison.
2593void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002594 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2595 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002596}
John McCall51313c32010-01-04 23:31:57 +00002597
John McCallba26e582010-01-04 23:21:16 +00002598/// \brief Implements -Wsign-compare.
2599///
2600/// \param lex the left-hand expression
2601/// \param rex the right-hand expression
2602/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002603/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002604void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2605 // The type the comparison is being performed in.
2606 QualType T = E->getLHS()->getType();
2607 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2608 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002609
John McCall323ed742010-05-06 08:58:33 +00002610 // We don't do anything special if this isn't an unsigned integral
2611 // comparison: we're only interested in integral comparisons, and
2612 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002613 //
2614 // We also don't care about value-dependent expressions or expressions
2615 // whose result is a constant.
2616 if (!T->hasUnsignedIntegerRepresentation()
2617 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002618 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002619
John McCall323ed742010-05-06 08:58:33 +00002620 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2621 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002622
John McCall323ed742010-05-06 08:58:33 +00002623 // Check to see if one of the (unmodified) operands is of different
2624 // signedness.
2625 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002626 if (lex->getType()->hasSignedIntegerRepresentation()) {
2627 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002628 "unsigned comparison between two signed integer expressions?");
2629 signedOperand = lex;
2630 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002631 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002632 signedOperand = rex;
2633 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002634 } else {
John McCall323ed742010-05-06 08:58:33 +00002635 CheckTrivialUnsignedComparison(S, E);
2636 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002637 }
2638
John McCall323ed742010-05-06 08:58:33 +00002639 // Otherwise, calculate the effective range of the signed operand.
2640 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002641
John McCall323ed742010-05-06 08:58:33 +00002642 // Go ahead and analyze implicit conversions in the operands. Note
2643 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002644 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2645 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002646
John McCall323ed742010-05-06 08:58:33 +00002647 // If the signed range is non-negative, -Wsign-compare won't fire,
2648 // but we should still check for comparisons which are always true
2649 // or false.
2650 if (signedRange.NonNegative)
2651 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002652
2653 // For (in)equality comparisons, if the unsigned operand is a
2654 // constant which cannot collide with a overflowed signed operand,
2655 // then reinterpreting the signed operand as unsigned will not
2656 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002657 if (E->isEqualityOp()) {
2658 unsigned comparisonWidth = S.Context.getIntWidth(T);
2659 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002660
John McCall323ed742010-05-06 08:58:33 +00002661 // We should never be unable to prove that the unsigned operand is
2662 // non-negative.
2663 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2664
2665 if (unsignedRange.Width < comparisonWidth)
2666 return;
2667 }
2668
2669 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2670 << lex->getType() << rex->getType()
2671 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002672}
2673
John McCall15d7d122010-11-11 03:21:53 +00002674/// Analyzes an attempt to assign the given value to a bitfield.
2675///
2676/// Returns true if there was something fishy about the attempt.
2677bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2678 SourceLocation InitLoc) {
2679 assert(Bitfield->isBitField());
2680 if (Bitfield->isInvalidDecl())
2681 return false;
2682
John McCall91b60142010-11-11 05:33:51 +00002683 // White-list bool bitfields.
2684 if (Bitfield->getType()->isBooleanType())
2685 return false;
2686
Douglas Gregor46ff3032011-02-04 13:09:01 +00002687 // Ignore value- or type-dependent expressions.
2688 if (Bitfield->getBitWidth()->isValueDependent() ||
2689 Bitfield->getBitWidth()->isTypeDependent() ||
2690 Init->isValueDependent() ||
2691 Init->isTypeDependent())
2692 return false;
2693
John McCall15d7d122010-11-11 03:21:53 +00002694 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2695
2696 llvm::APSInt Width(32);
2697 Expr::EvalResult InitValue;
2698 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002699 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002700 !InitValue.Val.isInt())
2701 return false;
2702
2703 const llvm::APSInt &Value = InitValue.Val.getInt();
2704 unsigned OriginalWidth = Value.getBitWidth();
2705 unsigned FieldWidth = Width.getZExtValue();
2706
2707 if (OriginalWidth <= FieldWidth)
2708 return false;
2709
Jay Foad9f71a8f2010-12-07 08:25:34 +00002710 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002711
2712 // It's fairly common to write values into signed bitfields
2713 // that, if sign-extended, would end up becoming a different
2714 // value. We don't want to warn about that.
2715 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002716 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002717 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002718 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002719
2720 if (Value == TruncatedValue)
2721 return false;
2722
2723 std::string PrettyValue = Value.toString(10);
2724 std::string PrettyTrunc = TruncatedValue.toString(10);
2725
2726 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2727 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2728 << Init->getSourceRange();
2729
2730 return true;
2731}
2732
John McCallbeb22aa2010-11-09 23:24:47 +00002733/// Analyze the given simple or compound assignment for warning-worthy
2734/// operations.
2735void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2736 // Just recurse on the LHS.
2737 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2738
2739 // We want to recurse on the RHS as normal unless we're assigning to
2740 // a bitfield.
2741 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002742 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2743 E->getOperatorLoc())) {
2744 // Recurse, ignoring any implicit conversions on the RHS.
2745 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2746 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002747 }
2748 }
2749
2750 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2751}
2752
John McCall51313c32010-01-04 23:31:57 +00002753/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002754void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2755 SourceLocation CContext, unsigned diag) {
2756 S.Diag(E->getExprLoc(), diag)
2757 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2758}
2759
Chandler Carruthe1b02e02011-04-05 06:47:57 +00002760/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2761void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2762 unsigned diag) {
2763 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
2764}
2765
John McCall091f23f2010-11-09 22:22:12 +00002766std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2767 if (!Range.Width) return "0";
2768
2769 llvm::APSInt ValueInRange = Value;
2770 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002771 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002772 return ValueInRange.toString(10);
2773}
2774
Ted Kremenekef9ff882011-03-10 20:03:42 +00002775static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2776 SourceManager &smgr = S.Context.getSourceManager();
2777 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2778}
2779
John McCall323ed742010-05-06 08:58:33 +00002780void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002781 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002782 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002783
John McCall323ed742010-05-06 08:58:33 +00002784 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2785 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2786 if (Source == Target) return;
2787 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002788
Ted Kremenekef9ff882011-03-10 20:03:42 +00002789 // If the conversion context location is invalid don't complain.
2790 // We also don't want to emit a warning if the issue occurs from the
2791 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2792 // is slow, so we delay this check as long as possible. Once we detect
2793 // we are in that scenario, we just return.
2794 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00002795 return;
2796
John McCall51313c32010-01-04 23:31:57 +00002797 // Never diagnose implicit casts to bool.
2798 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2799 return;
2800
2801 // Strip vector types.
2802 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002803 if (!isa<VectorType>(Target)) {
2804 if (isFromSystemMacro(S, CC))
2805 return;
John McCallb4eb64d2010-10-08 02:01:28 +00002806 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002807 }
John McCall51313c32010-01-04 23:31:57 +00002808
2809 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2810 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2811 }
2812
2813 // Strip complex types.
2814 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002815 if (!isa<ComplexType>(Target)) {
2816 if (isFromSystemMacro(S, CC))
2817 return;
2818
John McCallb4eb64d2010-10-08 02:01:28 +00002819 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002820 }
John McCall51313c32010-01-04 23:31:57 +00002821
2822 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2823 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2824 }
2825
2826 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2827 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2828
2829 // If the source is floating point...
2830 if (SourceBT && SourceBT->isFloatingPoint()) {
2831 // ...and the target is floating point...
2832 if (TargetBT && TargetBT->isFloatingPoint()) {
2833 // ...then warn if we're dropping FP rank.
2834
2835 // Builtin FP kinds are ordered by increasing FP rank.
2836 if (SourceBT->getKind() > TargetBT->getKind()) {
2837 // Don't warn about float constants that are precisely
2838 // representable in the target type.
2839 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002840 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002841 // Value might be a float, a float vector, or a float complex.
2842 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002843 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2844 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002845 return;
2846 }
2847
Ted Kremenekef9ff882011-03-10 20:03:42 +00002848 if (isFromSystemMacro(S, CC))
2849 return;
2850
John McCallb4eb64d2010-10-08 02:01:28 +00002851 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002852 }
2853 return;
2854 }
2855
Ted Kremenekef9ff882011-03-10 20:03:42 +00002856 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00002857 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002858 if (isFromSystemMacro(S, CC))
2859 return;
2860
Chandler Carrutha5b93322011-02-17 11:05:49 +00002861 Expr *InnerE = E->IgnoreParenImpCasts();
2862 if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) {
2863 DiagnoseImpCast(S, LiteralExpr, T, CC,
2864 diag::warn_impcast_literal_float_to_integer);
2865 } else {
2866 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2867 }
2868 }
John McCall51313c32010-01-04 23:31:57 +00002869
2870 return;
2871 }
2872
John McCallf2370c92010-01-06 05:24:50 +00002873 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002874 return;
2875
John McCall323ed742010-05-06 08:58:33 +00002876 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002877 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002878
2879 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002880 // If the source is a constant, use a default-on diagnostic.
2881 // TODO: this should happen for bitfield stores, too.
2882 llvm::APSInt Value(32);
2883 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002884 if (isFromSystemMacro(S, CC))
2885 return;
2886
John McCall091f23f2010-11-09 22:22:12 +00002887 std::string PrettySourceValue = Value.toString(10);
2888 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2889
2890 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2891 << PrettySourceValue << PrettyTargetValue
2892 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2893 return;
2894 }
2895
John McCall51313c32010-01-04 23:31:57 +00002896 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2897 // and by god we'll let them.
Ted Kremenekef9ff882011-03-10 20:03:42 +00002898
2899 if (isFromSystemMacro(S, CC))
2900 return;
2901
John McCallf2370c92010-01-06 05:24:50 +00002902 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002903 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2904 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002905 }
2906
2907 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2908 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2909 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002910
2911 if (isFromSystemMacro(S, CC))
2912 return;
2913
John McCall323ed742010-05-06 08:58:33 +00002914 unsigned DiagID = diag::warn_impcast_integer_sign;
2915
2916 // Traditionally, gcc has warned about this under -Wsign-compare.
2917 // We also want to warn about it in -Wconversion.
2918 // So if -Wconversion is off, use a completely identical diagnostic
2919 // in the sign-compare group.
2920 // The conditional-checking code will
2921 if (ICContext) {
2922 DiagID = diag::warn_impcast_integer_sign_conditional;
2923 *ICContext = true;
2924 }
2925
John McCallb4eb64d2010-10-08 02:01:28 +00002926 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002927 }
2928
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002929 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002930 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
2931 // type, to give us better diagnostics.
2932 QualType SourceType = E->getType();
2933 if (!S.getLangOptions().CPlusPlus) {
2934 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2935 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2936 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
2937 SourceType = S.Context.getTypeDeclType(Enum);
2938 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
2939 }
2940 }
2941
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002942 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
2943 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
2944 if ((SourceEnum->getDecl()->getIdentifier() ||
2945 SourceEnum->getDecl()->getTypedefForAnonDecl()) &&
2946 (TargetEnum->getDecl()->getIdentifier() ||
2947 TargetEnum->getDecl()->getTypedefForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00002948 SourceEnum != TargetEnum) {
2949 if (isFromSystemMacro(S, CC))
2950 return;
2951
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002952 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002953 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002954 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002955
John McCall51313c32010-01-04 23:31:57 +00002956 return;
2957}
2958
John McCall323ed742010-05-06 08:58:33 +00002959void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2960
2961void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002962 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00002963 E = E->IgnoreParenImpCasts();
2964
2965 if (isa<ConditionalOperator>(E))
2966 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2967
John McCallb4eb64d2010-10-08 02:01:28 +00002968 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002969 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002970 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00002971 return;
2972}
2973
2974void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00002975 SourceLocation CC = E->getQuestionLoc();
2976
2977 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00002978
2979 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00002980 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2981 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002982
2983 // If -Wconversion would have warned about either of the candidates
2984 // for a signedness conversion to the context type...
2985 if (!Suspicious) return;
2986
2987 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002988 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
2989 CC))
John McCall323ed742010-05-06 08:58:33 +00002990 return;
2991
2992 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002993 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00002994 return;
2995
2996 // ...then check whether it would have warned about either of the
2997 // candidates for a signedness conversion to the condition type.
2998 if (E->getType() != T) {
2999 Suspicious = false;
3000 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003001 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003002 if (!Suspicious)
3003 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003004 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003005 if (!Suspicious)
3006 return;
3007 }
3008
3009 // If so, emit a diagnostic under -Wsign-compare.
3010 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3011 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3012 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3013 << lex->getType() << rex->getType()
3014 << lex->getSourceRange() << rex->getSourceRange();
3015}
3016
3017/// AnalyzeImplicitConversions - Find and report any interesting
3018/// implicit conversions in the given expression. There are a couple
3019/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003020void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003021 QualType T = OrigE->getType();
3022 Expr *E = OrigE->IgnoreParenImpCasts();
3023
3024 // For conditional operators, we analyze the arguments as if they
3025 // were being fed directly into the output.
3026 if (isa<ConditionalOperator>(E)) {
3027 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3028 CheckConditionalOperator(S, CO, T);
3029 return;
3030 }
3031
3032 // Go ahead and check any implicit conversions we might have skipped.
3033 // The non-canonical typecheck is just an optimization;
3034 // CheckImplicitConversion will filter out dead implicit conversions.
3035 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003036 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003037
3038 // Now continue drilling into this expression.
3039
3040 // Skip past explicit casts.
3041 if (isa<ExplicitCastExpr>(E)) {
3042 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003043 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003044 }
3045
John McCallbeb22aa2010-11-09 23:24:47 +00003046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3047 // Do a somewhat different check with comparison operators.
3048 if (BO->isComparisonOp())
3049 return AnalyzeComparison(S, BO);
3050
3051 // And with assignments and compound assignments.
3052 if (BO->isAssignmentOp())
3053 return AnalyzeAssignment(S, BO);
3054 }
John McCall323ed742010-05-06 08:58:33 +00003055
3056 // These break the otherwise-useful invariant below. Fortunately,
3057 // we don't really need to recurse into them, because any internal
3058 // expressions should have been analyzed already when they were
3059 // built into statements.
3060 if (isa<StmtExpr>(E)) return;
3061
3062 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003063 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003064
3065 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003066 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003067 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003068 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003069}
3070
3071} // end anonymous namespace
3072
3073/// Diagnoses "dangerous" implicit conversions within the given
3074/// expression (which is a full expression). Implements -Wconversion
3075/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003076///
3077/// \param CC the "context" location of the implicit conversion, i.e.
3078/// the most location of the syntactic entity requiring the implicit
3079/// conversion
3080void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003081 // Don't diagnose in unevaluated contexts.
3082 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3083 return;
3084
3085 // Don't diagnose for value- or type-dependent expressions.
3086 if (E->isTypeDependent() || E->isValueDependent())
3087 return;
3088
John McCallb4eb64d2010-10-08 02:01:28 +00003089 // This is not the right CC for (e.g.) a variable initialization.
3090 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003091}
3092
John McCall15d7d122010-11-11 03:21:53 +00003093void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3094 FieldDecl *BitField,
3095 Expr *Init) {
3096 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3097}
3098
Mike Stumpf8c49212010-01-21 03:59:47 +00003099/// CheckParmsForFunctionDef - Check that the parameters of the given
3100/// function are appropriate for the definition of a function. This
3101/// takes care of any checks that cannot be performed on the
3102/// declaration itself, e.g., that the types of each of the function
3103/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003104bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3105 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003106 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003107 for (; P != PEnd; ++P) {
3108 ParmVarDecl *Param = *P;
3109
Mike Stumpf8c49212010-01-21 03:59:47 +00003110 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3111 // function declarator that is part of a function definition of
3112 // that function shall not have incomplete type.
3113 //
3114 // This is also C++ [dcl.fct]p6.
3115 if (!Param->isInvalidDecl() &&
3116 RequireCompleteType(Param->getLocation(), Param->getType(),
3117 diag::err_typecheck_decl_incomplete_type)) {
3118 Param->setInvalidDecl();
3119 HasInvalidParm = true;
3120 }
3121
3122 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3123 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003124 if (CheckParameterNames &&
3125 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003126 !Param->isImplicit() &&
3127 !getLangOptions().CPlusPlus)
3128 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003129
3130 // C99 6.7.5.3p12:
3131 // If the function declarator is not part of a definition of that
3132 // function, parameters may have incomplete type and may use the [*]
3133 // notation in their sequences of declarator specifiers to specify
3134 // variable length array types.
3135 QualType PType = Param->getOriginalType();
3136 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3137 if (AT->getSizeModifier() == ArrayType::Star) {
3138 // FIXME: This diagnosic should point the the '[*]' if source-location
3139 // information is added for it.
3140 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3141 }
3142 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003143 }
3144
3145 return HasInvalidParm;
3146}
John McCallb7f4ffe2010-08-12 21:44:57 +00003147
3148/// CheckCastAlign - Implements -Wcast-align, which warns when a
3149/// pointer cast increases the alignment requirements.
3150void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3151 // This is actually a lot of work to potentially be doing on every
3152 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003153 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3154 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003155 == Diagnostic::Ignored)
3156 return;
3157
3158 // Ignore dependent types.
3159 if (T->isDependentType() || Op->getType()->isDependentType())
3160 return;
3161
3162 // Require that the destination be a pointer type.
3163 const PointerType *DestPtr = T->getAs<PointerType>();
3164 if (!DestPtr) return;
3165
3166 // If the destination has alignment 1, we're done.
3167 QualType DestPointee = DestPtr->getPointeeType();
3168 if (DestPointee->isIncompleteType()) return;
3169 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3170 if (DestAlign.isOne()) return;
3171
3172 // Require that the source be a pointer type.
3173 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3174 if (!SrcPtr) return;
3175 QualType SrcPointee = SrcPtr->getPointeeType();
3176
3177 // Whitelist casts from cv void*. We already implicitly
3178 // whitelisted casts to cv void*, since they have alignment 1.
3179 // Also whitelist casts involving incomplete types, which implicitly
3180 // includes 'void'.
3181 if (SrcPointee->isIncompleteType()) return;
3182
3183 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3184 if (SrcAlign >= DestAlign) return;
3185
3186 Diag(TRange.getBegin(), diag::warn_cast_align)
3187 << Op->getType() << T
3188 << static_cast<unsigned>(SrcAlign.getQuantity())
3189 << static_cast<unsigned>(DestAlign.getQuantity())
3190 << TRange << Op->getSourceRange();
3191}
3192
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003193static void CheckArrayAccess_Check(Sema &S,
3194 const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003195 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003196 const ConstantArrayType *ArrayTy =
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003197 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003198 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003199 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003200
Chandler Carruth34064582011-02-17 20:55:08 +00003201 const Expr *IndexExpr = E->getIdx();
3202 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003203 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003204 llvm::APSInt index;
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003205 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003206 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003207
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003208 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003209 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003210 if (!size.isStrictlyPositive())
3211 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003212 if (size.getBitWidth() > index.getBitWidth())
3213 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003214 else if (size.getBitWidth() < index.getBitWidth())
3215 size = size.sext(index.getBitWidth());
3216
Chandler Carruth34064582011-02-17 20:55:08 +00003217 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003218 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003219
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003220 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3221 S.PDiag(diag::warn_array_index_exceeds_bounds)
3222 << index.toString(10, true)
3223 << size.toString(10, true)
3224 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003225 } else {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003226 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3227 S.PDiag(diag::warn_array_index_precedes_bounds)
3228 << index.toString(10, true)
3229 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003230 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003231
3232 const NamedDecl *ND = NULL;
3233 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3234 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3235 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3236 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3237 if (ND)
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003238 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3239 S.PDiag(diag::note_array_index_out_of_bounds)
3240 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003241}
3242
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003243void Sema::CheckArrayAccess(const Expr *expr) {
3244 while (true)
3245 switch (expr->getStmtClass()) {
3246 case Stmt::ParenExprClass:
3247 expr = cast<ParenExpr>(expr)->getSubExpr();
3248 continue;
3249 case Stmt::ArraySubscriptExprClass:
3250 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3251 return;
3252 case Stmt::ConditionalOperatorClass: {
3253 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3254 if (const Expr *lhs = cond->getLHS())
3255 CheckArrayAccess(lhs);
3256 if (const Expr *rhs = cond->getRHS())
3257 CheckArrayAccess(rhs);
3258 return;
3259 }
3260 default:
3261 return;
3262 }
3263}