blob: 9dec2596969ebf46c63ad1e88cc7e0b72c0bf4a2 [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).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000865// For compatibility 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
Peter Collingbournef111d932011-04-15 00:35:48 +0000908 E = E->IgnoreParens();
909
Ted Kremenekd30ef872009-01-12 23:09:09 +0000910 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000911 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000912 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000913 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000914 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
915 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000916 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000917 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000918 }
919
Ted Kremenek95355bb2010-09-09 03:51:42 +0000920 case Stmt::IntegerLiteralClass:
921 // Technically -Wformat-nonliteral does not warn about this case.
922 // The behavior of printf and friends in this case is implementation
923 // dependent. Ideally if the format string cannot be null then
924 // it should have a 'nonnull' attribute in the function prototype.
925 return true;
926
Ted Kremenekd30ef872009-01-12 23:09:09 +0000927 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000928 E = cast<ImplicitCastExpr>(E)->getSubExpr();
929 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000930 }
931
John McCall56ca35d2011-02-17 10:25:35 +0000932 case Stmt::OpaqueValueExprClass:
933 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
934 E = src;
935 goto tryAgain;
936 }
937 return false;
938
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000939 case Stmt::PredefinedExprClass:
940 // While __func__, etc., are technically not string literals, they
941 // cannot contain format specifiers and thus are not a security
942 // liability.
943 return true;
944
Ted Kremenek082d9362009-03-20 21:35:28 +0000945 case Stmt::DeclRefExprClass: {
946 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Ted Kremenek082d9362009-03-20 21:35:28 +0000948 // As an exception, do not flag errors for variables binding to
949 // const string literals.
950 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
951 bool isConstant = false;
952 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000953
Ted Kremenek082d9362009-03-20 21:35:28 +0000954 if (const ArrayType *AT = Context.getAsArrayType(T)) {
955 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000956 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000957 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000958 PT->getPointeeType().isConstant(Context);
959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Ted Kremenek082d9362009-03-20 21:35:28 +0000961 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000962 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000963 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000964 HasVAListArg, format_idx, firstDataArg,
965 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000966 }
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Anders Carlssond966a552009-06-28 19:55:58 +0000968 // For vprintf* functions (i.e., HasVAListArg==true), we add a
969 // special check to see if the format string is a function parameter
970 // of the function calling the printf function. If the function
971 // has an attribute indicating it is a printf-like function, then we
972 // should suppress warnings concerning non-literals being used in a call
973 // to a vprintf function. For example:
974 //
975 // void
976 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
977 // va_list ap;
978 // va_start(ap, fmt);
979 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
980 // ...
981 //
982 //
983 // FIXME: We don't have full attribute support yet, so just check to see
984 // if the argument is a DeclRefExpr that references a parameter. We'll
985 // add proper support for checking the attribute later.
986 if (HasVAListArg)
987 if (isa<ParmVarDecl>(VD))
988 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Ted Kremenek082d9362009-03-20 21:35:28 +0000991 return false;
992 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000993
Anders Carlsson8f031b32009-06-27 04:05:33 +0000994 case Stmt::CallExprClass: {
995 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000996 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000997 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
998 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
999 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001000 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001001 unsigned ArgIndex = FA->getFormatIdx();
1002 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001003
1004 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001005 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001006 }
1007 }
1008 }
1009 }
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Anders Carlsson8f031b32009-06-27 04:05:33 +00001011 return false;
1012 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001013 case Stmt::ObjCStringLiteralClass:
1014 case Stmt::StringLiteralClass: {
1015 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Ted Kremenek082d9362009-03-20 21:35:28 +00001017 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001018 StrE = ObjCFExpr->getString();
1019 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001020 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001021
Ted Kremenekd30ef872009-01-12 23:09:09 +00001022 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001023 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1024 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001025 return true;
1026 }
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Ted Kremenekd30ef872009-01-12 23:09:09 +00001028 return false;
1029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Ted Kremenek082d9362009-03-20 21:35:28 +00001031 default:
1032 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001033 }
1034}
1035
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001036void
Mike Stump1eb44332009-09-09 15:08:12 +00001037Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001038 const Expr * const *ExprArgs,
1039 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001040 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1041 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001042 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001043 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001044 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001045 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001046 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001047 }
1048}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001049
Ted Kremenek826a3452010-07-16 02:11:22 +00001050/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1051/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001052void
Ted Kremenek826a3452010-07-16 02:11:22 +00001053Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1054 unsigned format_idx, unsigned firstDataArg,
1055 bool isPrintf) {
1056
Ted Kremenek082d9362009-03-20 21:35:28 +00001057 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001058
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001059 // The way the format attribute works in GCC, the implicit this argument
1060 // of member functions is counted. However, it doesn't appear in our own
1061 // lists, so decrement format_idx in that case.
1062 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001063 const CXXMethodDecl *method_decl =
1064 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1065 if (method_decl && method_decl->isInstance()) {
1066 // Catch a format attribute mistakenly referring to the object argument.
1067 if (format_idx == 0)
1068 return;
1069 --format_idx;
1070 if(firstDataArg != 0)
1071 --firstDataArg;
1072 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001073 }
1074
Ted Kremenek826a3452010-07-16 02:11:22 +00001075 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001076 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001077 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001078 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001079 return;
1080 }
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Ted Kremenek082d9362009-03-20 21:35:28 +00001082 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Chris Lattner59907c42007-08-10 20:18:51 +00001084 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001085 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001086 // Dynamically generated format strings are difficult to
1087 // automatically vet at compile time. Requiring that format strings
1088 // are string literals: (1) permits the checking of format strings by
1089 // the compiler and thereby (2) can practically remove the source of
1090 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001091
Mike Stump1eb44332009-09-09 15:08:12 +00001092 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001093 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001094 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001095 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001096 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001097 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001098 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001099
Chris Lattner655f1412009-04-29 04:59:47 +00001100 // If there are no arguments specified, warn with -Wformat-security, otherwise
1101 // warn only with -Wformat-nonliteral.
1102 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001103 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001104 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001105 << OrigFormatExpr->getSourceRange();
1106 else
Mike Stump1eb44332009-09-09 15:08:12 +00001107 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001108 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001109 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001110}
Ted Kremenek71895b92007-08-14 17:39:48 +00001111
Ted Kremeneke0e53132010-01-28 23:39:18 +00001112namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001113class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1114protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001115 Sema &S;
1116 const StringLiteral *FExpr;
1117 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001118 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001119 const unsigned NumDataArgs;
1120 const bool IsObjCLiteral;
1121 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001122 const bool HasVAListArg;
1123 const CallExpr *TheCall;
1124 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001125 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001126 bool usesPositionalArgs;
1127 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001128public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001129 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001130 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001131 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001132 const char *beg, bool hasVAListArg,
1133 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001134 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001135 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001136 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001137 IsObjCLiteral(isObjCLiteral), Beg(beg),
1138 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001139 TheCall(theCall), FormatIdx(formatIdx),
1140 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001141 CoveredArgs.resize(numDataArgs);
1142 CoveredArgs.reset();
1143 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001144
Ted Kremenek07d161f2010-01-29 01:50:07 +00001145 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001146
Ted Kremenek826a3452010-07-16 02:11:22 +00001147 void HandleIncompleteSpecifier(const char *startSpecifier,
1148 unsigned specifierLen);
1149
Ted Kremenekefaff192010-02-27 01:41:03 +00001150 virtual void HandleInvalidPosition(const char *startSpecifier,
1151 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001152 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001153
1154 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1155
Ted Kremeneke0e53132010-01-28 23:39:18 +00001156 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001157
Ted Kremenek826a3452010-07-16 02:11:22 +00001158protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001159 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1160 const char *startSpec,
1161 unsigned specifierLen,
1162 const char *csStart, unsigned csLen);
1163
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001164 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001165 CharSourceRange getSpecifierRange(const char *startSpecifier,
1166 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001167 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001168
Ted Kremenek0d277352010-01-29 01:06:55 +00001169 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001170
1171 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1172 const analyze_format_string::ConversionSpecifier &CS,
1173 const char *startSpecifier, unsigned specifierLen,
1174 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001175};
1176}
1177
Ted Kremenek826a3452010-07-16 02:11:22 +00001178SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001179 return OrigFormatExpr->getSourceRange();
1180}
1181
Ted Kremenek826a3452010-07-16 02:11:22 +00001182CharSourceRange CheckFormatHandler::
1183getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001184 SourceLocation Start = getLocationOfByte(startSpecifier);
1185 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1186
1187 // Advance the end SourceLocation by one due to half-open ranges.
1188 End = End.getFileLocWithOffset(1);
1189
1190 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001191}
1192
Ted Kremenek826a3452010-07-16 02:11:22 +00001193SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001194 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001195}
1196
Ted Kremenek826a3452010-07-16 02:11:22 +00001197void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1198 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001199 SourceLocation Loc = getLocationOfByte(startSpecifier);
1200 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001201 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001202}
1203
Ted Kremenekefaff192010-02-27 01:41:03 +00001204void
Ted Kremenek826a3452010-07-16 02:11:22 +00001205CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1206 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001207 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001208 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1209 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001210}
1211
Ted Kremenek826a3452010-07-16 02:11:22 +00001212void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001213 unsigned posLen) {
1214 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001215 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1216 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001217}
1218
Ted Kremenek826a3452010-07-16 02:11:22 +00001219void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001220 if (!IsObjCLiteral) {
1221 // The presence of a null character is likely an error.
1222 S.Diag(getLocationOfByte(nullCharacter),
1223 diag::warn_printf_format_string_contains_null_char)
1224 << getFormatStringRange();
1225 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001226}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001227
Ted Kremenek826a3452010-07-16 02:11:22 +00001228const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1229 return TheCall->getArg(FirstDataArg + i);
1230}
1231
1232void CheckFormatHandler::DoneProcessing() {
1233 // Does the number of data arguments exceed the number of
1234 // format conversions in the format string?
1235 if (!HasVAListArg) {
1236 // Find any arguments that weren't covered.
1237 CoveredArgs.flip();
1238 signed notCoveredArg = CoveredArgs.find_first();
1239 if (notCoveredArg >= 0) {
1240 assert((unsigned)notCoveredArg < NumDataArgs);
1241 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1242 diag::warn_printf_data_arg_not_used)
1243 << getFormatStringRange();
1244 }
1245 }
1246}
1247
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001248bool
1249CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1250 SourceLocation Loc,
1251 const char *startSpec,
1252 unsigned specifierLen,
1253 const char *csStart,
1254 unsigned csLen) {
1255
1256 bool keepGoing = true;
1257 if (argIndex < NumDataArgs) {
1258 // Consider the argument coverered, even though the specifier doesn't
1259 // make sense.
1260 CoveredArgs.set(argIndex);
1261 }
1262 else {
1263 // If argIndex exceeds the number of data arguments we
1264 // don't issue a warning because that is just a cascade of warnings (and
1265 // they may have intended '%%' anyway). We don't want to continue processing
1266 // the format string after this point, however, as we will like just get
1267 // gibberish when trying to match arguments.
1268 keepGoing = false;
1269 }
1270
1271 S.Diag(Loc, diag::warn_format_invalid_conversion)
1272 << llvm::StringRef(csStart, csLen)
1273 << getSpecifierRange(startSpec, specifierLen);
1274
1275 return keepGoing;
1276}
1277
Ted Kremenek666a1972010-07-26 19:45:42 +00001278bool
1279CheckFormatHandler::CheckNumArgs(
1280 const analyze_format_string::FormatSpecifier &FS,
1281 const analyze_format_string::ConversionSpecifier &CS,
1282 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1283
1284 if (argIndex >= NumDataArgs) {
1285 if (FS.usesPositionalArg()) {
1286 S.Diag(getLocationOfByte(CS.getStart()),
1287 diag::warn_printf_positional_arg_exceeds_data_args)
1288 << (argIndex+1) << NumDataArgs
1289 << getSpecifierRange(startSpecifier, specifierLen);
1290 }
1291 else {
1292 S.Diag(getLocationOfByte(CS.getStart()),
1293 diag::warn_printf_insufficient_data_args)
1294 << getSpecifierRange(startSpecifier, specifierLen);
1295 }
1296
1297 return false;
1298 }
1299 return true;
1300}
1301
Ted Kremenek826a3452010-07-16 02:11:22 +00001302//===--- CHECK: Printf format string checking ------------------------------===//
1303
1304namespace {
1305class CheckPrintfHandler : public CheckFormatHandler {
1306public:
1307 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1308 const Expr *origFormatExpr, unsigned firstDataArg,
1309 unsigned numDataArgs, bool isObjCLiteral,
1310 const char *beg, bool hasVAListArg,
1311 const CallExpr *theCall, unsigned formatIdx)
1312 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1313 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1314 theCall, formatIdx) {}
1315
1316
1317 bool HandleInvalidPrintfConversionSpecifier(
1318 const analyze_printf::PrintfSpecifier &FS,
1319 const char *startSpecifier,
1320 unsigned specifierLen);
1321
1322 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1323 const char *startSpecifier,
1324 unsigned specifierLen);
1325
1326 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1327 const char *startSpecifier, unsigned specifierLen);
1328 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1329 const analyze_printf::OptionalAmount &Amt,
1330 unsigned type,
1331 const char *startSpecifier, unsigned specifierLen);
1332 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1333 const analyze_printf::OptionalFlag &flag,
1334 const char *startSpecifier, unsigned specifierLen);
1335 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1336 const analyze_printf::OptionalFlag &ignoredFlag,
1337 const analyze_printf::OptionalFlag &flag,
1338 const char *startSpecifier, unsigned specifierLen);
1339};
1340}
1341
1342bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1343 const analyze_printf::PrintfSpecifier &FS,
1344 const char *startSpecifier,
1345 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001346 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001347 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001348
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001349 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1350 getLocationOfByte(CS.getStart()),
1351 startSpecifier, specifierLen,
1352 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001353}
1354
Ted Kremenek826a3452010-07-16 02:11:22 +00001355bool CheckPrintfHandler::HandleAmount(
1356 const analyze_format_string::OptionalAmount &Amt,
1357 unsigned k, const char *startSpecifier,
1358 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001359
1360 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001361 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001362 unsigned argIndex = Amt.getArgIndex();
1363 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001364 S.Diag(getLocationOfByte(Amt.getStart()),
1365 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001366 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001367 // Don't do any more checking. We will just emit
1368 // spurious errors.
1369 return false;
1370 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001371
Ted Kremenek0d277352010-01-29 01:06:55 +00001372 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001373 // Although not in conformance with C99, we also allow the argument to be
1374 // an 'unsigned int' as that is a reasonably safe case. GCC also
1375 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001376 CoveredArgs.set(argIndex);
1377 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001378 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001379
1380 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1381 assert(ATR.isValid());
1382
1383 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001384 S.Diag(getLocationOfByte(Amt.getStart()),
1385 diag::warn_printf_asterisk_wrong_type)
1386 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001387 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001388 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001389 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001390 // Don't do any more checking. We will just emit
1391 // spurious errors.
1392 return false;
1393 }
1394 }
1395 }
1396 return true;
1397}
Ted Kremenek0d277352010-01-29 01:06:55 +00001398
Tom Caree4ee9662010-06-17 19:00:27 +00001399void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001400 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001401 const analyze_printf::OptionalAmount &Amt,
1402 unsigned type,
1403 const char *startSpecifier,
1404 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001405 const analyze_printf::PrintfConversionSpecifier &CS =
1406 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001407 switch (Amt.getHowSpecified()) {
1408 case analyze_printf::OptionalAmount::Constant:
1409 S.Diag(getLocationOfByte(Amt.getStart()),
1410 diag::warn_printf_nonsensical_optional_amount)
1411 << type
1412 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001413 << getSpecifierRange(startSpecifier, specifierLen)
1414 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001415 Amt.getConstantLength()));
1416 break;
1417
1418 default:
1419 S.Diag(getLocationOfByte(Amt.getStart()),
1420 diag::warn_printf_nonsensical_optional_amount)
1421 << type
1422 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001423 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001424 break;
1425 }
1426}
1427
Ted Kremenek826a3452010-07-16 02:11:22 +00001428void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001429 const analyze_printf::OptionalFlag &flag,
1430 const char *startSpecifier,
1431 unsigned specifierLen) {
1432 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001433 const analyze_printf::PrintfConversionSpecifier &CS =
1434 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001435 S.Diag(getLocationOfByte(flag.getPosition()),
1436 diag::warn_printf_nonsensical_flag)
1437 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001438 << getSpecifierRange(startSpecifier, specifierLen)
1439 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001440}
1441
1442void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001443 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001444 const analyze_printf::OptionalFlag &ignoredFlag,
1445 const analyze_printf::OptionalFlag &flag,
1446 const char *startSpecifier,
1447 unsigned specifierLen) {
1448 // Warn about ignored flag with a fixit removal.
1449 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1450 diag::warn_printf_ignored_flag)
1451 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001452 << getSpecifierRange(startSpecifier, specifierLen)
1453 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001454 ignoredFlag.getPosition(), 1));
1455}
1456
Ted Kremeneke0e53132010-01-28 23:39:18 +00001457bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001458CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001459 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001460 const char *startSpecifier,
1461 unsigned specifierLen) {
1462
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001463 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001464 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001465 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001466
Ted Kremenekbaa40062010-07-19 22:01:06 +00001467 if (FS.consumesDataArgument()) {
1468 if (atFirstArg) {
1469 atFirstArg = false;
1470 usesPositionalArgs = FS.usesPositionalArg();
1471 }
1472 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1473 // Cannot mix-and-match positional and non-positional arguments.
1474 S.Diag(getLocationOfByte(CS.getStart()),
1475 diag::warn_format_mix_positional_nonpositional_args)
1476 << getSpecifierRange(startSpecifier, specifierLen);
1477 return false;
1478 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001479 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001480
Ted Kremenekefaff192010-02-27 01:41:03 +00001481 // First check if the field width, precision, and conversion specifier
1482 // have matching data arguments.
1483 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1484 startSpecifier, specifierLen)) {
1485 return false;
1486 }
1487
1488 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1489 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001490 return false;
1491 }
1492
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001493 if (!CS.consumesDataArgument()) {
1494 // FIXME: Technically specifying a precision or field width here
1495 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001496 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001497 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001498
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001499 // Consume the argument.
1500 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001501 if (argIndex < NumDataArgs) {
1502 // The check to see if the argIndex is valid will come later.
1503 // We set the bit here because we may exit early from this
1504 // function if we encounter some other error.
1505 CoveredArgs.set(argIndex);
1506 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001507
1508 // Check for using an Objective-C specific conversion specifier
1509 // in a non-ObjC literal.
1510 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001511 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1512 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001513 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001514
Tom Caree4ee9662010-06-17 19:00:27 +00001515 // Check for invalid use of field width
1516 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001517 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001518 startSpecifier, specifierLen);
1519 }
1520
1521 // Check for invalid use of precision
1522 if (!FS.hasValidPrecision()) {
1523 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1524 startSpecifier, specifierLen);
1525 }
1526
1527 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001528 if (!FS.hasValidThousandsGroupingPrefix())
1529 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001530 if (!FS.hasValidLeadingZeros())
1531 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1532 if (!FS.hasValidPlusPrefix())
1533 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001534 if (!FS.hasValidSpacePrefix())
1535 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001536 if (!FS.hasValidAlternativeForm())
1537 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1538 if (!FS.hasValidLeftJustified())
1539 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1540
1541 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001542 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1543 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1544 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001545 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1546 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1547 startSpecifier, specifierLen);
1548
1549 // Check the length modifier is valid with the given conversion specifier.
1550 const LengthModifier &LM = FS.getLengthModifier();
1551 if (!FS.hasValidLengthModifier())
1552 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001553 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001554 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001555 << getSpecifierRange(startSpecifier, specifierLen)
1556 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001557 LM.getLength()));
1558
1559 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001560 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001561 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001562 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001563 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001564 // Continue checking the other format specifiers.
1565 return true;
1566 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001567
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001568 // The remaining checks depend on the data arguments.
1569 if (HasVAListArg)
1570 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001571
Ted Kremenek666a1972010-07-26 19:45:42 +00001572 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001573 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001574
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001575 // Now type check the data expression that matches the
1576 // format specifier.
1577 const Expr *Ex = getDataArg(argIndex);
1578 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1579 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1580 // Check if we didn't match because of an implicit cast from a 'char'
1581 // or 'short' to an 'int'. This is done because printf is a varargs
1582 // function.
1583 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001584 if (ICE->getType() == S.Context.IntTy) {
1585 // All further checking is done on the subexpression.
1586 Ex = ICE->getSubExpr();
1587 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001588 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001589 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001590
1591 // We may be able to offer a FixItHint if it is a supported type.
1592 PrintfSpecifier fixedFS = FS;
1593 bool success = fixedFS.fixType(Ex->getType());
1594
1595 if (success) {
1596 // Get the fix string from the fixed format specifier
1597 llvm::SmallString<128> buf;
1598 llvm::raw_svector_ostream os(buf);
1599 fixedFS.toString(os);
1600
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001601 // FIXME: getRepresentativeType() perhaps should return a string
1602 // instead of a QualType to better handle when the representative
1603 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001604 S.Diag(getLocationOfByte(CS.getStart()),
1605 diag::warn_printf_conversion_argument_type_mismatch)
1606 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1607 << getSpecifierRange(startSpecifier, specifierLen)
1608 << Ex->getSourceRange()
1609 << FixItHint::CreateReplacement(
1610 getSpecifierRange(startSpecifier, specifierLen),
1611 os.str());
1612 }
1613 else {
1614 S.Diag(getLocationOfByte(CS.getStart()),
1615 diag::warn_printf_conversion_argument_type_mismatch)
1616 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1617 << getSpecifierRange(startSpecifier, specifierLen)
1618 << Ex->getSourceRange();
1619 }
1620 }
1621
Ted Kremeneke0e53132010-01-28 23:39:18 +00001622 return true;
1623}
1624
Ted Kremenek826a3452010-07-16 02:11:22 +00001625//===--- CHECK: Scanf format string checking ------------------------------===//
1626
1627namespace {
1628class CheckScanfHandler : public CheckFormatHandler {
1629public:
1630 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1631 const Expr *origFormatExpr, unsigned firstDataArg,
1632 unsigned numDataArgs, bool isObjCLiteral,
1633 const char *beg, bool hasVAListArg,
1634 const CallExpr *theCall, unsigned formatIdx)
1635 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1636 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1637 theCall, formatIdx) {}
1638
1639 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1640 const char *startSpecifier,
1641 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001642
1643 bool HandleInvalidScanfConversionSpecifier(
1644 const analyze_scanf::ScanfSpecifier &FS,
1645 const char *startSpecifier,
1646 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001647
1648 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001649};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001650}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001651
Ted Kremenekb7c21012010-07-16 18:28:03 +00001652void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1653 const char *end) {
1654 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1655 << getSpecifierRange(start, end - start);
1656}
1657
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001658bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1659 const analyze_scanf::ScanfSpecifier &FS,
1660 const char *startSpecifier,
1661 unsigned specifierLen) {
1662
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001663 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001664 FS.getConversionSpecifier();
1665
1666 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1667 getLocationOfByte(CS.getStart()),
1668 startSpecifier, specifierLen,
1669 CS.getStart(), CS.getLength());
1670}
1671
Ted Kremenek826a3452010-07-16 02:11:22 +00001672bool CheckScanfHandler::HandleScanfSpecifier(
1673 const analyze_scanf::ScanfSpecifier &FS,
1674 const char *startSpecifier,
1675 unsigned specifierLen) {
1676
1677 using namespace analyze_scanf;
1678 using namespace analyze_format_string;
1679
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001680 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001681
Ted Kremenekbaa40062010-07-19 22:01:06 +00001682 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1683 // be used to decide if we are using positional arguments consistently.
1684 if (FS.consumesDataArgument()) {
1685 if (atFirstArg) {
1686 atFirstArg = false;
1687 usesPositionalArgs = FS.usesPositionalArg();
1688 }
1689 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1690 // Cannot mix-and-match positional and non-positional arguments.
1691 S.Diag(getLocationOfByte(CS.getStart()),
1692 diag::warn_format_mix_positional_nonpositional_args)
1693 << getSpecifierRange(startSpecifier, specifierLen);
1694 return false;
1695 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001696 }
1697
1698 // Check if the field with is non-zero.
1699 const OptionalAmount &Amt = FS.getFieldWidth();
1700 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1701 if (Amt.getConstantAmount() == 0) {
1702 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1703 Amt.getConstantLength());
1704 S.Diag(getLocationOfByte(Amt.getStart()),
1705 diag::warn_scanf_nonzero_width)
1706 << R << FixItHint::CreateRemoval(R);
1707 }
1708 }
1709
1710 if (!FS.consumesDataArgument()) {
1711 // FIXME: Technically specifying a precision or field width here
1712 // makes no sense. Worth issuing a warning at some point.
1713 return true;
1714 }
1715
1716 // Consume the argument.
1717 unsigned argIndex = FS.getArgIndex();
1718 if (argIndex < NumDataArgs) {
1719 // The check to see if the argIndex is valid will come later.
1720 // We set the bit here because we may exit early from this
1721 // function if we encounter some other error.
1722 CoveredArgs.set(argIndex);
1723 }
1724
Ted Kremenek1e51c202010-07-20 20:04:47 +00001725 // Check the length modifier is valid with the given conversion specifier.
1726 const LengthModifier &LM = FS.getLengthModifier();
1727 if (!FS.hasValidLengthModifier()) {
1728 S.Diag(getLocationOfByte(LM.getStart()),
1729 diag::warn_format_nonsensical_length)
1730 << LM.toString() << CS.toString()
1731 << getSpecifierRange(startSpecifier, specifierLen)
1732 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1733 LM.getLength()));
1734 }
1735
Ted Kremenek826a3452010-07-16 02:11:22 +00001736 // The remaining checks depend on the data arguments.
1737 if (HasVAListArg)
1738 return true;
1739
Ted Kremenek666a1972010-07-26 19:45:42 +00001740 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001741 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001742
1743 // FIXME: Check that the argument type matches the format specifier.
1744
1745 return true;
1746}
1747
1748void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001749 const Expr *OrigFormatExpr,
1750 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001751 unsigned format_idx, unsigned firstDataArg,
1752 bool isPrintf) {
1753
Ted Kremeneke0e53132010-01-28 23:39:18 +00001754 // CHECK: is the format string a wide literal?
1755 if (FExpr->isWide()) {
1756 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001757 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001758 << OrigFormatExpr->getSourceRange();
1759 return;
1760 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001761
Ted Kremeneke0e53132010-01-28 23:39:18 +00001762 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001763 llvm::StringRef StrRef = FExpr->getString();
1764 const char *Str = StrRef.data();
1765 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001766
Ted Kremeneke0e53132010-01-28 23:39:18 +00001767 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001768 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001769 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001770 << OrigFormatExpr->getSourceRange();
1771 return;
1772 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001773
1774 if (isPrintf) {
1775 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1776 TheCall->getNumArgs() - firstDataArg,
1777 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1778 HasVAListArg, TheCall, format_idx);
1779
1780 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1781 H.DoneProcessing();
1782 }
1783 else {
1784 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1785 TheCall->getNumArgs() - firstDataArg,
1786 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1787 HasVAListArg, TheCall, format_idx);
1788
1789 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1790 H.DoneProcessing();
1791 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001792}
1793
Ted Kremenek06de2762007-08-17 16:46:58 +00001794//===--- CHECK: Return Address of Stack Variable --------------------------===//
1795
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001796static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1797static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001798
1799/// CheckReturnStackAddr - Check if a return statement returns the address
1800/// of a stack variable.
1801void
1802Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1803 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001805 Expr *stackE = 0;
1806 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1807
1808 // Perform checking for returned stack addresses, local blocks,
1809 // label addresses or references to temporaries.
Steve Naroffdd972f22008-09-05 22:11:13 +00001810 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001811 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001812 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001813 stackE = EvalVal(RetValExp, refVars);
1814 }
1815
1816 if (stackE == 0)
1817 return; // Nothing suspicious was found.
1818
1819 SourceLocation diagLoc;
1820 SourceRange diagRange;
1821 if (refVars.empty()) {
1822 diagLoc = stackE->getLocStart();
1823 diagRange = stackE->getSourceRange();
1824 } else {
1825 // We followed through a reference variable. 'stackE' contains the
1826 // problematic expression but we will warn at the return statement pointing
1827 // at the reference variable. We will later display the "trail" of
1828 // reference variables using notes.
1829 diagLoc = refVars[0]->getLocStart();
1830 diagRange = refVars[0]->getSourceRange();
1831 }
1832
1833 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1834 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1835 : diag::warn_ret_stack_addr)
1836 << DR->getDecl()->getDeclName() << diagRange;
1837 } else if (isa<BlockExpr>(stackE)) { // local block.
1838 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1839 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1840 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1841 } else { // local temporary.
1842 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1843 : diag::warn_ret_local_temp_addr)
1844 << diagRange;
1845 }
1846
1847 // Display the "trail" of reference variables that we followed until we
1848 // found the problematic expression using notes.
1849 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1850 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1851 // If this var binds to another reference var, show the range of the next
1852 // var, otherwise the var binds to the problematic expression, in which case
1853 // show the range of the expression.
1854 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1855 : stackE->getSourceRange();
1856 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1857 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00001858 }
1859}
1860
1861/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1862/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001863/// to a location on the stack, a local block, an address of a label, or a
1864/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00001865/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001866/// encounter a subexpression that (1) clearly does not lead to one of the
1867/// above problematic expressions (2) is something we cannot determine leads to
1868/// a problematic expression based on such local checking.
1869///
1870/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1871/// the expression that they point to. Such variables are added to the
1872/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00001873///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001874/// EvalAddr processes expressions that are pointers that are used as
1875/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001876/// At the base case of the recursion is a check for the above problematic
1877/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00001878///
1879/// This implementation handles:
1880///
1881/// * pointer-to-pointer casts
1882/// * implicit conversions from array references to pointers
1883/// * taking the address of fields
1884/// * arbitrary interplay between "&" and "*" operators
1885/// * pointer arithmetic from an address of a stack variable
1886/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001887static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1888 if (E->isTypeDependent())
1889 return NULL;
1890
Ted Kremenek06de2762007-08-17 16:46:58 +00001891 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001892 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001893 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001894 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001895 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Peter Collingbournef111d932011-04-15 00:35:48 +00001897 E = E->IgnoreParens();
1898
Ted Kremenek06de2762007-08-17 16:46:58 +00001899 // Our "symbolic interpreter" is just a dispatch off the currently
1900 // viewed AST node. We then recursively traverse the AST by calling
1901 // EvalAddr and EvalVal appropriately.
1902 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001903 case Stmt::DeclRefExprClass: {
1904 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1905
1906 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1907 // If this is a reference variable, follow through to the expression that
1908 // it points to.
1909 if (V->hasLocalStorage() &&
1910 V->getType()->isReferenceType() && V->hasInit()) {
1911 // Add the reference variable to the "trail".
1912 refVars.push_back(DR);
1913 return EvalAddr(V->getInit(), refVars);
1914 }
1915
1916 return NULL;
1917 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001918
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001919 case Stmt::UnaryOperatorClass: {
1920 // The only unary operator that make sense to handle here
1921 // is AddrOf. All others don't make sense as pointers.
1922 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001923
John McCall2de56d12010-08-25 11:45:40 +00001924 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001925 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001926 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001927 return NULL;
1928 }
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001930 case Stmt::BinaryOperatorClass: {
1931 // Handle pointer arithmetic. All other binary operators are not valid
1932 // in this context.
1933 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001934 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001935
John McCall2de56d12010-08-25 11:45:40 +00001936 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001937 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001939 Expr *Base = B->getLHS();
1940
1941 // Determine which argument is the real pointer base. It could be
1942 // the RHS argument instead of the LHS.
1943 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001945 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001946 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001947 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001948
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001949 // For conditional operators we need to see if either the LHS or RHS are
1950 // valid DeclRefExpr*s. If one of them is valid, we return it.
1951 case Stmt::ConditionalOperatorClass: {
1952 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001954 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001955 if (Expr *lhsExpr = C->getLHS()) {
1956 // In C++, we can have a throw-expression, which has 'void' type.
1957 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001958 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001959 return LHS;
1960 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001961
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001962 // In C++, we can have a throw-expression, which has 'void' type.
1963 if (C->getRHS()->getType()->isVoidType())
1964 return NULL;
1965
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001966 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001967 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001968
1969 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00001970 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001971 return E; // local block.
1972 return NULL;
1973
1974 case Stmt::AddrLabelExprClass:
1975 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Ted Kremenek54b52742008-08-07 00:49:01 +00001977 // For casts, we need to handle conversions from arrays to
1978 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001979 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001980 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001981 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001982 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001983 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Steve Naroffdd972f22008-09-05 22:11:13 +00001985 if (SubExpr->getType()->isPointerType() ||
1986 SubExpr->getType()->isBlockPointerType() ||
1987 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001988 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00001989 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001990 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001991 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001992 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001993 }
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001995 // C++ casts. For dynamic casts, static casts, and const casts, we
1996 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001997 // through the cast. In the case the dynamic cast doesn't fail (and
1998 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001999 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002000 // FIXME: The comment about is wrong; we're not always converting
2001 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002002 // handle references to objects.
2003 case Stmt::CXXStaticCastExprClass:
2004 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002005 case Stmt::CXXConstCastExprClass:
2006 case Stmt::CXXReinterpretCastExprClass: {
2007 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002008 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002009 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002010 else
2011 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002012 }
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002014 // Everything else: we simply don't reason about them.
2015 default:
2016 return NULL;
2017 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002018}
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Ted Kremenek06de2762007-08-17 16:46:58 +00002020
2021/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2022/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002023static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002024do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002025 // We should only be called for evaluating non-pointer expressions, or
2026 // expressions with a pointer type that are not used as references but instead
2027 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Ted Kremenek06de2762007-08-17 16:46:58 +00002029 // Our "symbolic interpreter" is just a dispatch off the currently
2030 // viewed AST node. We then recursively traverse the AST by calling
2031 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002032
2033 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002034 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002035 case Stmt::ImplicitCastExprClass: {
2036 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002037 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002038 E = IE->getSubExpr();
2039 continue;
2040 }
2041 return NULL;
2042 }
2043
Douglas Gregora2813ce2009-10-23 18:54:35 +00002044 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002045 // When we hit a DeclRefExpr we are looking at code that refers to a
2046 // variable's name. If it's not a reference variable we check if it has
2047 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002048 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Ted Kremenek06de2762007-08-17 16:46:58 +00002050 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002051 if (V->hasLocalStorage()) {
2052 if (!V->getType()->isReferenceType())
2053 return DR;
2054
2055 // Reference variable, follow through to the expression that
2056 // it points to.
2057 if (V->hasInit()) {
2058 // Add the reference variable to the "trail".
2059 refVars.push_back(DR);
2060 return EvalVal(V->getInit(), refVars);
2061 }
2062 }
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Ted Kremenek06de2762007-08-17 16:46:58 +00002064 return NULL;
2065 }
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Ted Kremenek06de2762007-08-17 16:46:58 +00002067 case Stmt::UnaryOperatorClass: {
2068 // The only unary operator that make sense to handle here
2069 // is Deref. All others don't resolve to a "name." This includes
2070 // handling all sorts of rvalues passed to a unary operator.
2071 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002072
John McCall2de56d12010-08-25 11:45:40 +00002073 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002074 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002075
2076 return NULL;
2077 }
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Ted Kremenek06de2762007-08-17 16:46:58 +00002079 case Stmt::ArraySubscriptExprClass: {
2080 // Array subscripts are potential references to data on the stack. We
2081 // retrieve the DeclRefExpr* for the array variable if it indeed
2082 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002083 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002084 }
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Ted Kremenek06de2762007-08-17 16:46:58 +00002086 case Stmt::ConditionalOperatorClass: {
2087 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002088 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002089 ConditionalOperator *C = cast<ConditionalOperator>(E);
2090
Anders Carlsson39073232007-11-30 19:04:31 +00002091 // Handle the GNU extension for missing LHS.
2092 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002093 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002094 return LHS;
2095
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002096 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002097 }
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Ted Kremenek06de2762007-08-17 16:46:58 +00002099 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002100 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002101 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Ted Kremenek06de2762007-08-17 16:46:58 +00002103 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002104 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002105 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002106
2107 // Check whether the member type is itself a reference, in which case
2108 // we're not going to refer to the member, but to what the member refers to.
2109 if (M->getMemberDecl()->getType()->isReferenceType())
2110 return NULL;
2111
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002112 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Ted Kremenek06de2762007-08-17 16:46:58 +00002115 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002116 // Check that we don't return or take the address of a reference to a
2117 // temporary. This is only useful in C++.
2118 if (!E->isTypeDependent() && E->isRValue())
2119 return E;
2120
2121 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002122 return NULL;
2123 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002124} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002125}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002126
2127//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2128
2129/// Check for comparisons of floating point operands using != and ==.
2130/// Issue a warning if these are no self-comparisons, as they are not likely
2131/// to do what the programmer intended.
2132void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2133 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002134
John McCallf6a16482010-12-04 03:47:34 +00002135 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2136 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002137
2138 // Special case: check for x == x (which is OK).
2139 // Do not emit warnings for such cases.
2140 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2141 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2142 if (DRL->getDecl() == DRR->getDecl())
2143 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002144
2145
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002146 // Special case: check for comparisons against literals that can be exactly
2147 // represented by APFloat. In such cases, do not emit a warning. This
2148 // is a heuristic: often comparison against such literals are used to
2149 // detect if a value in a variable has not changed. This clearly can
2150 // lead to false negatives.
2151 if (EmitWarning) {
2152 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2153 if (FLL->isExact())
2154 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002155 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002156 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2157 if (FLR->isExact())
2158 EmitWarning = false;
2159 }
2160 }
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002162 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002163 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002164 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002165 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002166 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Sebastian Redl0eb23302009-01-19 00:08:26 +00002168 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002169 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002170 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002171 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002173 // Emit the diagnostic.
2174 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002175 Diag(loc, diag::warn_floatingpoint_eq)
2176 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002177}
John McCallba26e582010-01-04 23:21:16 +00002178
John McCallf2370c92010-01-06 05:24:50 +00002179//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2180//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002181
John McCallf2370c92010-01-06 05:24:50 +00002182namespace {
John McCallba26e582010-01-04 23:21:16 +00002183
John McCallf2370c92010-01-06 05:24:50 +00002184/// Structure recording the 'active' range of an integer-valued
2185/// expression.
2186struct IntRange {
2187 /// The number of bits active in the int.
2188 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002189
John McCallf2370c92010-01-06 05:24:50 +00002190 /// True if the int is known not to have negative values.
2191 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002192
John McCallf2370c92010-01-06 05:24:50 +00002193 IntRange(unsigned Width, bool NonNegative)
2194 : Width(Width), NonNegative(NonNegative)
2195 {}
John McCallba26e582010-01-04 23:21:16 +00002196
John McCall1844a6e2010-11-10 23:38:19 +00002197 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002198 static IntRange forBoolType() {
2199 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002200 }
2201
John McCall1844a6e2010-11-10 23:38:19 +00002202 /// Returns the range of an opaque value of the given integral type.
2203 static IntRange forValueOfType(ASTContext &C, QualType T) {
2204 return forValueOfCanonicalType(C,
2205 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002206 }
2207
John McCall1844a6e2010-11-10 23:38:19 +00002208 /// Returns the range of an opaque value of a canonical integral type.
2209 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002210 assert(T->isCanonicalUnqualified());
2211
2212 if (const VectorType *VT = dyn_cast<VectorType>(T))
2213 T = VT->getElementType().getTypePtr();
2214 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2215 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002216
John McCall091f23f2010-11-09 22:22:12 +00002217 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002218 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2219 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002220 if (!Enum->isDefinition())
2221 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2222
John McCall323ed742010-05-06 08:58:33 +00002223 unsigned NumPositive = Enum->getNumPositiveBits();
2224 unsigned NumNegative = Enum->getNumNegativeBits();
2225
2226 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2227 }
John McCallf2370c92010-01-06 05:24:50 +00002228
2229 const BuiltinType *BT = cast<BuiltinType>(T);
2230 assert(BT->isInteger());
2231
2232 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2233 }
2234
John McCall1844a6e2010-11-10 23:38:19 +00002235 /// Returns the "target" range of a canonical integral type, i.e.
2236 /// the range of values expressible in the type.
2237 ///
2238 /// This matches forValueOfCanonicalType except that enums have the
2239 /// full range of their type, not the range of their enumerators.
2240 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2241 assert(T->isCanonicalUnqualified());
2242
2243 if (const VectorType *VT = dyn_cast<VectorType>(T))
2244 T = VT->getElementType().getTypePtr();
2245 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2246 T = CT->getElementType().getTypePtr();
2247 if (const EnumType *ET = dyn_cast<EnumType>(T))
2248 T = ET->getDecl()->getIntegerType().getTypePtr();
2249
2250 const BuiltinType *BT = cast<BuiltinType>(T);
2251 assert(BT->isInteger());
2252
2253 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2254 }
2255
2256 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002257 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002258 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002259 L.NonNegative && R.NonNegative);
2260 }
2261
John McCall1844a6e2010-11-10 23:38:19 +00002262 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002263 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002264 return IntRange(std::min(L.Width, R.Width),
2265 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002266 }
2267};
2268
2269IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2270 if (value.isSigned() && value.isNegative())
2271 return IntRange(value.getMinSignedBits(), false);
2272
2273 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002274 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002275
2276 // isNonNegative() just checks the sign bit without considering
2277 // signedness.
2278 return IntRange(value.getActiveBits(), true);
2279}
2280
John McCall0acc3112010-01-06 22:57:21 +00002281IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002282 unsigned MaxWidth) {
2283 if (result.isInt())
2284 return GetValueRange(C, result.getInt(), MaxWidth);
2285
2286 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002287 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2288 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2289 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2290 R = IntRange::join(R, El);
2291 }
John McCallf2370c92010-01-06 05:24:50 +00002292 return R;
2293 }
2294
2295 if (result.isComplexInt()) {
2296 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2297 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2298 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002299 }
2300
2301 // This can happen with lossless casts to intptr_t of "based" lvalues.
2302 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002303 // FIXME: The only reason we need to pass the type in here is to get
2304 // the sign right on this one case. It would be nice if APValue
2305 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002306 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002307 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002308}
John McCallf2370c92010-01-06 05:24:50 +00002309
2310/// Pseudo-evaluate the given integer expression, estimating the
2311/// range of values it might take.
2312///
2313/// \param MaxWidth - the width to which the value will be truncated
2314IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2315 E = E->IgnoreParens();
2316
2317 // Try a full evaluation first.
2318 Expr::EvalResult result;
2319 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002320 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002321
2322 // I think we only want to look through implicit casts here; if the
2323 // user has an explicit widening cast, we should treat the value as
2324 // being of the new, wider type.
2325 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002326 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002327 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2328
John McCall1844a6e2010-11-10 23:38:19 +00002329 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002330
John McCall2de56d12010-08-25 11:45:40 +00002331 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002332
John McCallf2370c92010-01-06 05:24:50 +00002333 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002334 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002335 return OutputTypeRange;
2336
2337 IntRange SubRange
2338 = GetExprRange(C, CE->getSubExpr(),
2339 std::min(MaxWidth, OutputTypeRange.Width));
2340
2341 // Bail out if the subexpr's range is as wide as the cast type.
2342 if (SubRange.Width >= OutputTypeRange.Width)
2343 return OutputTypeRange;
2344
2345 // Otherwise, we take the smaller width, and we're non-negative if
2346 // either the output type or the subexpr is.
2347 return IntRange(SubRange.Width,
2348 SubRange.NonNegative || OutputTypeRange.NonNegative);
2349 }
2350
2351 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2352 // If we can fold the condition, just take that operand.
2353 bool CondResult;
2354 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2355 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2356 : CO->getFalseExpr(),
2357 MaxWidth);
2358
2359 // Otherwise, conservatively merge.
2360 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2361 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2362 return IntRange::join(L, R);
2363 }
2364
2365 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2366 switch (BO->getOpcode()) {
2367
2368 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002369 case BO_LAnd:
2370 case BO_LOr:
2371 case BO_LT:
2372 case BO_GT:
2373 case BO_LE:
2374 case BO_GE:
2375 case BO_EQ:
2376 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002377 return IntRange::forBoolType();
2378
John McCallc0cd21d2010-02-23 19:22:29 +00002379 // The type of these compound assignments is the type of the LHS,
2380 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002381 case BO_MulAssign:
2382 case BO_DivAssign:
2383 case BO_RemAssign:
2384 case BO_AddAssign:
2385 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002386 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002387
John McCallf2370c92010-01-06 05:24:50 +00002388 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002389 case BO_PtrMemD:
2390 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002391 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002392
John McCall60fad452010-01-06 22:07:33 +00002393 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002394 case BO_And:
2395 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002396 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2397 GetExprRange(C, BO->getRHS(), MaxWidth));
2398
John McCallf2370c92010-01-06 05:24:50 +00002399 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002400 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002401 // ...except that we want to treat '1 << (blah)' as logically
2402 // positive. It's an important idiom.
2403 if (IntegerLiteral *I
2404 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2405 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002406 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002407 return IntRange(R.Width, /*NonNegative*/ true);
2408 }
2409 }
2410 // fallthrough
2411
John McCall2de56d12010-08-25 11:45:40 +00002412 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002413 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002414
John McCall60fad452010-01-06 22:07:33 +00002415 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002416 case BO_Shr:
2417 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002418 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2419
2420 // If the shift amount is a positive constant, drop the width by
2421 // that much.
2422 llvm::APSInt shift;
2423 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2424 shift.isNonNegative()) {
2425 unsigned zext = shift.getZExtValue();
2426 if (zext >= L.Width)
2427 L.Width = (L.NonNegative ? 0 : 1);
2428 else
2429 L.Width -= zext;
2430 }
2431
2432 return L;
2433 }
2434
2435 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002436 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002437 return GetExprRange(C, BO->getRHS(), MaxWidth);
2438
John McCall60fad452010-01-06 22:07:33 +00002439 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002440 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002441 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002442 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002443 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002444
John McCallf2370c92010-01-06 05:24:50 +00002445 default:
2446 break;
2447 }
2448
2449 // Treat every other operator as if it were closed on the
2450 // narrowest type that encompasses both operands.
2451 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2452 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2453 return IntRange::join(L, R);
2454 }
2455
2456 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2457 switch (UO->getOpcode()) {
2458 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002459 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002460 return IntRange::forBoolType();
2461
2462 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002463 case UO_Deref:
2464 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002465 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002466
2467 default:
2468 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2469 }
2470 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002471
2472 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002473 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002474 }
John McCallf2370c92010-01-06 05:24:50 +00002475
2476 FieldDecl *BitField = E->getBitField();
2477 if (BitField) {
2478 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2479 unsigned BitWidth = BitWidthAP.getZExtValue();
2480
2481 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2482 }
2483
John McCall1844a6e2010-11-10 23:38:19 +00002484 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002485}
John McCall51313c32010-01-04 23:31:57 +00002486
John McCall323ed742010-05-06 08:58:33 +00002487IntRange GetExprRange(ASTContext &C, Expr *E) {
2488 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2489}
2490
John McCall51313c32010-01-04 23:31:57 +00002491/// Checks whether the given value, which currently has the given
2492/// source semantics, has the same value when coerced through the
2493/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002494bool IsSameFloatAfterCast(const llvm::APFloat &value,
2495 const llvm::fltSemantics &Src,
2496 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002497 llvm::APFloat truncated = value;
2498
2499 bool ignored;
2500 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2501 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2502
2503 return truncated.bitwiseIsEqual(value);
2504}
2505
2506/// Checks whether the given value, which currently has the given
2507/// source semantics, has the same value when coerced through the
2508/// target semantics.
2509///
2510/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002511bool IsSameFloatAfterCast(const APValue &value,
2512 const llvm::fltSemantics &Src,
2513 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002514 if (value.isFloat())
2515 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2516
2517 if (value.isVector()) {
2518 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2519 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2520 return false;
2521 return true;
2522 }
2523
2524 assert(value.isComplexFloat());
2525 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2526 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2527}
2528
John McCallb4eb64d2010-10-08 02:01:28 +00002529void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002530
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002531static bool IsZero(Sema &S, Expr *E) {
2532 // Suppress cases where we are comparing against an enum constant.
2533 if (const DeclRefExpr *DR =
2534 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2535 if (isa<EnumConstantDecl>(DR->getDecl()))
2536 return false;
2537
2538 // Suppress cases where the '0' value is expanded from a macro.
2539 if (E->getLocStart().isMacroID())
2540 return false;
2541
John McCall323ed742010-05-06 08:58:33 +00002542 llvm::APSInt Value;
2543 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2544}
2545
John McCall372e1032010-10-06 00:25:24 +00002546static bool HasEnumType(Expr *E) {
2547 // Strip off implicit integral promotions.
2548 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002549 if (ICE->getCastKind() != CK_IntegralCast &&
2550 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002551 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002552 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002553 }
2554
2555 return E->getType()->isEnumeralType();
2556}
2557
John McCall323ed742010-05-06 08:58:33 +00002558void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002559 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002560 if (E->isValueDependent())
2561 return;
2562
John McCall2de56d12010-08-25 11:45:40 +00002563 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002564 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002565 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002566 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002567 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002568 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002569 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002570 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002571 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002572 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002573 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002574 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002575 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002576 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002577 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002578 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2579 }
2580}
2581
2582/// Analyze the operands of the given comparison. Implements the
2583/// fallback case from AnalyzeComparison.
2584void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002585 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2586 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002587}
John McCall51313c32010-01-04 23:31:57 +00002588
John McCallba26e582010-01-04 23:21:16 +00002589/// \brief Implements -Wsign-compare.
2590///
2591/// \param lex the left-hand expression
2592/// \param rex the right-hand expression
2593/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002594/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002595void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2596 // The type the comparison is being performed in.
2597 QualType T = E->getLHS()->getType();
2598 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2599 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002600
John McCall323ed742010-05-06 08:58:33 +00002601 // We don't do anything special if this isn't an unsigned integral
2602 // comparison: we're only interested in integral comparisons, and
2603 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002604 //
2605 // We also don't care about value-dependent expressions or expressions
2606 // whose result is a constant.
2607 if (!T->hasUnsignedIntegerRepresentation()
2608 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002609 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002610
John McCall323ed742010-05-06 08:58:33 +00002611 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2612 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002613
John McCall323ed742010-05-06 08:58:33 +00002614 // Check to see if one of the (unmodified) operands is of different
2615 // signedness.
2616 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002617 if (lex->getType()->hasSignedIntegerRepresentation()) {
2618 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002619 "unsigned comparison between two signed integer expressions?");
2620 signedOperand = lex;
2621 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002622 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002623 signedOperand = rex;
2624 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002625 } else {
John McCall323ed742010-05-06 08:58:33 +00002626 CheckTrivialUnsignedComparison(S, E);
2627 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002628 }
2629
John McCall323ed742010-05-06 08:58:33 +00002630 // Otherwise, calculate the effective range of the signed operand.
2631 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002632
John McCall323ed742010-05-06 08:58:33 +00002633 // Go ahead and analyze implicit conversions in the operands. Note
2634 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002635 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2636 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002637
John McCall323ed742010-05-06 08:58:33 +00002638 // If the signed range is non-negative, -Wsign-compare won't fire,
2639 // but we should still check for comparisons which are always true
2640 // or false.
2641 if (signedRange.NonNegative)
2642 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002643
2644 // For (in)equality comparisons, if the unsigned operand is a
2645 // constant which cannot collide with a overflowed signed operand,
2646 // then reinterpreting the signed operand as unsigned will not
2647 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002648 if (E->isEqualityOp()) {
2649 unsigned comparisonWidth = S.Context.getIntWidth(T);
2650 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002651
John McCall323ed742010-05-06 08:58:33 +00002652 // We should never be unable to prove that the unsigned operand is
2653 // non-negative.
2654 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2655
2656 if (unsignedRange.Width < comparisonWidth)
2657 return;
2658 }
2659
2660 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2661 << lex->getType() << rex->getType()
2662 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002663}
2664
John McCall15d7d122010-11-11 03:21:53 +00002665/// Analyzes an attempt to assign the given value to a bitfield.
2666///
2667/// Returns true if there was something fishy about the attempt.
2668bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2669 SourceLocation InitLoc) {
2670 assert(Bitfield->isBitField());
2671 if (Bitfield->isInvalidDecl())
2672 return false;
2673
John McCall91b60142010-11-11 05:33:51 +00002674 // White-list bool bitfields.
2675 if (Bitfield->getType()->isBooleanType())
2676 return false;
2677
Douglas Gregor46ff3032011-02-04 13:09:01 +00002678 // Ignore value- or type-dependent expressions.
2679 if (Bitfield->getBitWidth()->isValueDependent() ||
2680 Bitfield->getBitWidth()->isTypeDependent() ||
2681 Init->isValueDependent() ||
2682 Init->isTypeDependent())
2683 return false;
2684
John McCall15d7d122010-11-11 03:21:53 +00002685 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2686
2687 llvm::APSInt Width(32);
2688 Expr::EvalResult InitValue;
2689 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002690 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002691 !InitValue.Val.isInt())
2692 return false;
2693
2694 const llvm::APSInt &Value = InitValue.Val.getInt();
2695 unsigned OriginalWidth = Value.getBitWidth();
2696 unsigned FieldWidth = Width.getZExtValue();
2697
2698 if (OriginalWidth <= FieldWidth)
2699 return false;
2700
Jay Foad9f71a8f2010-12-07 08:25:34 +00002701 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002702
2703 // It's fairly common to write values into signed bitfields
2704 // that, if sign-extended, would end up becoming a different
2705 // value. We don't want to warn about that.
2706 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002707 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002708 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002709 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002710
2711 if (Value == TruncatedValue)
2712 return false;
2713
2714 std::string PrettyValue = Value.toString(10);
2715 std::string PrettyTrunc = TruncatedValue.toString(10);
2716
2717 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2718 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2719 << Init->getSourceRange();
2720
2721 return true;
2722}
2723
John McCallbeb22aa2010-11-09 23:24:47 +00002724/// Analyze the given simple or compound assignment for warning-worthy
2725/// operations.
2726void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2727 // Just recurse on the LHS.
2728 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2729
2730 // We want to recurse on the RHS as normal unless we're assigning to
2731 // a bitfield.
2732 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002733 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2734 E->getOperatorLoc())) {
2735 // Recurse, ignoring any implicit conversions on the RHS.
2736 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2737 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002738 }
2739 }
2740
2741 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2742}
2743
John McCall51313c32010-01-04 23:31:57 +00002744/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002745void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2746 SourceLocation CContext, unsigned diag) {
2747 S.Diag(E->getExprLoc(), diag)
2748 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2749}
2750
Chandler Carruthe1b02e02011-04-05 06:47:57 +00002751/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2752void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2753 unsigned diag) {
2754 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
2755}
2756
Chandler Carruthf65076e2011-04-10 08:36:24 +00002757/// Diagnose an implicit cast from a literal expression. Also attemps to supply
2758/// fixit hints when the cast wouldn't lose information to simply write the
2759/// expression with the expected type.
2760void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
2761 SourceLocation CContext) {
2762 // Emit the primary warning first, then try to emit a fixit hint note if
2763 // reasonable.
2764 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
2765 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
2766
2767 const llvm::APFloat &Value = FL->getValue();
2768
2769 // Don't attempt to fix PPC double double literals.
2770 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
2771 return;
2772
2773 // Try to convert this exactly to an 64-bit integer. FIXME: It would be
2774 // nice to support arbitrarily large integers here.
2775 bool isExact = false;
2776 uint64_t IntegerPart;
2777 if (Value.convertToInteger(&IntegerPart, 64, /*isSigned=*/true,
2778 llvm::APFloat::rmTowardZero, &isExact)
2779 != llvm::APFloat::opOK || !isExact)
2780 return;
2781
2782 llvm::APInt IntegerValue(64, IntegerPart, /*isSigned=*/true);
2783
2784 std::string LiteralValue = IntegerValue.toString(10, /*isSigned=*/true);
2785 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
2786 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
2787}
2788
John McCall091f23f2010-11-09 22:22:12 +00002789std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2790 if (!Range.Width) return "0";
2791
2792 llvm::APSInt ValueInRange = Value;
2793 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002794 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002795 return ValueInRange.toString(10);
2796}
2797
Ted Kremenekef9ff882011-03-10 20:03:42 +00002798static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2799 SourceManager &smgr = S.Context.getSourceManager();
2800 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2801}
Chandler Carruthf65076e2011-04-10 08:36:24 +00002802
John McCall323ed742010-05-06 08:58:33 +00002803void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002804 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002805 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002806
John McCall323ed742010-05-06 08:58:33 +00002807 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2808 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2809 if (Source == Target) return;
2810 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002811
Ted Kremenekef9ff882011-03-10 20:03:42 +00002812 // If the conversion context location is invalid don't complain.
2813 // We also don't want to emit a warning if the issue occurs from the
2814 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2815 // is slow, so we delay this check as long as possible. Once we detect
2816 // we are in that scenario, we just return.
2817 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00002818 return;
2819
John McCall51313c32010-01-04 23:31:57 +00002820 // Never diagnose implicit casts to bool.
2821 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2822 return;
2823
2824 // Strip vector types.
2825 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002826 if (!isa<VectorType>(Target)) {
2827 if (isFromSystemMacro(S, CC))
2828 return;
John McCallb4eb64d2010-10-08 02:01:28 +00002829 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002830 }
John McCall51313c32010-01-04 23:31:57 +00002831
2832 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2833 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2834 }
2835
2836 // Strip complex types.
2837 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002838 if (!isa<ComplexType>(Target)) {
2839 if (isFromSystemMacro(S, CC))
2840 return;
2841
John McCallb4eb64d2010-10-08 02:01:28 +00002842 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002843 }
John McCall51313c32010-01-04 23:31:57 +00002844
2845 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2846 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2847 }
2848
2849 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2850 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2851
2852 // If the source is floating point...
2853 if (SourceBT && SourceBT->isFloatingPoint()) {
2854 // ...and the target is floating point...
2855 if (TargetBT && TargetBT->isFloatingPoint()) {
2856 // ...then warn if we're dropping FP rank.
2857
2858 // Builtin FP kinds are ordered by increasing FP rank.
2859 if (SourceBT->getKind() > TargetBT->getKind()) {
2860 // Don't warn about float constants that are precisely
2861 // representable in the target type.
2862 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002863 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002864 // Value might be a float, a float vector, or a float complex.
2865 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002866 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2867 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002868 return;
2869 }
2870
Ted Kremenekef9ff882011-03-10 20:03:42 +00002871 if (isFromSystemMacro(S, CC))
2872 return;
2873
John McCallb4eb64d2010-10-08 02:01:28 +00002874 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002875 }
2876 return;
2877 }
2878
Ted Kremenekef9ff882011-03-10 20:03:42 +00002879 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00002880 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002881 if (isFromSystemMacro(S, CC))
2882 return;
2883
Chandler Carrutha5b93322011-02-17 11:05:49 +00002884 Expr *InnerE = E->IgnoreParenImpCasts();
Chandler Carruthf65076e2011-04-10 08:36:24 +00002885 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
2886 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00002887 } else {
2888 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2889 }
2890 }
John McCall51313c32010-01-04 23:31:57 +00002891
2892 return;
2893 }
2894
John McCallf2370c92010-01-06 05:24:50 +00002895 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002896 return;
2897
John McCall323ed742010-05-06 08:58:33 +00002898 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002899 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002900
2901 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002902 // If the source is a constant, use a default-on diagnostic.
2903 // TODO: this should happen for bitfield stores, too.
2904 llvm::APSInt Value(32);
2905 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002906 if (isFromSystemMacro(S, CC))
2907 return;
2908
John McCall091f23f2010-11-09 22:22:12 +00002909 std::string PrettySourceValue = Value.toString(10);
2910 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2911
2912 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2913 << PrettySourceValue << PrettyTargetValue
2914 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2915 return;
2916 }
2917
John McCall51313c32010-01-04 23:31:57 +00002918 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2919 // and by god we'll let them.
Ted Kremenekef9ff882011-03-10 20:03:42 +00002920
2921 if (isFromSystemMacro(S, CC))
2922 return;
2923
John McCallf2370c92010-01-06 05:24:50 +00002924 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002925 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2926 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002927 }
2928
2929 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2930 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2931 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002932
2933 if (isFromSystemMacro(S, CC))
2934 return;
2935
John McCall323ed742010-05-06 08:58:33 +00002936 unsigned DiagID = diag::warn_impcast_integer_sign;
2937
2938 // Traditionally, gcc has warned about this under -Wsign-compare.
2939 // We also want to warn about it in -Wconversion.
2940 // So if -Wconversion is off, use a completely identical diagnostic
2941 // in the sign-compare group.
2942 // The conditional-checking code will
2943 if (ICContext) {
2944 DiagID = diag::warn_impcast_integer_sign_conditional;
2945 *ICContext = true;
2946 }
2947
John McCallb4eb64d2010-10-08 02:01:28 +00002948 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002949 }
2950
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002951 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002952 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
2953 // type, to give us better diagnostics.
2954 QualType SourceType = E->getType();
2955 if (!S.getLangOptions().CPlusPlus) {
2956 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2957 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2958 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
2959 SourceType = S.Context.getTypeDeclType(Enum);
2960 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
2961 }
2962 }
2963
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002964 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
2965 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
2966 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00002967 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002968 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00002969 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00002970 SourceEnum != TargetEnum) {
2971 if (isFromSystemMacro(S, CC))
2972 return;
2973
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002974 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002975 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002976 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002977
John McCall51313c32010-01-04 23:31:57 +00002978 return;
2979}
2980
John McCall323ed742010-05-06 08:58:33 +00002981void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2982
2983void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002984 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00002985 E = E->IgnoreParenImpCasts();
2986
2987 if (isa<ConditionalOperator>(E))
2988 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2989
John McCallb4eb64d2010-10-08 02:01:28 +00002990 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002991 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002992 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00002993 return;
2994}
2995
2996void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00002997 SourceLocation CC = E->getQuestionLoc();
2998
2999 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003000
3001 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003002 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3003 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003004
3005 // If -Wconversion would have warned about either of the candidates
3006 // for a signedness conversion to the context type...
3007 if (!Suspicious) return;
3008
3009 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003010 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3011 CC))
John McCall323ed742010-05-06 08:58:33 +00003012 return;
3013
3014 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003015 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00003016 return;
3017
3018 // ...then check whether it would have warned about either of the
3019 // candidates for a signedness conversion to the condition type.
3020 if (E->getType() != T) {
3021 Suspicious = false;
3022 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003023 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003024 if (!Suspicious)
3025 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003026 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003027 if (!Suspicious)
3028 return;
3029 }
3030
3031 // If so, emit a diagnostic under -Wsign-compare.
3032 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3033 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3034 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3035 << lex->getType() << rex->getType()
3036 << lex->getSourceRange() << rex->getSourceRange();
3037}
3038
3039/// AnalyzeImplicitConversions - Find and report any interesting
3040/// implicit conversions in the given expression. There are a couple
3041/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003042void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003043 QualType T = OrigE->getType();
3044 Expr *E = OrigE->IgnoreParenImpCasts();
3045
3046 // For conditional operators, we analyze the arguments as if they
3047 // were being fed directly into the output.
3048 if (isa<ConditionalOperator>(E)) {
3049 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3050 CheckConditionalOperator(S, CO, T);
3051 return;
3052 }
3053
3054 // Go ahead and check any implicit conversions we might have skipped.
3055 // The non-canonical typecheck is just an optimization;
3056 // CheckImplicitConversion will filter out dead implicit conversions.
3057 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003058 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003059
3060 // Now continue drilling into this expression.
3061
3062 // Skip past explicit casts.
3063 if (isa<ExplicitCastExpr>(E)) {
3064 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003065 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003066 }
3067
John McCallbeb22aa2010-11-09 23:24:47 +00003068 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3069 // Do a somewhat different check with comparison operators.
3070 if (BO->isComparisonOp())
3071 return AnalyzeComparison(S, BO);
3072
3073 // And with assignments and compound assignments.
3074 if (BO->isAssignmentOp())
3075 return AnalyzeAssignment(S, BO);
3076 }
John McCall323ed742010-05-06 08:58:33 +00003077
3078 // These break the otherwise-useful invariant below. Fortunately,
3079 // we don't really need to recurse into them, because any internal
3080 // expressions should have been analyzed already when they were
3081 // built into statements.
3082 if (isa<StmtExpr>(E)) return;
3083
3084 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003085 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003086
3087 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003088 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003089 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003090 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003091}
3092
3093} // end anonymous namespace
3094
3095/// Diagnoses "dangerous" implicit conversions within the given
3096/// expression (which is a full expression). Implements -Wconversion
3097/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003098///
3099/// \param CC the "context" location of the implicit conversion, i.e.
3100/// the most location of the syntactic entity requiring the implicit
3101/// conversion
3102void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003103 // Don't diagnose in unevaluated contexts.
3104 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3105 return;
3106
3107 // Don't diagnose for value- or type-dependent expressions.
3108 if (E->isTypeDependent() || E->isValueDependent())
3109 return;
3110
John McCallb4eb64d2010-10-08 02:01:28 +00003111 // This is not the right CC for (e.g.) a variable initialization.
3112 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003113}
3114
John McCall15d7d122010-11-11 03:21:53 +00003115void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3116 FieldDecl *BitField,
3117 Expr *Init) {
3118 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3119}
3120
Mike Stumpf8c49212010-01-21 03:59:47 +00003121/// CheckParmsForFunctionDef - Check that the parameters of the given
3122/// function are appropriate for the definition of a function. This
3123/// takes care of any checks that cannot be performed on the
3124/// declaration itself, e.g., that the types of each of the function
3125/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003126bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3127 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003128 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003129 for (; P != PEnd; ++P) {
3130 ParmVarDecl *Param = *P;
3131
Mike Stumpf8c49212010-01-21 03:59:47 +00003132 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3133 // function declarator that is part of a function definition of
3134 // that function shall not have incomplete type.
3135 //
3136 // This is also C++ [dcl.fct]p6.
3137 if (!Param->isInvalidDecl() &&
3138 RequireCompleteType(Param->getLocation(), Param->getType(),
3139 diag::err_typecheck_decl_incomplete_type)) {
3140 Param->setInvalidDecl();
3141 HasInvalidParm = true;
3142 }
3143
3144 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3145 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003146 if (CheckParameterNames &&
3147 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003148 !Param->isImplicit() &&
3149 !getLangOptions().CPlusPlus)
3150 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003151
3152 // C99 6.7.5.3p12:
3153 // If the function declarator is not part of a definition of that
3154 // function, parameters may have incomplete type and may use the [*]
3155 // notation in their sequences of declarator specifiers to specify
3156 // variable length array types.
3157 QualType PType = Param->getOriginalType();
3158 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3159 if (AT->getSizeModifier() == ArrayType::Star) {
3160 // FIXME: This diagnosic should point the the '[*]' if source-location
3161 // information is added for it.
3162 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3163 }
3164 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003165 }
3166
3167 return HasInvalidParm;
3168}
John McCallb7f4ffe2010-08-12 21:44:57 +00003169
3170/// CheckCastAlign - Implements -Wcast-align, which warns when a
3171/// pointer cast increases the alignment requirements.
3172void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3173 // This is actually a lot of work to potentially be doing on every
3174 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003175 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3176 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003177 == Diagnostic::Ignored)
3178 return;
3179
3180 // Ignore dependent types.
3181 if (T->isDependentType() || Op->getType()->isDependentType())
3182 return;
3183
3184 // Require that the destination be a pointer type.
3185 const PointerType *DestPtr = T->getAs<PointerType>();
3186 if (!DestPtr) return;
3187
3188 // If the destination has alignment 1, we're done.
3189 QualType DestPointee = DestPtr->getPointeeType();
3190 if (DestPointee->isIncompleteType()) return;
3191 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3192 if (DestAlign.isOne()) return;
3193
3194 // Require that the source be a pointer type.
3195 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3196 if (!SrcPtr) return;
3197 QualType SrcPointee = SrcPtr->getPointeeType();
3198
3199 // Whitelist casts from cv void*. We already implicitly
3200 // whitelisted casts to cv void*, since they have alignment 1.
3201 // Also whitelist casts involving incomplete types, which implicitly
3202 // includes 'void'.
3203 if (SrcPointee->isIncompleteType()) return;
3204
3205 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3206 if (SrcAlign >= DestAlign) return;
3207
3208 Diag(TRange.getBegin(), diag::warn_cast_align)
3209 << Op->getType() << T
3210 << static_cast<unsigned>(SrcAlign.getQuantity())
3211 << static_cast<unsigned>(DestAlign.getQuantity())
3212 << TRange << Op->getSourceRange();
3213}
3214
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003215static void CheckArrayAccess_Check(Sema &S,
3216 const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003217 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003218 const ConstantArrayType *ArrayTy =
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003219 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003220 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003221 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003222
Chandler Carruth34064582011-02-17 20:55:08 +00003223 const Expr *IndexExpr = E->getIdx();
3224 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003225 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003226 llvm::APSInt index;
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003227 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003228 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003229
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003230 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003231 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003232 if (!size.isStrictlyPositive())
3233 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003234 if (size.getBitWidth() > index.getBitWidth())
3235 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003236 else if (size.getBitWidth() < index.getBitWidth())
3237 size = size.sext(index.getBitWidth());
3238
Chandler Carruth34064582011-02-17 20:55:08 +00003239 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003240 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003241
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003242 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3243 S.PDiag(diag::warn_array_index_exceeds_bounds)
3244 << index.toString(10, true)
3245 << size.toString(10, true)
3246 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003247 } else {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003248 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3249 S.PDiag(diag::warn_array_index_precedes_bounds)
3250 << index.toString(10, true)
3251 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003252 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003253
3254 const NamedDecl *ND = NULL;
3255 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3256 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3257 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3258 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3259 if (ND)
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003260 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3261 S.PDiag(diag::note_array_index_out_of_bounds)
3262 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003263}
3264
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003265void Sema::CheckArrayAccess(const Expr *expr) {
Peter Collingbournef111d932011-04-15 00:35:48 +00003266 while (true) {
3267 expr = expr->IgnoreParens();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003268 switch (expr->getStmtClass()) {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003269 case Stmt::ArraySubscriptExprClass:
3270 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3271 return;
3272 case Stmt::ConditionalOperatorClass: {
3273 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3274 if (const Expr *lhs = cond->getLHS())
3275 CheckArrayAccess(lhs);
3276 if (const Expr *rhs = cond->getRHS())
3277 CheckArrayAccess(rhs);
3278 return;
3279 }
3280 default:
3281 return;
3282 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003283 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003284}