blob: 15644c99d91fa46b3e3f48e98677eb0d15dfcd02 [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:
Chandler Carruthd2014572010-07-09 18:59:35 +0000183 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000184 }
185
186 // Since the target specific builtins for each arch overlap, only check those
187 // of the arch we are compiling for.
188 if (BuiltinID >= Builtin::FirstTSBuiltin) {
189 switch (Context.Target.getTriple().getArch()) {
190 case llvm::Triple::arm:
191 case llvm::Triple::thumb:
192 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
193 return ExprError();
194 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000195 default:
196 break;
197 }
198 }
199
200 return move(TheCallResult);
201}
202
Nate Begeman61eecf52010-06-14 05:21:25 +0000203// Get the valid immediate range for the specified NEON type code.
204static unsigned RFT(unsigned t, bool shift = false) {
205 bool quad = t & 0x10;
206
207 switch (t & 0x7) {
208 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000209 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000210 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000211 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000212 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000213 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000214 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000215 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000216 case 4: // f32
217 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000218 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000219 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000220 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000221 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000222 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000223 case 7: // float16
224 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000225 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000226 }
227 return 0;
228}
229
Nate Begeman26a31422010-06-08 02:47:44 +0000230bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000231 llvm::APSInt Result;
232
Nate Begeman0d15c532010-06-13 04:47:52 +0000233 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000234 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000235 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000236#define GET_NEON_OVERLOAD_CHECK
237#include "clang/Basic/arm_neon.inc"
238#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000239 }
240
Nate Begeman0d15c532010-06-13 04:47:52 +0000241 // For NEON intrinsics which are overloaded on vector element type, validate
242 // the immediate which specifies which variant to emit.
243 if (mask) {
244 unsigned ArgNo = TheCall->getNumArgs()-1;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246 return true;
247
Nate Begeman61eecf52010-06-14 05:21:25 +0000248 TV = Result.getLimitedValue(32);
249 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000250 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
251 << TheCall->getArg(ArgNo)->getSourceRange();
252 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000253
Nate Begeman0d15c532010-06-13 04:47:52 +0000254 // For NEON intrinsics which take an immediate value as part of the
255 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000256 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000257 switch (BuiltinID) {
258 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000259 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
260 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000261 case ARM::BI__builtin_arm_vcvtr_f:
262 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000263#define GET_NEON_IMMEDIATE_CHECK
264#include "clang/Basic/arm_neon.inc"
265#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000266 };
267
Nate Begeman61eecf52010-06-14 05:21:25 +0000268 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000269 if (SemaBuiltinConstantArg(TheCall, i, Result))
270 return true;
271
Nate Begeman61eecf52010-06-14 05:21:25 +0000272 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000273 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000274 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000275 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000276 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000277
Nate Begeman99c40bb2010-08-03 21:32:34 +0000278 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000279 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000280}
Daniel Dunbarde454282008-10-02 18:44:07 +0000281
Anders Carlssond406bf02009-08-16 01:56:34 +0000282/// CheckFunctionCall - Check a direct function call for various correctness
283/// and safety properties not strictly enforced by the C type system.
284bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
285 // Get the IdentifierInfo* for the called function.
286 IdentifierInfo *FnInfo = FDecl->getIdentifier();
287
288 // None of the checks below are needed for functions that don't have
289 // simple names (e.g., C++ conversion functions).
290 if (!FnInfo)
291 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Daniel Dunbarde454282008-10-02 18:44:07 +0000293 // FIXME: This mechanism should be abstracted to be less fragile and
294 // more efficient. For example, just map function ids to custom
295 // handlers.
296
Ted Kremenekc82faca2010-09-09 04:33:05 +0000297 // Printf and scanf checking.
298 for (specific_attr_iterator<FormatAttr>
299 i = FDecl->specific_attr_begin<FormatAttr>(),
300 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
301
302 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000303 const bool b = Format->getType() == "scanf";
304 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000305 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000306 CheckPrintfScanfArguments(TheCall, HasVAListArg,
307 Format->getFormatIdx() - 1,
308 HasVAListArg ? 0 : Format->getFirstArg() - 1,
309 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000310 }
Chris Lattner59907c42007-08-10 20:18:51 +0000311 }
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Ted Kremenekc82faca2010-09-09 04:33:05 +0000313 for (specific_attr_iterator<NonNullAttr>
314 i = FDecl->specific_attr_begin<NonNullAttr>(),
315 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000316 CheckNonNullArguments(*i, TheCall->getArgs(),
317 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000318 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000319
Anders Carlssond406bf02009-08-16 01:56:34 +0000320 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000321}
322
Anders Carlssond406bf02009-08-16 01:56:34 +0000323bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000324 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000325 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000326 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000327 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000329 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
330 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000331 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000333 QualType Ty = V->getType();
334 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000335 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Ted Kremenek826a3452010-07-16 02:11:22 +0000337 const bool b = Format->getType() == "scanf";
338 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000339 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Anders Carlssond406bf02009-08-16 01:56:34 +0000341 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000342 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
343 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000344
345 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000346}
347
Chris Lattner5caa3702009-05-08 06:58:22 +0000348/// SemaBuiltinAtomicOverloaded - We have a call to a function like
349/// __sync_fetch_and_add, which is an overloaded function based on the pointer
350/// type of its first argument. The main ActOnCallExpr routines have already
351/// promoted the types of arguments because all of these calls are prototyped as
352/// void(...).
353///
354/// This function goes through and does final semantic checking for these
355/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000356ExprResult
357Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000358 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000359 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
360 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
361
362 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000363 if (TheCall->getNumArgs() < 1) {
364 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
365 << 0 << 1 << TheCall->getNumArgs()
366 << TheCall->getCallee()->getSourceRange();
367 return ExprError();
368 }
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Chris Lattner5caa3702009-05-08 06:58:22 +0000370 // Inspect the first argument of the atomic builtin. This should always be
371 // a pointer type, whose element is an integral scalar or pointer type.
372 // Because it is a pointer type, we don't have to worry about any implicit
373 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000374 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000375 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruthd2014572010-07-09 18:59:35 +0000376 if (!FirstArg->getType()->isPointerType()) {
377 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
378 << FirstArg->getType() << FirstArg->getSourceRange();
379 return ExprError();
380 }
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chandler Carruthd2014572010-07-09 18:59:35 +0000382 QualType ValType =
383 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000384 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000385 !ValType->isBlockPointerType()) {
386 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
387 << FirstArg->getType() << FirstArg->getSourceRange();
388 return ExprError();
389 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000390
Chandler Carruth8d13d222010-07-18 20:54:12 +0000391 // The majority of builtins return a value, but a few have special return
392 // types, so allow them to override appropriately below.
393 QualType ResultType = ValType;
394
Chris Lattner5caa3702009-05-08 06:58:22 +0000395 // We need to figure out which concrete builtin this maps onto. For example,
396 // __sync_fetch_and_add with a 2 byte object turns into
397 // __sync_fetch_and_add_2.
398#define BUILTIN_ROW(x) \
399 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
400 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Chris Lattner5caa3702009-05-08 06:58:22 +0000402 static const unsigned BuiltinIndices[][5] = {
403 BUILTIN_ROW(__sync_fetch_and_add),
404 BUILTIN_ROW(__sync_fetch_and_sub),
405 BUILTIN_ROW(__sync_fetch_and_or),
406 BUILTIN_ROW(__sync_fetch_and_and),
407 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner5caa3702009-05-08 06:58:22 +0000409 BUILTIN_ROW(__sync_add_and_fetch),
410 BUILTIN_ROW(__sync_sub_and_fetch),
411 BUILTIN_ROW(__sync_and_and_fetch),
412 BUILTIN_ROW(__sync_or_and_fetch),
413 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner5caa3702009-05-08 06:58:22 +0000415 BUILTIN_ROW(__sync_val_compare_and_swap),
416 BUILTIN_ROW(__sync_bool_compare_and_swap),
417 BUILTIN_ROW(__sync_lock_test_and_set),
418 BUILTIN_ROW(__sync_lock_release)
419 };
Mike Stump1eb44332009-09-09 15:08:12 +0000420#undef BUILTIN_ROW
421
Chris Lattner5caa3702009-05-08 06:58:22 +0000422 // Determine the index of the size.
423 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000424 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000425 case 1: SizeIndex = 0; break;
426 case 2: SizeIndex = 1; break;
427 case 4: SizeIndex = 2; break;
428 case 8: SizeIndex = 3; break;
429 case 16: SizeIndex = 4; break;
430 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000431 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
432 << FirstArg->getType() << FirstArg->getSourceRange();
433 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000434 }
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Chris Lattner5caa3702009-05-08 06:58:22 +0000436 // Each of these builtins has one pointer argument, followed by some number of
437 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
438 // that we ignore. Find out which row of BuiltinIndices to read from as well
439 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000440 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000441 unsigned BuiltinIndex, NumFixed = 1;
442 switch (BuiltinID) {
443 default: assert(0 && "Unknown overloaded atomic builtin!");
444 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
445 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
446 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
447 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
448 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000450 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
451 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
452 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
453 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
454 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Chris Lattner5caa3702009-05-08 06:58:22 +0000456 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000457 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000458 NumFixed = 2;
459 break;
460 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000461 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000462 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000463 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000464 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000465 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000466 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000467 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000468 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000469 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000470 break;
471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Chris Lattner5caa3702009-05-08 06:58:22 +0000473 // Now that we know how many fixed arguments we expect, first check that we
474 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000475 if (TheCall->getNumArgs() < 1+NumFixed) {
476 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
477 << 0 << 1+NumFixed << TheCall->getNumArgs()
478 << TheCall->getCallee()->getSourceRange();
479 return ExprError();
480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000482 // Get the decl for the concrete builtin from this, we can tell what the
483 // concrete integer type we should convert to is.
484 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
485 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
486 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000487 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000488 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
489 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000490
John McCallf871d0c2010-08-07 06:22:56 +0000491 // The first argument --- the pointer --- has a fixed type; we
492 // deduce the types of the rest of the arguments accordingly. Walk
493 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000494 for (unsigned i = 0; i != NumFixed; ++i) {
495 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Chris Lattner5caa3702009-05-08 06:58:22 +0000497 // If the argument is an implicit cast, then there was a promotion due to
498 // "...", just remove it now.
499 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
500 Arg = ICE->getSubExpr();
501 ICE->setSubExpr(0);
Chris Lattner5caa3702009-05-08 06:58:22 +0000502 TheCall->setArg(i+1, Arg);
503 }
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Chris Lattner5caa3702009-05-08 06:58:22 +0000505 // GCC does an implicit conversion to the pointer or integer ValType. This
506 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000507 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000508 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000509 CXXCastPath BasePath;
John McCallf89e55a2010-11-18 06:31:45 +0000510 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, VK, BasePath))
Chandler Carruthd2014572010-07-09 18:59:35 +0000511 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chris Lattner5caa3702009-05-08 06:58:22 +0000513 // Okay, we have something that *can* be converted to the right type. Check
514 // to see if there is a potentially weird extension going on here. This can
515 // happen when you do an atomic operation on something like an char* and
516 // pass in 42. The 42 gets converted to char. This is even more strange
517 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000518 // FIXME: Do this check.
John McCallf89e55a2010-11-18 06:31:45 +0000519 ImpCastExprToType(Arg, ValType, Kind, VK, &BasePath);
Chris Lattner5caa3702009-05-08 06:58:22 +0000520 TheCall->setArg(i+1, Arg);
521 }
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattner5caa3702009-05-08 06:58:22 +0000523 // Switch the DeclRefExpr to refer to the new decl.
524 DRE->setDecl(NewBuiltinDecl);
525 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner5caa3702009-05-08 06:58:22 +0000527 // Set the callee in the CallExpr.
528 // FIXME: This leaks the original parens and implicit casts.
529 Expr *PromotedCall = DRE;
530 UsualUnaryConversions(PromotedCall);
531 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000533 // Change the result type of the call to match the original value type. This
534 // is arbitrary, but the codegen for these builtins ins design to handle it
535 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000536 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000537
538 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000539}
540
541
Chris Lattner69039812009-02-18 06:01:06 +0000542/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000543/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000544/// Note: It might also make sense to do the UTF-16 conversion here (would
545/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000546bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000547 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000548 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
549
550 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000551 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
552 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000553 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000554 }
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000556 if (Literal->containsNonAsciiOrNull()) {
557 llvm::StringRef String = Literal->getString();
558 unsigned NumBytes = String.size();
559 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
560 const UTF8 *FromPtr = (UTF8 *)String.data();
561 UTF16 *ToPtr = &ToBuf[0];
562
563 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
564 &ToPtr, ToPtr + NumBytes,
565 strictConversion);
566 // Check for conversion failure.
567 if (Result != conversionOK)
568 Diag(Arg->getLocStart(),
569 diag::warn_cfstring_truncated) << Arg->getSourceRange();
570 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000571 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000572}
573
Chris Lattnerc27c6652007-12-20 00:05:45 +0000574/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
575/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000576bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
577 Expr *Fn = TheCall->getCallee();
578 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000579 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000580 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000581 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
582 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000583 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000584 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000585 return true;
586 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000587
588 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000589 return Diag(TheCall->getLocEnd(),
590 diag::err_typecheck_call_too_few_args_at_least)
591 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000592 }
593
Chris Lattnerc27c6652007-12-20 00:05:45 +0000594 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000595 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000596 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000597 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000598 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000599 else if (FunctionDecl *FD = getCurFunctionDecl())
600 isVariadic = FD->isVariadic();
601 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000602 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Chris Lattnerc27c6652007-12-20 00:05:45 +0000604 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000605 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
606 return true;
607 }
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattner30ce3442007-12-19 23:59:04 +0000609 // Verify that the second argument to the builtin is the last argument of the
610 // current function or method.
611 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000612 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Anders Carlsson88cf2262008-02-11 04:20:54 +0000614 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
615 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000616 // FIXME: This isn't correct for methods (results in bogus warning).
617 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000618 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000619 if (CurBlock)
620 LastArg = *(CurBlock->TheDecl->param_end()-1);
621 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000622 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000623 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000624 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000625 SecondArgIsLastNamedArgument = PV == LastArg;
626 }
627 }
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Chris Lattner30ce3442007-12-19 23:59:04 +0000629 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000630 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000631 diag::warn_second_parameter_of_va_start_not_last_named_argument);
632 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000633}
Chris Lattner30ce3442007-12-19 23:59:04 +0000634
Chris Lattner1b9a0792007-12-20 00:26:33 +0000635/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
636/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000637bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
638 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000639 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000640 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000641 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000642 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000643 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000644 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000645 << SourceRange(TheCall->getArg(2)->getLocStart(),
646 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Chris Lattner925e60d2007-12-28 05:29:59 +0000648 Expr *OrigArg0 = TheCall->getArg(0);
649 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000650
Chris Lattner1b9a0792007-12-20 00:26:33 +0000651 // Do standard promotions between the two arguments, returning their common
652 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000653 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000654
655 // Make sure any conversions are pushed back into the call; this is
656 // type safe since unordered compare builtins are declared as "_Bool
657 // foo(...)".
658 TheCall->setArg(0, OrigArg0);
659 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Douglas Gregorcde01732009-05-19 22:10:17 +0000661 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
662 return false;
663
Chris Lattner1b9a0792007-12-20 00:26:33 +0000664 // If the common type isn't a real floating type, then the arguments were
665 // invalid for this operation.
666 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000667 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000668 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000669 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000670 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Chris Lattner1b9a0792007-12-20 00:26:33 +0000672 return false;
673}
674
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000675/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
676/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000677/// to check everything. We expect the last argument to be a floating point
678/// value.
679bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
680 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000681 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000682 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000683 if (TheCall->getNumArgs() > NumArgs)
684 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000685 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000686 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000687 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000688 (*(TheCall->arg_end()-1))->getLocEnd());
689
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000690 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Eli Friedman9ac6f622009-08-31 20:06:00 +0000692 if (OrigArg->isTypeDependent())
693 return false;
694
Chris Lattner81368fb2010-05-06 05:50:07 +0000695 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000696 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000697 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000698 diag::err_typecheck_call_invalid_unary_fp)
699 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Chris Lattner81368fb2010-05-06 05:50:07 +0000701 // If this is an implicit conversion from float -> double, remove it.
702 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
703 Expr *CastArg = Cast->getSubExpr();
704 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
705 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
706 "promotion from float to double is the only expected cast here");
707 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000708 TheCall->setArg(NumArgs-1, CastArg);
709 OrigArg = CastArg;
710 }
711 }
712
Eli Friedman9ac6f622009-08-31 20:06:00 +0000713 return false;
714}
715
Eli Friedmand38617c2008-05-14 19:38:39 +0000716/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
717// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000718ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000719 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000720 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000721 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000722 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000723 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000724
Nate Begeman37b6a572010-06-08 00:16:34 +0000725 // Determine which of the following types of shufflevector we're checking:
726 // 1) unary, vector mask: (lhs, mask)
727 // 2) binary, vector mask: (lhs, rhs, mask)
728 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
729 QualType resType = TheCall->getArg(0)->getType();
730 unsigned numElements = 0;
731
Douglas Gregorcde01732009-05-19 22:10:17 +0000732 if (!TheCall->getArg(0)->isTypeDependent() &&
733 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000734 QualType LHSType = TheCall->getArg(0)->getType();
735 QualType RHSType = TheCall->getArg(1)->getType();
736
737 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000738 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000739 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000740 TheCall->getArg(1)->getLocEnd());
741 return ExprError();
742 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000743
744 numElements = LHSType->getAs<VectorType>()->getNumElements();
745 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Nate Begeman37b6a572010-06-08 00:16:34 +0000747 // Check to see if we have a call with 2 vector arguments, the unary shuffle
748 // with mask. If so, verify that RHS is an integer vector type with the
749 // same number of elts as lhs.
750 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000751 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000752 RHSType->getAs<VectorType>()->getNumElements() != numElements)
753 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
754 << SourceRange(TheCall->getArg(1)->getLocStart(),
755 TheCall->getArg(1)->getLocEnd());
756 numResElements = numElements;
757 }
758 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000759 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000760 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000761 TheCall->getArg(1)->getLocEnd());
762 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000763 } else if (numElements != numResElements) {
764 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000765 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000766 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000767 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000768 }
769
770 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000771 if (TheCall->getArg(i)->isTypeDependent() ||
772 TheCall->getArg(i)->isValueDependent())
773 continue;
774
Nate Begeman37b6a572010-06-08 00:16:34 +0000775 llvm::APSInt Result(32);
776 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
777 return ExprError(Diag(TheCall->getLocStart(),
778 diag::err_shufflevector_nonconstant_argument)
779 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000780
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000781 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000782 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000783 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000784 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000785 }
786
787 llvm::SmallVector<Expr*, 32> exprs;
788
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000789 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000790 exprs.push_back(TheCall->getArg(i));
791 TheCall->setArg(i, 0);
792 }
793
Nate Begemana88dc302009-08-12 02:10:25 +0000794 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000795 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000796 TheCall->getCallee()->getLocStart(),
797 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000798}
Chris Lattner30ce3442007-12-19 23:59:04 +0000799
Daniel Dunbar4493f792008-07-21 22:59:13 +0000800/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
801// This is declared to take (const void*, ...) and can take two
802// optional constant int args.
803bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000804 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000805
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000806 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000807 return Diag(TheCall->getLocEnd(),
808 diag::err_typecheck_call_too_many_args_at_most)
809 << 0 /*function call*/ << 3 << NumArgs
810 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000811
812 // Argument 0 is checked for us and the remaining arguments must be
813 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000814 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000815 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000816
Eli Friedman9aef7262009-12-04 00:30:06 +0000817 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000818 if (SemaBuiltinConstantArg(TheCall, i, Result))
819 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Daniel Dunbar4493f792008-07-21 22:59:13 +0000821 // FIXME: gcc issues a warning and rewrites these to 0. These
822 // seems especially odd for the third argument since the default
823 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000824 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000825 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000826 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000827 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000828 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000829 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000830 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000831 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000832 }
833 }
834
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000835 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000836}
837
Eric Christopher691ebc32010-04-17 02:26:23 +0000838/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
839/// TheCall is a constant expression.
840bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
841 llvm::APSInt &Result) {
842 Expr *Arg = TheCall->getArg(ArgNum);
843 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
844 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
845
846 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
847
848 if (!Arg->isIntegerConstantExpr(Result, Context))
849 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000850 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000851
Chris Lattner21fb98e2009-09-23 06:06:36 +0000852 return false;
853}
854
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000855/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
856/// int type). This simply type checks that type is one of the defined
857/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000858// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000859bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000860 llvm::APSInt Result;
861
862 // Check constant-ness first.
863 if (SemaBuiltinConstantArg(TheCall, 1, Result))
864 return true;
865
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000866 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000867 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000868 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
869 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000870 }
871
872 return false;
873}
874
Eli Friedman586d6a82009-05-03 06:04:26 +0000875/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000876/// This checks that val is a constant 1.
877bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
878 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000879 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000880
Eric Christopher691ebc32010-04-17 02:26:23 +0000881 // TODO: This is less than ideal. Overload this to take a value.
882 if (SemaBuiltinConstantArg(TheCall, 1, Result))
883 return true;
884
885 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000886 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
887 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
888
889 return false;
890}
891
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000892// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000893bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
894 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000895 unsigned format_idx, unsigned firstDataArg,
896 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000897 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000898 if (E->isTypeDependent() || E->isValueDependent())
899 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000900
901 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000902 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000903 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000904 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000905 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
906 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000907 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000908 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000909 }
910
Ted Kremenek95355bb2010-09-09 03:51:42 +0000911 case Stmt::IntegerLiteralClass:
912 // Technically -Wformat-nonliteral does not warn about this case.
913 // The behavior of printf and friends in this case is implementation
914 // dependent. Ideally if the format string cannot be null then
915 // it should have a 'nonnull' attribute in the function prototype.
916 return true;
917
Ted Kremenekd30ef872009-01-12 23:09:09 +0000918 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000919 E = cast<ImplicitCastExpr>(E)->getSubExpr();
920 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000921 }
922
923 case Stmt::ParenExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000924 E = cast<ParenExpr>(E)->getSubExpr();
925 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000926 }
Mike Stump1eb44332009-09-09 15:08:12 +0000927
John McCall56ca35d2011-02-17 10:25:35 +0000928 case Stmt::OpaqueValueExprClass:
929 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
930 E = src;
931 goto tryAgain;
932 }
933 return false;
934
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000935 case Stmt::PredefinedExprClass:
936 // While __func__, etc., are technically not string literals, they
937 // cannot contain format specifiers and thus are not a security
938 // liability.
939 return true;
940
Ted Kremenek082d9362009-03-20 21:35:28 +0000941 case Stmt::DeclRefExprClass: {
942 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Ted Kremenek082d9362009-03-20 21:35:28 +0000944 // As an exception, do not flag errors for variables binding to
945 // const string literals.
946 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
947 bool isConstant = false;
948 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000949
Ted Kremenek082d9362009-03-20 21:35:28 +0000950 if (const ArrayType *AT = Context.getAsArrayType(T)) {
951 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000952 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000953 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000954 PT->getPointeeType().isConstant(Context);
955 }
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Ted Kremenek082d9362009-03-20 21:35:28 +0000957 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000958 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000959 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000960 HasVAListArg, format_idx, firstDataArg,
961 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000962 }
Mike Stump1eb44332009-09-09 15:08:12 +0000963
Anders Carlssond966a552009-06-28 19:55:58 +0000964 // For vprintf* functions (i.e., HasVAListArg==true), we add a
965 // special check to see if the format string is a function parameter
966 // of the function calling the printf function. If the function
967 // has an attribute indicating it is a printf-like function, then we
968 // should suppress warnings concerning non-literals being used in a call
969 // to a vprintf function. For example:
970 //
971 // void
972 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
973 // va_list ap;
974 // va_start(ap, fmt);
975 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
976 // ...
977 //
978 //
979 // FIXME: We don't have full attribute support yet, so just check to see
980 // if the argument is a DeclRefExpr that references a parameter. We'll
981 // add proper support for checking the attribute later.
982 if (HasVAListArg)
983 if (isa<ParmVarDecl>(VD))
984 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000985 }
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Ted Kremenek082d9362009-03-20 21:35:28 +0000987 return false;
988 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000989
Anders Carlsson8f031b32009-06-27 04:05:33 +0000990 case Stmt::CallExprClass: {
991 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000992 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000993 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
994 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
995 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000996 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000997 unsigned ArgIndex = FA->getFormatIdx();
998 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000999
1000 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001001 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001002 }
1003 }
1004 }
1005 }
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Anders Carlsson8f031b32009-06-27 04:05:33 +00001007 return false;
1008 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001009 case Stmt::ObjCStringLiteralClass:
1010 case Stmt::StringLiteralClass: {
1011 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Ted Kremenek082d9362009-03-20 21:35:28 +00001013 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001014 StrE = ObjCFExpr->getString();
1015 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001016 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Ted Kremenekd30ef872009-01-12 23:09:09 +00001018 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001019 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1020 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001021 return true;
1022 }
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Ted Kremenekd30ef872009-01-12 23:09:09 +00001024 return false;
1025 }
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Ted Kremenek082d9362009-03-20 21:35:28 +00001027 default:
1028 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001029 }
1030}
1031
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001032void
Mike Stump1eb44332009-09-09 15:08:12 +00001033Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001034 const Expr * const *ExprArgs,
1035 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001036 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1037 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001038 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001039 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001040 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001041 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001042 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001043 }
1044}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001045
Ted Kremenek826a3452010-07-16 02:11:22 +00001046/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1047/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001048void
Ted Kremenek826a3452010-07-16 02:11:22 +00001049Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1050 unsigned format_idx, unsigned firstDataArg,
1051 bool isPrintf) {
1052
Ted Kremenek082d9362009-03-20 21:35:28 +00001053 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001054
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001055 // The way the format attribute works in GCC, the implicit this argument
1056 // of member functions is counted. However, it doesn't appear in our own
1057 // lists, so decrement format_idx in that case.
1058 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001059 const CXXMethodDecl *method_decl =
1060 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1061 if (method_decl && method_decl->isInstance()) {
1062 // Catch a format attribute mistakenly referring to the object argument.
1063 if (format_idx == 0)
1064 return;
1065 --format_idx;
1066 if(firstDataArg != 0)
1067 --firstDataArg;
1068 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001069 }
1070
Ted Kremenek826a3452010-07-16 02:11:22 +00001071 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001072 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001073 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001074 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001075 return;
1076 }
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Ted Kremenek082d9362009-03-20 21:35:28 +00001078 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Chris Lattner59907c42007-08-10 20:18:51 +00001080 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001081 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001082 // Dynamically generated format strings are difficult to
1083 // automatically vet at compile time. Requiring that format strings
1084 // are string literals: (1) permits the checking of format strings by
1085 // the compiler and thereby (2) can practically remove the source of
1086 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001087
Mike Stump1eb44332009-09-09 15:08:12 +00001088 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001089 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001090 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001091 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001092 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001093 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001094 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001095
Chris Lattner655f1412009-04-29 04:59:47 +00001096 // If there are no arguments specified, warn with -Wformat-security, otherwise
1097 // warn only with -Wformat-nonliteral.
1098 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001099 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001100 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001101 << OrigFormatExpr->getSourceRange();
1102 else
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)
Chris Lattner655f1412009-04-29 04:59:47 +00001105 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001106}
Ted Kremenek71895b92007-08-14 17:39:48 +00001107
Ted Kremeneke0e53132010-01-28 23:39:18 +00001108namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001109class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1110protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001111 Sema &S;
1112 const StringLiteral *FExpr;
1113 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001114 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001115 const unsigned NumDataArgs;
1116 const bool IsObjCLiteral;
1117 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001118 const bool HasVAListArg;
1119 const CallExpr *TheCall;
1120 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001121 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001122 bool usesPositionalArgs;
1123 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001124public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001125 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001126 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001127 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001128 const char *beg, bool hasVAListArg,
1129 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001130 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001131 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001132 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001133 IsObjCLiteral(isObjCLiteral), Beg(beg),
1134 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001135 TheCall(theCall), FormatIdx(formatIdx),
1136 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001137 CoveredArgs.resize(numDataArgs);
1138 CoveredArgs.reset();
1139 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001140
Ted Kremenek07d161f2010-01-29 01:50:07 +00001141 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001142
Ted Kremenek826a3452010-07-16 02:11:22 +00001143 void HandleIncompleteSpecifier(const char *startSpecifier,
1144 unsigned specifierLen);
1145
Ted Kremenekefaff192010-02-27 01:41:03 +00001146 virtual void HandleInvalidPosition(const char *startSpecifier,
1147 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001148 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001149
1150 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1151
Ted Kremeneke0e53132010-01-28 23:39:18 +00001152 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001153
Ted Kremenek826a3452010-07-16 02:11:22 +00001154protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001155 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1156 const char *startSpec,
1157 unsigned specifierLen,
1158 const char *csStart, unsigned csLen);
1159
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001160 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001161 CharSourceRange getSpecifierRange(const char *startSpecifier,
1162 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001163 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001164
Ted Kremenek0d277352010-01-29 01:06:55 +00001165 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001166
1167 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1168 const analyze_format_string::ConversionSpecifier &CS,
1169 const char *startSpecifier, unsigned specifierLen,
1170 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001171};
1172}
1173
Ted Kremenek826a3452010-07-16 02:11:22 +00001174SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001175 return OrigFormatExpr->getSourceRange();
1176}
1177
Ted Kremenek826a3452010-07-16 02:11:22 +00001178CharSourceRange CheckFormatHandler::
1179getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001180 SourceLocation Start = getLocationOfByte(startSpecifier);
1181 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1182
1183 // Advance the end SourceLocation by one due to half-open ranges.
1184 End = End.getFileLocWithOffset(1);
1185
1186 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001187}
1188
Ted Kremenek826a3452010-07-16 02:11:22 +00001189SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001190 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001191}
1192
Ted Kremenek826a3452010-07-16 02:11:22 +00001193void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1194 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001195 SourceLocation Loc = getLocationOfByte(startSpecifier);
1196 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001197 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001198}
1199
Ted Kremenekefaff192010-02-27 01:41:03 +00001200void
Ted Kremenek826a3452010-07-16 02:11:22 +00001201CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1202 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001203 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001204 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1205 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001206}
1207
Ted Kremenek826a3452010-07-16 02:11:22 +00001208void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001209 unsigned posLen) {
1210 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001211 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1212 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001213}
1214
Ted Kremenek826a3452010-07-16 02:11:22 +00001215void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001216 if (!IsObjCLiteral) {
1217 // The presence of a null character is likely an error.
1218 S.Diag(getLocationOfByte(nullCharacter),
1219 diag::warn_printf_format_string_contains_null_char)
1220 << getFormatStringRange();
1221 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001222}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001223
Ted Kremenek826a3452010-07-16 02:11:22 +00001224const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1225 return TheCall->getArg(FirstDataArg + i);
1226}
1227
1228void CheckFormatHandler::DoneProcessing() {
1229 // Does the number of data arguments exceed the number of
1230 // format conversions in the format string?
1231 if (!HasVAListArg) {
1232 // Find any arguments that weren't covered.
1233 CoveredArgs.flip();
1234 signed notCoveredArg = CoveredArgs.find_first();
1235 if (notCoveredArg >= 0) {
1236 assert((unsigned)notCoveredArg < NumDataArgs);
1237 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1238 diag::warn_printf_data_arg_not_used)
1239 << getFormatStringRange();
1240 }
1241 }
1242}
1243
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001244bool
1245CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1246 SourceLocation Loc,
1247 const char *startSpec,
1248 unsigned specifierLen,
1249 const char *csStart,
1250 unsigned csLen) {
1251
1252 bool keepGoing = true;
1253 if (argIndex < NumDataArgs) {
1254 // Consider the argument coverered, even though the specifier doesn't
1255 // make sense.
1256 CoveredArgs.set(argIndex);
1257 }
1258 else {
1259 // If argIndex exceeds the number of data arguments we
1260 // don't issue a warning because that is just a cascade of warnings (and
1261 // they may have intended '%%' anyway). We don't want to continue processing
1262 // the format string after this point, however, as we will like just get
1263 // gibberish when trying to match arguments.
1264 keepGoing = false;
1265 }
1266
1267 S.Diag(Loc, diag::warn_format_invalid_conversion)
1268 << llvm::StringRef(csStart, csLen)
1269 << getSpecifierRange(startSpec, specifierLen);
1270
1271 return keepGoing;
1272}
1273
Ted Kremenek666a1972010-07-26 19:45:42 +00001274bool
1275CheckFormatHandler::CheckNumArgs(
1276 const analyze_format_string::FormatSpecifier &FS,
1277 const analyze_format_string::ConversionSpecifier &CS,
1278 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1279
1280 if (argIndex >= NumDataArgs) {
1281 if (FS.usesPositionalArg()) {
1282 S.Diag(getLocationOfByte(CS.getStart()),
1283 diag::warn_printf_positional_arg_exceeds_data_args)
1284 << (argIndex+1) << NumDataArgs
1285 << getSpecifierRange(startSpecifier, specifierLen);
1286 }
1287 else {
1288 S.Diag(getLocationOfByte(CS.getStart()),
1289 diag::warn_printf_insufficient_data_args)
1290 << getSpecifierRange(startSpecifier, specifierLen);
1291 }
1292
1293 return false;
1294 }
1295 return true;
1296}
1297
Ted Kremenek826a3452010-07-16 02:11:22 +00001298//===--- CHECK: Printf format string checking ------------------------------===//
1299
1300namespace {
1301class CheckPrintfHandler : public CheckFormatHandler {
1302public:
1303 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1304 const Expr *origFormatExpr, unsigned firstDataArg,
1305 unsigned numDataArgs, bool isObjCLiteral,
1306 const char *beg, bool hasVAListArg,
1307 const CallExpr *theCall, unsigned formatIdx)
1308 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1309 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1310 theCall, formatIdx) {}
1311
1312
1313 bool HandleInvalidPrintfConversionSpecifier(
1314 const analyze_printf::PrintfSpecifier &FS,
1315 const char *startSpecifier,
1316 unsigned specifierLen);
1317
1318 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1319 const char *startSpecifier,
1320 unsigned specifierLen);
1321
1322 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1323 const char *startSpecifier, unsigned specifierLen);
1324 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1325 const analyze_printf::OptionalAmount &Amt,
1326 unsigned type,
1327 const char *startSpecifier, unsigned specifierLen);
1328 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1329 const analyze_printf::OptionalFlag &flag,
1330 const char *startSpecifier, unsigned specifierLen);
1331 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1332 const analyze_printf::OptionalFlag &ignoredFlag,
1333 const analyze_printf::OptionalFlag &flag,
1334 const char *startSpecifier, unsigned specifierLen);
1335};
1336}
1337
1338bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1339 const analyze_printf::PrintfSpecifier &FS,
1340 const char *startSpecifier,
1341 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001342 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001343 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001344
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001345 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1346 getLocationOfByte(CS.getStart()),
1347 startSpecifier, specifierLen,
1348 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001349}
1350
Ted Kremenek826a3452010-07-16 02:11:22 +00001351bool CheckPrintfHandler::HandleAmount(
1352 const analyze_format_string::OptionalAmount &Amt,
1353 unsigned k, const char *startSpecifier,
1354 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001355
1356 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001357 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001358 unsigned argIndex = Amt.getArgIndex();
1359 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001360 S.Diag(getLocationOfByte(Amt.getStart()),
1361 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001362 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001363 // Don't do any more checking. We will just emit
1364 // spurious errors.
1365 return false;
1366 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001367
Ted Kremenek0d277352010-01-29 01:06:55 +00001368 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001369 // Although not in conformance with C99, we also allow the argument to be
1370 // an 'unsigned int' as that is a reasonably safe case. GCC also
1371 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001372 CoveredArgs.set(argIndex);
1373 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001374 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001375
1376 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1377 assert(ATR.isValid());
1378
1379 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001380 S.Diag(getLocationOfByte(Amt.getStart()),
1381 diag::warn_printf_asterisk_wrong_type)
1382 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001383 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001384 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001385 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001386 // Don't do any more checking. We will just emit
1387 // spurious errors.
1388 return false;
1389 }
1390 }
1391 }
1392 return true;
1393}
Ted Kremenek0d277352010-01-29 01:06:55 +00001394
Tom Caree4ee9662010-06-17 19:00:27 +00001395void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001396 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001397 const analyze_printf::OptionalAmount &Amt,
1398 unsigned type,
1399 const char *startSpecifier,
1400 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001401 const analyze_printf::PrintfConversionSpecifier &CS =
1402 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001403 switch (Amt.getHowSpecified()) {
1404 case analyze_printf::OptionalAmount::Constant:
1405 S.Diag(getLocationOfByte(Amt.getStart()),
1406 diag::warn_printf_nonsensical_optional_amount)
1407 << type
1408 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001409 << getSpecifierRange(startSpecifier, specifierLen)
1410 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001411 Amt.getConstantLength()));
1412 break;
1413
1414 default:
1415 S.Diag(getLocationOfByte(Amt.getStart()),
1416 diag::warn_printf_nonsensical_optional_amount)
1417 << type
1418 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001419 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001420 break;
1421 }
1422}
1423
Ted Kremenek826a3452010-07-16 02:11:22 +00001424void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001425 const analyze_printf::OptionalFlag &flag,
1426 const char *startSpecifier,
1427 unsigned specifierLen) {
1428 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001429 const analyze_printf::PrintfConversionSpecifier &CS =
1430 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001431 S.Diag(getLocationOfByte(flag.getPosition()),
1432 diag::warn_printf_nonsensical_flag)
1433 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001434 << getSpecifierRange(startSpecifier, specifierLen)
1435 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001436}
1437
1438void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001439 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001440 const analyze_printf::OptionalFlag &ignoredFlag,
1441 const analyze_printf::OptionalFlag &flag,
1442 const char *startSpecifier,
1443 unsigned specifierLen) {
1444 // Warn about ignored flag with a fixit removal.
1445 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1446 diag::warn_printf_ignored_flag)
1447 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001448 << getSpecifierRange(startSpecifier, specifierLen)
1449 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001450 ignoredFlag.getPosition(), 1));
1451}
1452
Ted Kremeneke0e53132010-01-28 23:39:18 +00001453bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001454CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001455 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001456 const char *startSpecifier,
1457 unsigned specifierLen) {
1458
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001459 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001460 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001461 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001462
Ted Kremenekbaa40062010-07-19 22:01:06 +00001463 if (FS.consumesDataArgument()) {
1464 if (atFirstArg) {
1465 atFirstArg = false;
1466 usesPositionalArgs = FS.usesPositionalArg();
1467 }
1468 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1469 // Cannot mix-and-match positional and non-positional arguments.
1470 S.Diag(getLocationOfByte(CS.getStart()),
1471 diag::warn_format_mix_positional_nonpositional_args)
1472 << getSpecifierRange(startSpecifier, specifierLen);
1473 return false;
1474 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001475 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001476
Ted Kremenekefaff192010-02-27 01:41:03 +00001477 // First check if the field width, precision, and conversion specifier
1478 // have matching data arguments.
1479 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1480 startSpecifier, specifierLen)) {
1481 return false;
1482 }
1483
1484 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1485 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001486 return false;
1487 }
1488
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001489 if (!CS.consumesDataArgument()) {
1490 // FIXME: Technically specifying a precision or field width here
1491 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001492 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001493 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001494
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001495 // Consume the argument.
1496 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001497 if (argIndex < NumDataArgs) {
1498 // The check to see if the argIndex is valid will come later.
1499 // We set the bit here because we may exit early from this
1500 // function if we encounter some other error.
1501 CoveredArgs.set(argIndex);
1502 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001503
1504 // Check for using an Objective-C specific conversion specifier
1505 // in a non-ObjC literal.
1506 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001507 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1508 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001509 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001510
Tom Caree4ee9662010-06-17 19:00:27 +00001511 // Check for invalid use of field width
1512 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001513 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001514 startSpecifier, specifierLen);
1515 }
1516
1517 // Check for invalid use of precision
1518 if (!FS.hasValidPrecision()) {
1519 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1520 startSpecifier, specifierLen);
1521 }
1522
1523 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001524 if (!FS.hasValidThousandsGroupingPrefix())
1525 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001526 if (!FS.hasValidLeadingZeros())
1527 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1528 if (!FS.hasValidPlusPrefix())
1529 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001530 if (!FS.hasValidSpacePrefix())
1531 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001532 if (!FS.hasValidAlternativeForm())
1533 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1534 if (!FS.hasValidLeftJustified())
1535 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1536
1537 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001538 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1539 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1540 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001541 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1542 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1543 startSpecifier, specifierLen);
1544
1545 // Check the length modifier is valid with the given conversion specifier.
1546 const LengthModifier &LM = FS.getLengthModifier();
1547 if (!FS.hasValidLengthModifier())
1548 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001549 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001550 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001551 << getSpecifierRange(startSpecifier, specifierLen)
1552 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001553 LM.getLength()));
1554
1555 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001556 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001557 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001558 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001559 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001560 // Continue checking the other format specifiers.
1561 return true;
1562 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001563
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001564 // The remaining checks depend on the data arguments.
1565 if (HasVAListArg)
1566 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001567
Ted Kremenek666a1972010-07-26 19:45:42 +00001568 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001569 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001570
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001571 // Now type check the data expression that matches the
1572 // format specifier.
1573 const Expr *Ex = getDataArg(argIndex);
1574 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1575 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1576 // Check if we didn't match because of an implicit cast from a 'char'
1577 // or 'short' to an 'int'. This is done because printf is a varargs
1578 // function.
1579 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001580 if (ICE->getType() == S.Context.IntTy) {
1581 // All further checking is done on the subexpression.
1582 Ex = ICE->getSubExpr();
1583 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001584 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001585 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001586
1587 // We may be able to offer a FixItHint if it is a supported type.
1588 PrintfSpecifier fixedFS = FS;
1589 bool success = fixedFS.fixType(Ex->getType());
1590
1591 if (success) {
1592 // Get the fix string from the fixed format specifier
1593 llvm::SmallString<128> buf;
1594 llvm::raw_svector_ostream os(buf);
1595 fixedFS.toString(os);
1596
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001597 // FIXME: getRepresentativeType() perhaps should return a string
1598 // instead of a QualType to better handle when the representative
1599 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001600 S.Diag(getLocationOfByte(CS.getStart()),
1601 diag::warn_printf_conversion_argument_type_mismatch)
1602 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1603 << getSpecifierRange(startSpecifier, specifierLen)
1604 << Ex->getSourceRange()
1605 << FixItHint::CreateReplacement(
1606 getSpecifierRange(startSpecifier, specifierLen),
1607 os.str());
1608 }
1609 else {
1610 S.Diag(getLocationOfByte(CS.getStart()),
1611 diag::warn_printf_conversion_argument_type_mismatch)
1612 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1613 << getSpecifierRange(startSpecifier, specifierLen)
1614 << Ex->getSourceRange();
1615 }
1616 }
1617
Ted Kremeneke0e53132010-01-28 23:39:18 +00001618 return true;
1619}
1620
Ted Kremenek826a3452010-07-16 02:11:22 +00001621//===--- CHECK: Scanf format string checking ------------------------------===//
1622
1623namespace {
1624class CheckScanfHandler : public CheckFormatHandler {
1625public:
1626 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1627 const Expr *origFormatExpr, unsigned firstDataArg,
1628 unsigned numDataArgs, bool isObjCLiteral,
1629 const char *beg, bool hasVAListArg,
1630 const CallExpr *theCall, unsigned formatIdx)
1631 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1632 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1633 theCall, formatIdx) {}
1634
1635 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1636 const char *startSpecifier,
1637 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001638
1639 bool HandleInvalidScanfConversionSpecifier(
1640 const analyze_scanf::ScanfSpecifier &FS,
1641 const char *startSpecifier,
1642 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001643
1644 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001645};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001646}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001647
Ted Kremenekb7c21012010-07-16 18:28:03 +00001648void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1649 const char *end) {
1650 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1651 << getSpecifierRange(start, end - start);
1652}
1653
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001654bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1655 const analyze_scanf::ScanfSpecifier &FS,
1656 const char *startSpecifier,
1657 unsigned specifierLen) {
1658
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001659 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001660 FS.getConversionSpecifier();
1661
1662 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1663 getLocationOfByte(CS.getStart()),
1664 startSpecifier, specifierLen,
1665 CS.getStart(), CS.getLength());
1666}
1667
Ted Kremenek826a3452010-07-16 02:11:22 +00001668bool CheckScanfHandler::HandleScanfSpecifier(
1669 const analyze_scanf::ScanfSpecifier &FS,
1670 const char *startSpecifier,
1671 unsigned specifierLen) {
1672
1673 using namespace analyze_scanf;
1674 using namespace analyze_format_string;
1675
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001676 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001677
Ted Kremenekbaa40062010-07-19 22:01:06 +00001678 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1679 // be used to decide if we are using positional arguments consistently.
1680 if (FS.consumesDataArgument()) {
1681 if (atFirstArg) {
1682 atFirstArg = false;
1683 usesPositionalArgs = FS.usesPositionalArg();
1684 }
1685 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1686 // Cannot mix-and-match positional and non-positional arguments.
1687 S.Diag(getLocationOfByte(CS.getStart()),
1688 diag::warn_format_mix_positional_nonpositional_args)
1689 << getSpecifierRange(startSpecifier, specifierLen);
1690 return false;
1691 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001692 }
1693
1694 // Check if the field with is non-zero.
1695 const OptionalAmount &Amt = FS.getFieldWidth();
1696 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1697 if (Amt.getConstantAmount() == 0) {
1698 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1699 Amt.getConstantLength());
1700 S.Diag(getLocationOfByte(Amt.getStart()),
1701 diag::warn_scanf_nonzero_width)
1702 << R << FixItHint::CreateRemoval(R);
1703 }
1704 }
1705
1706 if (!FS.consumesDataArgument()) {
1707 // FIXME: Technically specifying a precision or field width here
1708 // makes no sense. Worth issuing a warning at some point.
1709 return true;
1710 }
1711
1712 // Consume the argument.
1713 unsigned argIndex = FS.getArgIndex();
1714 if (argIndex < NumDataArgs) {
1715 // The check to see if the argIndex is valid will come later.
1716 // We set the bit here because we may exit early from this
1717 // function if we encounter some other error.
1718 CoveredArgs.set(argIndex);
1719 }
1720
Ted Kremenek1e51c202010-07-20 20:04:47 +00001721 // Check the length modifier is valid with the given conversion specifier.
1722 const LengthModifier &LM = FS.getLengthModifier();
1723 if (!FS.hasValidLengthModifier()) {
1724 S.Diag(getLocationOfByte(LM.getStart()),
1725 diag::warn_format_nonsensical_length)
1726 << LM.toString() << CS.toString()
1727 << getSpecifierRange(startSpecifier, specifierLen)
1728 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1729 LM.getLength()));
1730 }
1731
Ted Kremenek826a3452010-07-16 02:11:22 +00001732 // The remaining checks depend on the data arguments.
1733 if (HasVAListArg)
1734 return true;
1735
Ted Kremenek666a1972010-07-26 19:45:42 +00001736 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001737 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001738
1739 // FIXME: Check that the argument type matches the format specifier.
1740
1741 return true;
1742}
1743
1744void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001745 const Expr *OrigFormatExpr,
1746 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001747 unsigned format_idx, unsigned firstDataArg,
1748 bool isPrintf) {
1749
Ted Kremeneke0e53132010-01-28 23:39:18 +00001750 // CHECK: is the format string a wide literal?
1751 if (FExpr->isWide()) {
1752 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001753 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001754 << OrigFormatExpr->getSourceRange();
1755 return;
1756 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001757
Ted Kremeneke0e53132010-01-28 23:39:18 +00001758 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001759 llvm::StringRef StrRef = FExpr->getString();
1760 const char *Str = StrRef.data();
1761 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001762
Ted Kremeneke0e53132010-01-28 23:39:18 +00001763 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001764 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001765 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001766 << OrigFormatExpr->getSourceRange();
1767 return;
1768 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001769
1770 if (isPrintf) {
1771 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1772 TheCall->getNumArgs() - firstDataArg,
1773 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1774 HasVAListArg, TheCall, format_idx);
1775
1776 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1777 H.DoneProcessing();
1778 }
1779 else {
1780 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1781 TheCall->getNumArgs() - firstDataArg,
1782 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1783 HasVAListArg, TheCall, format_idx);
1784
1785 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1786 H.DoneProcessing();
1787 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001788}
1789
Ted Kremenek06de2762007-08-17 16:46:58 +00001790//===--- CHECK: Return Address of Stack Variable --------------------------===//
1791
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001792static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1793static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001794
1795/// CheckReturnStackAddr - Check if a return statement returns the address
1796/// of a stack variable.
1797void
1798Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1799 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001801 Expr *stackE = 0;
1802 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1803
1804 // Perform checking for returned stack addresses, local blocks,
1805 // label addresses or references to temporaries.
Steve Naroffdd972f22008-09-05 22:11:13 +00001806 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001807 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001808 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001809 stackE = EvalVal(RetValExp, refVars);
1810 }
1811
1812 if (stackE == 0)
1813 return; // Nothing suspicious was found.
1814
1815 SourceLocation diagLoc;
1816 SourceRange diagRange;
1817 if (refVars.empty()) {
1818 diagLoc = stackE->getLocStart();
1819 diagRange = stackE->getSourceRange();
1820 } else {
1821 // We followed through a reference variable. 'stackE' contains the
1822 // problematic expression but we will warn at the return statement pointing
1823 // at the reference variable. We will later display the "trail" of
1824 // reference variables using notes.
1825 diagLoc = refVars[0]->getLocStart();
1826 diagRange = refVars[0]->getSourceRange();
1827 }
1828
1829 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1830 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1831 : diag::warn_ret_stack_addr)
1832 << DR->getDecl()->getDeclName() << diagRange;
1833 } else if (isa<BlockExpr>(stackE)) { // local block.
1834 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1835 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1836 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1837 } else { // local temporary.
1838 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1839 : diag::warn_ret_local_temp_addr)
1840 << diagRange;
1841 }
1842
1843 // Display the "trail" of reference variables that we followed until we
1844 // found the problematic expression using notes.
1845 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1846 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1847 // If this var binds to another reference var, show the range of the next
1848 // var, otherwise the var binds to the problematic expression, in which case
1849 // show the range of the expression.
1850 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1851 : stackE->getSourceRange();
1852 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1853 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00001854 }
1855}
1856
1857/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1858/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001859/// to a location on the stack, a local block, an address of a label, or a
1860/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00001861/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001862/// encounter a subexpression that (1) clearly does not lead to one of the
1863/// above problematic expressions (2) is something we cannot determine leads to
1864/// a problematic expression based on such local checking.
1865///
1866/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1867/// the expression that they point to. Such variables are added to the
1868/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00001869///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001870/// EvalAddr processes expressions that are pointers that are used as
1871/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001872/// At the base case of the recursion is a check for the above problematic
1873/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00001874///
1875/// This implementation handles:
1876///
1877/// * pointer-to-pointer casts
1878/// * implicit conversions from array references to pointers
1879/// * taking the address of fields
1880/// * arbitrary interplay between "&" and "*" operators
1881/// * pointer arithmetic from an address of a stack variable
1882/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001883static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1884 if (E->isTypeDependent())
1885 return NULL;
1886
Ted Kremenek06de2762007-08-17 16:46:58 +00001887 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001888 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001889 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001890 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001891 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Ted Kremenek06de2762007-08-17 16:46:58 +00001893 // Our "symbolic interpreter" is just a dispatch off the currently
1894 // viewed AST node. We then recursively traverse the AST by calling
1895 // EvalAddr and EvalVal appropriately.
1896 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001897 case Stmt::ParenExprClass:
1898 // Ignore parentheses.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001899 return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1900
1901 case Stmt::DeclRefExprClass: {
1902 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1903
1904 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1905 // If this is a reference variable, follow through to the expression that
1906 // it points to.
1907 if (V->hasLocalStorage() &&
1908 V->getType()->isReferenceType() && V->hasInit()) {
1909 // Add the reference variable to the "trail".
1910 refVars.push_back(DR);
1911 return EvalAddr(V->getInit(), refVars);
1912 }
1913
1914 return NULL;
1915 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001916
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001917 case Stmt::UnaryOperatorClass: {
1918 // The only unary operator that make sense to handle here
1919 // is AddrOf. All others don't make sense as pointers.
1920 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001921
John McCall2de56d12010-08-25 11:45:40 +00001922 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001923 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001924 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001925 return NULL;
1926 }
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001928 case Stmt::BinaryOperatorClass: {
1929 // Handle pointer arithmetic. All other binary operators are not valid
1930 // in this context.
1931 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001932 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001933
John McCall2de56d12010-08-25 11:45:40 +00001934 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001935 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001937 Expr *Base = B->getLHS();
1938
1939 // Determine which argument is the real pointer base. It could be
1940 // the RHS argument instead of the LHS.
1941 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001943 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001944 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001945 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001946
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001947 // For conditional operators we need to see if either the LHS or RHS are
1948 // valid DeclRefExpr*s. If one of them is valid, we return it.
1949 case Stmt::ConditionalOperatorClass: {
1950 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001952 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001953 if (Expr *lhsExpr = C->getLHS()) {
1954 // In C++, we can have a throw-expression, which has 'void' type.
1955 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001956 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001957 return LHS;
1958 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001959
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001960 // In C++, we can have a throw-expression, which has 'void' type.
1961 if (C->getRHS()->getType()->isVoidType())
1962 return NULL;
1963
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001964 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001965 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001966
1967 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00001968 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001969 return E; // local block.
1970 return NULL;
1971
1972 case Stmt::AddrLabelExprClass:
1973 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Ted Kremenek54b52742008-08-07 00:49:01 +00001975 // For casts, we need to handle conversions from arrays to
1976 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001977 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001978 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001979 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001980 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001981 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Steve Naroffdd972f22008-09-05 22:11:13 +00001983 if (SubExpr->getType()->isPointerType() ||
1984 SubExpr->getType()->isBlockPointerType() ||
1985 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001986 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00001987 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001988 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001989 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001990 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001991 }
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001993 // C++ casts. For dynamic casts, static casts, and const casts, we
1994 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001995 // through the cast. In the case the dynamic cast doesn't fail (and
1996 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001997 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001998 // FIXME: The comment about is wrong; we're not always converting
1999 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002000 // handle references to objects.
2001 case Stmt::CXXStaticCastExprClass:
2002 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002003 case Stmt::CXXConstCastExprClass:
2004 case Stmt::CXXReinterpretCastExprClass: {
2005 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002006 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002007 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002008 else
2009 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002010 }
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002012 // Everything else: we simply don't reason about them.
2013 default:
2014 return NULL;
2015 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002016}
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Ted Kremenek06de2762007-08-17 16:46:58 +00002018
2019/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2020/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002021static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002022do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002023 // We should only be called for evaluating non-pointer expressions, or
2024 // expressions with a pointer type that are not used as references but instead
2025 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Ted Kremenek06de2762007-08-17 16:46:58 +00002027 // Our "symbolic interpreter" is just a dispatch off the currently
2028 // viewed AST node. We then recursively traverse the AST by calling
2029 // EvalAddr and EvalVal appropriately.
2030 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002031 case Stmt::ImplicitCastExprClass: {
2032 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002033 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002034 E = IE->getSubExpr();
2035 continue;
2036 }
2037 return NULL;
2038 }
2039
Douglas Gregora2813ce2009-10-23 18:54:35 +00002040 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002041 // When we hit a DeclRefExpr we are looking at code that refers to a
2042 // variable's name. If it's not a reference variable we check if it has
2043 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002044 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Ted Kremenek06de2762007-08-17 16:46:58 +00002046 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002047 if (V->hasLocalStorage()) {
2048 if (!V->getType()->isReferenceType())
2049 return DR;
2050
2051 // Reference variable, follow through to the expression that
2052 // it points to.
2053 if (V->hasInit()) {
2054 // Add the reference variable to the "trail".
2055 refVars.push_back(DR);
2056 return EvalVal(V->getInit(), refVars);
2057 }
2058 }
Mike Stump1eb44332009-09-09 15:08:12 +00002059
Ted Kremenek06de2762007-08-17 16:46:58 +00002060 return NULL;
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Ted Kremenek68957a92010-08-04 20:01:07 +00002063 case Stmt::ParenExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002064 // Ignore parentheses.
Ted Kremenek68957a92010-08-04 20:01:07 +00002065 E = cast<ParenExpr>(E)->getSubExpr();
2066 continue;
2067 }
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Ted Kremenek06de2762007-08-17 16:46:58 +00002069 case Stmt::UnaryOperatorClass: {
2070 // The only unary operator that make sense to handle here
2071 // is Deref. All others don't resolve to a "name." This includes
2072 // handling all sorts of rvalues passed to a unary operator.
2073 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002074
John McCall2de56d12010-08-25 11:45:40 +00002075 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002076 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002077
2078 return NULL;
2079 }
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Ted Kremenek06de2762007-08-17 16:46:58 +00002081 case Stmt::ArraySubscriptExprClass: {
2082 // Array subscripts are potential references to data on the stack. We
2083 // retrieve the DeclRefExpr* for the array variable if it indeed
2084 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002085 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002086 }
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Ted Kremenek06de2762007-08-17 16:46:58 +00002088 case Stmt::ConditionalOperatorClass: {
2089 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002090 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002091 ConditionalOperator *C = cast<ConditionalOperator>(E);
2092
Anders Carlsson39073232007-11-30 19:04:31 +00002093 // Handle the GNU extension for missing LHS.
2094 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002095 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002096 return LHS;
2097
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002098 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002099 }
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Ted Kremenek06de2762007-08-17 16:46:58 +00002101 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002102 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002103 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Ted Kremenek06de2762007-08-17 16:46:58 +00002105 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002106 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002107 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002108
2109 // Check whether the member type is itself a reference, in which case
2110 // we're not going to refer to the member, but to what the member refers to.
2111 if (M->getMemberDecl()->getType()->isReferenceType())
2112 return NULL;
2113
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002114 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002115 }
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Ted Kremenek06de2762007-08-17 16:46:58 +00002117 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002118 // Check that we don't return or take the address of a reference to a
2119 // temporary. This is only useful in C++.
2120 if (!E->isTypeDependent() && E->isRValue())
2121 return E;
2122
2123 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002124 return NULL;
2125 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002126} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002127}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002128
2129//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2130
2131/// Check for comparisons of floating point operands using != and ==.
2132/// Issue a warning if these are no self-comparisons, as they are not likely
2133/// to do what the programmer intended.
2134void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2135 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002136
John McCallf6a16482010-12-04 03:47:34 +00002137 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2138 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002139
2140 // Special case: check for x == x (which is OK).
2141 // Do not emit warnings for such cases.
2142 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2143 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2144 if (DRL->getDecl() == DRR->getDecl())
2145 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002146
2147
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002148 // Special case: check for comparisons against literals that can be exactly
2149 // represented by APFloat. In such cases, do not emit a warning. This
2150 // is a heuristic: often comparison against such literals are used to
2151 // detect if a value in a variable has not changed. This clearly can
2152 // lead to false negatives.
2153 if (EmitWarning) {
2154 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2155 if (FLL->isExact())
2156 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002157 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002158 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2159 if (FLR->isExact())
2160 EmitWarning = false;
2161 }
2162 }
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002164 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002165 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002166 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002167 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002168 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Sebastian Redl0eb23302009-01-19 00:08:26 +00002170 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002171 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002172 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002173 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002175 // Emit the diagnostic.
2176 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002177 Diag(loc, diag::warn_floatingpoint_eq)
2178 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002179}
John McCallba26e582010-01-04 23:21:16 +00002180
John McCallf2370c92010-01-06 05:24:50 +00002181//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2182//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002183
John McCallf2370c92010-01-06 05:24:50 +00002184namespace {
John McCallba26e582010-01-04 23:21:16 +00002185
John McCallf2370c92010-01-06 05:24:50 +00002186/// Structure recording the 'active' range of an integer-valued
2187/// expression.
2188struct IntRange {
2189 /// The number of bits active in the int.
2190 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002191
John McCallf2370c92010-01-06 05:24:50 +00002192 /// True if the int is known not to have negative values.
2193 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002194
John McCallf2370c92010-01-06 05:24:50 +00002195 IntRange(unsigned Width, bool NonNegative)
2196 : Width(Width), NonNegative(NonNegative)
2197 {}
John McCallba26e582010-01-04 23:21:16 +00002198
John McCall1844a6e2010-11-10 23:38:19 +00002199 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002200 static IntRange forBoolType() {
2201 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002202 }
2203
John McCall1844a6e2010-11-10 23:38:19 +00002204 /// Returns the range of an opaque value of the given integral type.
2205 static IntRange forValueOfType(ASTContext &C, QualType T) {
2206 return forValueOfCanonicalType(C,
2207 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002208 }
2209
John McCall1844a6e2010-11-10 23:38:19 +00002210 /// Returns the range of an opaque value of a canonical integral type.
2211 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002212 assert(T->isCanonicalUnqualified());
2213
2214 if (const VectorType *VT = dyn_cast<VectorType>(T))
2215 T = VT->getElementType().getTypePtr();
2216 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2217 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002218
John McCall091f23f2010-11-09 22:22:12 +00002219 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002220 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2221 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002222 if (!Enum->isDefinition())
2223 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2224
John McCall323ed742010-05-06 08:58:33 +00002225 unsigned NumPositive = Enum->getNumPositiveBits();
2226 unsigned NumNegative = Enum->getNumNegativeBits();
2227
2228 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2229 }
John McCallf2370c92010-01-06 05:24:50 +00002230
2231 const BuiltinType *BT = cast<BuiltinType>(T);
2232 assert(BT->isInteger());
2233
2234 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2235 }
2236
John McCall1844a6e2010-11-10 23:38:19 +00002237 /// Returns the "target" range of a canonical integral type, i.e.
2238 /// the range of values expressible in the type.
2239 ///
2240 /// This matches forValueOfCanonicalType except that enums have the
2241 /// full range of their type, not the range of their enumerators.
2242 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2243 assert(T->isCanonicalUnqualified());
2244
2245 if (const VectorType *VT = dyn_cast<VectorType>(T))
2246 T = VT->getElementType().getTypePtr();
2247 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2248 T = CT->getElementType().getTypePtr();
2249 if (const EnumType *ET = dyn_cast<EnumType>(T))
2250 T = ET->getDecl()->getIntegerType().getTypePtr();
2251
2252 const BuiltinType *BT = cast<BuiltinType>(T);
2253 assert(BT->isInteger());
2254
2255 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2256 }
2257
2258 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002259 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002260 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002261 L.NonNegative && R.NonNegative);
2262 }
2263
John McCall1844a6e2010-11-10 23:38:19 +00002264 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002265 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002266 return IntRange(std::min(L.Width, R.Width),
2267 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002268 }
2269};
2270
2271IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2272 if (value.isSigned() && value.isNegative())
2273 return IntRange(value.getMinSignedBits(), false);
2274
2275 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002276 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002277
2278 // isNonNegative() just checks the sign bit without considering
2279 // signedness.
2280 return IntRange(value.getActiveBits(), true);
2281}
2282
John McCall0acc3112010-01-06 22:57:21 +00002283IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002284 unsigned MaxWidth) {
2285 if (result.isInt())
2286 return GetValueRange(C, result.getInt(), MaxWidth);
2287
2288 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002289 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2290 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2291 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2292 R = IntRange::join(R, El);
2293 }
John McCallf2370c92010-01-06 05:24:50 +00002294 return R;
2295 }
2296
2297 if (result.isComplexInt()) {
2298 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2299 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2300 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002301 }
2302
2303 // This can happen with lossless casts to intptr_t of "based" lvalues.
2304 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002305 // FIXME: The only reason we need to pass the type in here is to get
2306 // the sign right on this one case. It would be nice if APValue
2307 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002308 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002309 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002310}
John McCallf2370c92010-01-06 05:24:50 +00002311
2312/// Pseudo-evaluate the given integer expression, estimating the
2313/// range of values it might take.
2314///
2315/// \param MaxWidth - the width to which the value will be truncated
2316IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2317 E = E->IgnoreParens();
2318
2319 // Try a full evaluation first.
2320 Expr::EvalResult result;
2321 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002322 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002323
2324 // I think we only want to look through implicit casts here; if the
2325 // user has an explicit widening cast, we should treat the value as
2326 // being of the new, wider type.
2327 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002328 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002329 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2330
John McCall1844a6e2010-11-10 23:38:19 +00002331 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002332
John McCall2de56d12010-08-25 11:45:40 +00002333 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002334
John McCallf2370c92010-01-06 05:24:50 +00002335 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002336 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002337 return OutputTypeRange;
2338
2339 IntRange SubRange
2340 = GetExprRange(C, CE->getSubExpr(),
2341 std::min(MaxWidth, OutputTypeRange.Width));
2342
2343 // Bail out if the subexpr's range is as wide as the cast type.
2344 if (SubRange.Width >= OutputTypeRange.Width)
2345 return OutputTypeRange;
2346
2347 // Otherwise, we take the smaller width, and we're non-negative if
2348 // either the output type or the subexpr is.
2349 return IntRange(SubRange.Width,
2350 SubRange.NonNegative || OutputTypeRange.NonNegative);
2351 }
2352
2353 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2354 // If we can fold the condition, just take that operand.
2355 bool CondResult;
2356 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2357 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2358 : CO->getFalseExpr(),
2359 MaxWidth);
2360
2361 // Otherwise, conservatively merge.
2362 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2363 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2364 return IntRange::join(L, R);
2365 }
2366
2367 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2368 switch (BO->getOpcode()) {
2369
2370 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002371 case BO_LAnd:
2372 case BO_LOr:
2373 case BO_LT:
2374 case BO_GT:
2375 case BO_LE:
2376 case BO_GE:
2377 case BO_EQ:
2378 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002379 return IntRange::forBoolType();
2380
John McCallc0cd21d2010-02-23 19:22:29 +00002381 // The type of these compound assignments is the type of the LHS,
2382 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002383 case BO_MulAssign:
2384 case BO_DivAssign:
2385 case BO_RemAssign:
2386 case BO_AddAssign:
2387 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002388 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002389
John McCallf2370c92010-01-06 05:24:50 +00002390 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002391 case BO_PtrMemD:
2392 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002393 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002394
John McCall60fad452010-01-06 22:07:33 +00002395 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002396 case BO_And:
2397 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002398 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2399 GetExprRange(C, BO->getRHS(), MaxWidth));
2400
John McCallf2370c92010-01-06 05:24:50 +00002401 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002402 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002403 // ...except that we want to treat '1 << (blah)' as logically
2404 // positive. It's an important idiom.
2405 if (IntegerLiteral *I
2406 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2407 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002408 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002409 return IntRange(R.Width, /*NonNegative*/ true);
2410 }
2411 }
2412 // fallthrough
2413
John McCall2de56d12010-08-25 11:45:40 +00002414 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002415 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002416
John McCall60fad452010-01-06 22:07:33 +00002417 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002418 case BO_Shr:
2419 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002420 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2421
2422 // If the shift amount is a positive constant, drop the width by
2423 // that much.
2424 llvm::APSInt shift;
2425 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2426 shift.isNonNegative()) {
2427 unsigned zext = shift.getZExtValue();
2428 if (zext >= L.Width)
2429 L.Width = (L.NonNegative ? 0 : 1);
2430 else
2431 L.Width -= zext;
2432 }
2433
2434 return L;
2435 }
2436
2437 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002438 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002439 return GetExprRange(C, BO->getRHS(), MaxWidth);
2440
John McCall60fad452010-01-06 22:07:33 +00002441 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002442 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002443 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002444 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002445 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002446
John McCallf2370c92010-01-06 05:24:50 +00002447 default:
2448 break;
2449 }
2450
2451 // Treat every other operator as if it were closed on the
2452 // narrowest type that encompasses both operands.
2453 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2454 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2455 return IntRange::join(L, R);
2456 }
2457
2458 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2459 switch (UO->getOpcode()) {
2460 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002461 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002462 return IntRange::forBoolType();
2463
2464 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002465 case UO_Deref:
2466 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002467 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002468
2469 default:
2470 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2471 }
2472 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002473
2474 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002475 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002476 }
John McCallf2370c92010-01-06 05:24:50 +00002477
2478 FieldDecl *BitField = E->getBitField();
2479 if (BitField) {
2480 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2481 unsigned BitWidth = BitWidthAP.getZExtValue();
2482
2483 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2484 }
2485
John McCall1844a6e2010-11-10 23:38:19 +00002486 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002487}
John McCall51313c32010-01-04 23:31:57 +00002488
John McCall323ed742010-05-06 08:58:33 +00002489IntRange GetExprRange(ASTContext &C, Expr *E) {
2490 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2491}
2492
John McCall51313c32010-01-04 23:31:57 +00002493/// Checks whether the given value, which currently has the given
2494/// source semantics, has the same value when coerced through the
2495/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002496bool IsSameFloatAfterCast(const llvm::APFloat &value,
2497 const llvm::fltSemantics &Src,
2498 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002499 llvm::APFloat truncated = value;
2500
2501 bool ignored;
2502 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2503 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2504
2505 return truncated.bitwiseIsEqual(value);
2506}
2507
2508/// Checks whether the given value, which currently has the given
2509/// source semantics, has the same value when coerced through the
2510/// target semantics.
2511///
2512/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002513bool IsSameFloatAfterCast(const APValue &value,
2514 const llvm::fltSemantics &Src,
2515 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002516 if (value.isFloat())
2517 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2518
2519 if (value.isVector()) {
2520 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2521 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2522 return false;
2523 return true;
2524 }
2525
2526 assert(value.isComplexFloat());
2527 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2528 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2529}
2530
John McCallb4eb64d2010-10-08 02:01:28 +00002531void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002532
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002533static bool IsZero(Sema &S, Expr *E) {
2534 // Suppress cases where we are comparing against an enum constant.
2535 if (const DeclRefExpr *DR =
2536 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2537 if (isa<EnumConstantDecl>(DR->getDecl()))
2538 return false;
2539
2540 // Suppress cases where the '0' value is expanded from a macro.
2541 if (E->getLocStart().isMacroID())
2542 return false;
2543
John McCall323ed742010-05-06 08:58:33 +00002544 llvm::APSInt Value;
2545 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2546}
2547
John McCall372e1032010-10-06 00:25:24 +00002548static bool HasEnumType(Expr *E) {
2549 // Strip off implicit integral promotions.
2550 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002551 if (ICE->getCastKind() != CK_IntegralCast &&
2552 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002553 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002554 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002555 }
2556
2557 return E->getType()->isEnumeralType();
2558}
2559
John McCall323ed742010-05-06 08:58:33 +00002560void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002561 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002562 if (E->isValueDependent())
2563 return;
2564
John McCall2de56d12010-08-25 11:45:40 +00002565 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002566 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002567 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002568 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002569 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002570 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002571 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002572 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002573 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002574 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002575 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002576 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002577 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002578 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002579 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002580 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2581 }
2582}
2583
2584/// Analyze the operands of the given comparison. Implements the
2585/// fallback case from AnalyzeComparison.
2586void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002587 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2588 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002589}
John McCall51313c32010-01-04 23:31:57 +00002590
John McCallba26e582010-01-04 23:21:16 +00002591/// \brief Implements -Wsign-compare.
2592///
2593/// \param lex the left-hand expression
2594/// \param rex the right-hand expression
2595/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002596/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002597void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2598 // The type the comparison is being performed in.
2599 QualType T = E->getLHS()->getType();
2600 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2601 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002602
John McCall323ed742010-05-06 08:58:33 +00002603 // We don't do anything special if this isn't an unsigned integral
2604 // comparison: we're only interested in integral comparisons, and
2605 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002606 //
2607 // We also don't care about value-dependent expressions or expressions
2608 // whose result is a constant.
2609 if (!T->hasUnsignedIntegerRepresentation()
2610 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002611 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002612
John McCall323ed742010-05-06 08:58:33 +00002613 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2614 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002615
John McCall323ed742010-05-06 08:58:33 +00002616 // Check to see if one of the (unmodified) operands is of different
2617 // signedness.
2618 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002619 if (lex->getType()->hasSignedIntegerRepresentation()) {
2620 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002621 "unsigned comparison between two signed integer expressions?");
2622 signedOperand = lex;
2623 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002624 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002625 signedOperand = rex;
2626 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002627 } else {
John McCall323ed742010-05-06 08:58:33 +00002628 CheckTrivialUnsignedComparison(S, E);
2629 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002630 }
2631
John McCall323ed742010-05-06 08:58:33 +00002632 // Otherwise, calculate the effective range of the signed operand.
2633 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002634
John McCall323ed742010-05-06 08:58:33 +00002635 // Go ahead and analyze implicit conversions in the operands. Note
2636 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002637 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2638 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002639
John McCall323ed742010-05-06 08:58:33 +00002640 // If the signed range is non-negative, -Wsign-compare won't fire,
2641 // but we should still check for comparisons which are always true
2642 // or false.
2643 if (signedRange.NonNegative)
2644 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002645
2646 // For (in)equality comparisons, if the unsigned operand is a
2647 // constant which cannot collide with a overflowed signed operand,
2648 // then reinterpreting the signed operand as unsigned will not
2649 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002650 if (E->isEqualityOp()) {
2651 unsigned comparisonWidth = S.Context.getIntWidth(T);
2652 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002653
John McCall323ed742010-05-06 08:58:33 +00002654 // We should never be unable to prove that the unsigned operand is
2655 // non-negative.
2656 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2657
2658 if (unsignedRange.Width < comparisonWidth)
2659 return;
2660 }
2661
2662 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2663 << lex->getType() << rex->getType()
2664 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002665}
2666
John McCall15d7d122010-11-11 03:21:53 +00002667/// Analyzes an attempt to assign the given value to a bitfield.
2668///
2669/// Returns true if there was something fishy about the attempt.
2670bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2671 SourceLocation InitLoc) {
2672 assert(Bitfield->isBitField());
2673 if (Bitfield->isInvalidDecl())
2674 return false;
2675
John McCall91b60142010-11-11 05:33:51 +00002676 // White-list bool bitfields.
2677 if (Bitfield->getType()->isBooleanType())
2678 return false;
2679
Douglas Gregor46ff3032011-02-04 13:09:01 +00002680 // Ignore value- or type-dependent expressions.
2681 if (Bitfield->getBitWidth()->isValueDependent() ||
2682 Bitfield->getBitWidth()->isTypeDependent() ||
2683 Init->isValueDependent() ||
2684 Init->isTypeDependent())
2685 return false;
2686
John McCall15d7d122010-11-11 03:21:53 +00002687 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2688
2689 llvm::APSInt Width(32);
2690 Expr::EvalResult InitValue;
2691 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002692 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002693 !InitValue.Val.isInt())
2694 return false;
2695
2696 const llvm::APSInt &Value = InitValue.Val.getInt();
2697 unsigned OriginalWidth = Value.getBitWidth();
2698 unsigned FieldWidth = Width.getZExtValue();
2699
2700 if (OriginalWidth <= FieldWidth)
2701 return false;
2702
Jay Foad9f71a8f2010-12-07 08:25:34 +00002703 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002704
2705 // It's fairly common to write values into signed bitfields
2706 // that, if sign-extended, would end up becoming a different
2707 // value. We don't want to warn about that.
2708 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002709 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002710 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002711 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002712
2713 if (Value == TruncatedValue)
2714 return false;
2715
2716 std::string PrettyValue = Value.toString(10);
2717 std::string PrettyTrunc = TruncatedValue.toString(10);
2718
2719 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2720 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2721 << Init->getSourceRange();
2722
2723 return true;
2724}
2725
John McCallbeb22aa2010-11-09 23:24:47 +00002726/// Analyze the given simple or compound assignment for warning-worthy
2727/// operations.
2728void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2729 // Just recurse on the LHS.
2730 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2731
2732 // We want to recurse on the RHS as normal unless we're assigning to
2733 // a bitfield.
2734 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002735 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2736 E->getOperatorLoc())) {
2737 // Recurse, ignoring any implicit conversions on the RHS.
2738 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2739 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002740 }
2741 }
2742
2743 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2744}
2745
John McCall51313c32010-01-04 23:31:57 +00002746/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCallb4eb64d2010-10-08 02:01:28 +00002747void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2748 unsigned diag) {
2749 S.Diag(E->getExprLoc(), diag)
2750 << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
John McCall51313c32010-01-04 23:31:57 +00002751}
2752
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002753/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2754void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2755 SourceLocation CContext, unsigned diag) {
2756 S.Diag(E->getExprLoc(), diag)
2757 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2758}
2759
John McCall091f23f2010-11-09 22:22:12 +00002760std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2761 if (!Range.Width) return "0";
2762
2763 llvm::APSInt ValueInRange = Value;
2764 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002765 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002766 return ValueInRange.toString(10);
2767}
2768
Ted Kremenekef9ff882011-03-10 20:03:42 +00002769static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2770 SourceManager &smgr = S.Context.getSourceManager();
2771 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2772}
2773
John McCall323ed742010-05-06 08:58:33 +00002774void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002775 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002776 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002777
John McCall323ed742010-05-06 08:58:33 +00002778 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2779 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2780 if (Source == Target) return;
2781 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002782
Ted Kremenekef9ff882011-03-10 20:03:42 +00002783 // If the conversion context location is invalid don't complain.
2784 // We also don't want to emit a warning if the issue occurs from the
2785 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2786 // is slow, so we delay this check as long as possible. Once we detect
2787 // we are in that scenario, we just return.
2788 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00002789 return;
2790
John McCall51313c32010-01-04 23:31:57 +00002791 // Never diagnose implicit casts to bool.
2792 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2793 return;
2794
2795 // Strip vector types.
2796 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002797 if (!isa<VectorType>(Target)) {
2798 if (isFromSystemMacro(S, CC))
2799 return;
John McCallb4eb64d2010-10-08 02:01:28 +00002800 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002801 }
John McCall51313c32010-01-04 23:31:57 +00002802
2803 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2804 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2805 }
2806
2807 // Strip complex types.
2808 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002809 if (!isa<ComplexType>(Target)) {
2810 if (isFromSystemMacro(S, CC))
2811 return;
2812
John McCallb4eb64d2010-10-08 02:01:28 +00002813 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002814 }
John McCall51313c32010-01-04 23:31:57 +00002815
2816 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2817 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2818 }
2819
2820 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2821 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2822
2823 // If the source is floating point...
2824 if (SourceBT && SourceBT->isFloatingPoint()) {
2825 // ...and the target is floating point...
2826 if (TargetBT && TargetBT->isFloatingPoint()) {
2827 // ...then warn if we're dropping FP rank.
2828
2829 // Builtin FP kinds are ordered by increasing FP rank.
2830 if (SourceBT->getKind() > TargetBT->getKind()) {
2831 // Don't warn about float constants that are precisely
2832 // representable in the target type.
2833 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002834 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002835 // Value might be a float, a float vector, or a float complex.
2836 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002837 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2838 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002839 return;
2840 }
2841
Ted Kremenekef9ff882011-03-10 20:03:42 +00002842 if (isFromSystemMacro(S, CC))
2843 return;
2844
John McCallb4eb64d2010-10-08 02:01:28 +00002845 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002846 }
2847 return;
2848 }
2849
Ted Kremenekef9ff882011-03-10 20:03:42 +00002850 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00002851 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002852 if (isFromSystemMacro(S, CC))
2853 return;
2854
Chandler Carrutha5b93322011-02-17 11:05:49 +00002855 Expr *InnerE = E->IgnoreParenImpCasts();
2856 if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) {
2857 DiagnoseImpCast(S, LiteralExpr, T, CC,
2858 diag::warn_impcast_literal_float_to_integer);
2859 } else {
2860 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2861 }
2862 }
John McCall51313c32010-01-04 23:31:57 +00002863
2864 return;
2865 }
2866
John McCallf2370c92010-01-06 05:24:50 +00002867 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002868 return;
2869
John McCall323ed742010-05-06 08:58:33 +00002870 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002871 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002872
2873 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002874 // If the source is a constant, use a default-on diagnostic.
2875 // TODO: this should happen for bitfield stores, too.
2876 llvm::APSInt Value(32);
2877 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002878 if (isFromSystemMacro(S, CC))
2879 return;
2880
John McCall091f23f2010-11-09 22:22:12 +00002881 std::string PrettySourceValue = Value.toString(10);
2882 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2883
2884 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2885 << PrettySourceValue << PrettyTargetValue
2886 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2887 return;
2888 }
2889
John McCall51313c32010-01-04 23:31:57 +00002890 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2891 // and by god we'll let them.
Ted Kremenekef9ff882011-03-10 20:03:42 +00002892
2893 if (isFromSystemMacro(S, CC))
2894 return;
2895
John McCallf2370c92010-01-06 05:24:50 +00002896 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002897 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2898 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002899 }
2900
2901 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2902 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2903 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002904
2905 if (isFromSystemMacro(S, CC))
2906 return;
2907
John McCall323ed742010-05-06 08:58:33 +00002908 unsigned DiagID = diag::warn_impcast_integer_sign;
2909
2910 // Traditionally, gcc has warned about this under -Wsign-compare.
2911 // We also want to warn about it in -Wconversion.
2912 // So if -Wconversion is off, use a completely identical diagnostic
2913 // in the sign-compare group.
2914 // The conditional-checking code will
2915 if (ICContext) {
2916 DiagID = diag::warn_impcast_integer_sign_conditional;
2917 *ICContext = true;
2918 }
2919
John McCallb4eb64d2010-10-08 02:01:28 +00002920 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002921 }
2922
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002923 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002924 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
2925 // type, to give us better diagnostics.
2926 QualType SourceType = E->getType();
2927 if (!S.getLangOptions().CPlusPlus) {
2928 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2929 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2930 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
2931 SourceType = S.Context.getTypeDeclType(Enum);
2932 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
2933 }
2934 }
2935
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002936 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
2937 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
2938 if ((SourceEnum->getDecl()->getIdentifier() ||
2939 SourceEnum->getDecl()->getTypedefForAnonDecl()) &&
2940 (TargetEnum->getDecl()->getIdentifier() ||
2941 TargetEnum->getDecl()->getTypedefForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00002942 SourceEnum != TargetEnum) {
2943 if (isFromSystemMacro(S, CC))
2944 return;
2945
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002946 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002947 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002948 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002949
John McCall51313c32010-01-04 23:31:57 +00002950 return;
2951}
2952
John McCall323ed742010-05-06 08:58:33 +00002953void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2954
2955void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002956 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00002957 E = E->IgnoreParenImpCasts();
2958
2959 if (isa<ConditionalOperator>(E))
2960 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2961
John McCallb4eb64d2010-10-08 02:01:28 +00002962 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002963 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002964 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00002965 return;
2966}
2967
2968void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00002969 SourceLocation CC = E->getQuestionLoc();
2970
2971 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00002972
2973 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00002974 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2975 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002976
2977 // If -Wconversion would have warned about either of the candidates
2978 // for a signedness conversion to the context type...
2979 if (!Suspicious) return;
2980
2981 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002982 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
2983 CC))
John McCall323ed742010-05-06 08:58:33 +00002984 return;
2985
2986 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002987 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00002988 return;
2989
2990 // ...then check whether it would have warned about either of the
2991 // candidates for a signedness conversion to the condition type.
2992 if (E->getType() != T) {
2993 Suspicious = false;
2994 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002995 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002996 if (!Suspicious)
2997 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002998 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002999 if (!Suspicious)
3000 return;
3001 }
3002
3003 // If so, emit a diagnostic under -Wsign-compare.
3004 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3005 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3006 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3007 << lex->getType() << rex->getType()
3008 << lex->getSourceRange() << rex->getSourceRange();
3009}
3010
3011/// AnalyzeImplicitConversions - Find and report any interesting
3012/// implicit conversions in the given expression. There are a couple
3013/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003014void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003015 QualType T = OrigE->getType();
3016 Expr *E = OrigE->IgnoreParenImpCasts();
3017
3018 // For conditional operators, we analyze the arguments as if they
3019 // were being fed directly into the output.
3020 if (isa<ConditionalOperator>(E)) {
3021 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3022 CheckConditionalOperator(S, CO, T);
3023 return;
3024 }
3025
3026 // Go ahead and check any implicit conversions we might have skipped.
3027 // The non-canonical typecheck is just an optimization;
3028 // CheckImplicitConversion will filter out dead implicit conversions.
3029 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003030 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003031
3032 // Now continue drilling into this expression.
3033
3034 // Skip past explicit casts.
3035 if (isa<ExplicitCastExpr>(E)) {
3036 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003037 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003038 }
3039
John McCallbeb22aa2010-11-09 23:24:47 +00003040 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3041 // Do a somewhat different check with comparison operators.
3042 if (BO->isComparisonOp())
3043 return AnalyzeComparison(S, BO);
3044
3045 // And with assignments and compound assignments.
3046 if (BO->isAssignmentOp())
3047 return AnalyzeAssignment(S, BO);
3048 }
John McCall323ed742010-05-06 08:58:33 +00003049
3050 // These break the otherwise-useful invariant below. Fortunately,
3051 // we don't really need to recurse into them, because any internal
3052 // expressions should have been analyzed already when they were
3053 // built into statements.
3054 if (isa<StmtExpr>(E)) return;
3055
3056 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003057 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003058
3059 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003060 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003061 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003062 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003063}
3064
3065} // end anonymous namespace
3066
3067/// Diagnoses "dangerous" implicit conversions within the given
3068/// expression (which is a full expression). Implements -Wconversion
3069/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003070///
3071/// \param CC the "context" location of the implicit conversion, i.e.
3072/// the most location of the syntactic entity requiring the implicit
3073/// conversion
3074void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003075 // Don't diagnose in unevaluated contexts.
3076 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3077 return;
3078
3079 // Don't diagnose for value- or type-dependent expressions.
3080 if (E->isTypeDependent() || E->isValueDependent())
3081 return;
3082
John McCallb4eb64d2010-10-08 02:01:28 +00003083 // This is not the right CC for (e.g.) a variable initialization.
3084 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003085}
3086
John McCall15d7d122010-11-11 03:21:53 +00003087void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3088 FieldDecl *BitField,
3089 Expr *Init) {
3090 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3091}
3092
Mike Stumpf8c49212010-01-21 03:59:47 +00003093/// CheckParmsForFunctionDef - Check that the parameters of the given
3094/// function are appropriate for the definition of a function. This
3095/// takes care of any checks that cannot be performed on the
3096/// declaration itself, e.g., that the types of each of the function
3097/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003098bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3099 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003100 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003101 for (; P != PEnd; ++P) {
3102 ParmVarDecl *Param = *P;
3103
Mike Stumpf8c49212010-01-21 03:59:47 +00003104 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3105 // function declarator that is part of a function definition of
3106 // that function shall not have incomplete type.
3107 //
3108 // This is also C++ [dcl.fct]p6.
3109 if (!Param->isInvalidDecl() &&
3110 RequireCompleteType(Param->getLocation(), Param->getType(),
3111 diag::err_typecheck_decl_incomplete_type)) {
3112 Param->setInvalidDecl();
3113 HasInvalidParm = true;
3114 }
3115
3116 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3117 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003118 if (CheckParameterNames &&
3119 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003120 !Param->isImplicit() &&
3121 !getLangOptions().CPlusPlus)
3122 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003123
3124 // C99 6.7.5.3p12:
3125 // If the function declarator is not part of a definition of that
3126 // function, parameters may have incomplete type and may use the [*]
3127 // notation in their sequences of declarator specifiers to specify
3128 // variable length array types.
3129 QualType PType = Param->getOriginalType();
3130 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3131 if (AT->getSizeModifier() == ArrayType::Star) {
3132 // FIXME: This diagnosic should point the the '[*]' if source-location
3133 // information is added for it.
3134 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3135 }
3136 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003137 }
3138
3139 return HasInvalidParm;
3140}
John McCallb7f4ffe2010-08-12 21:44:57 +00003141
3142/// CheckCastAlign - Implements -Wcast-align, which warns when a
3143/// pointer cast increases the alignment requirements.
3144void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3145 // This is actually a lot of work to potentially be doing on every
3146 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003147 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3148 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003149 == Diagnostic::Ignored)
3150 return;
3151
3152 // Ignore dependent types.
3153 if (T->isDependentType() || Op->getType()->isDependentType())
3154 return;
3155
3156 // Require that the destination be a pointer type.
3157 const PointerType *DestPtr = T->getAs<PointerType>();
3158 if (!DestPtr) return;
3159
3160 // If the destination has alignment 1, we're done.
3161 QualType DestPointee = DestPtr->getPointeeType();
3162 if (DestPointee->isIncompleteType()) return;
3163 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3164 if (DestAlign.isOne()) return;
3165
3166 // Require that the source be a pointer type.
3167 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3168 if (!SrcPtr) return;
3169 QualType SrcPointee = SrcPtr->getPointeeType();
3170
3171 // Whitelist casts from cv void*. We already implicitly
3172 // whitelisted casts to cv void*, since they have alignment 1.
3173 // Also whitelist casts involving incomplete types, which implicitly
3174 // includes 'void'.
3175 if (SrcPointee->isIncompleteType()) return;
3176
3177 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3178 if (SrcAlign >= DestAlign) return;
3179
3180 Diag(TRange.getBegin(), diag::warn_cast_align)
3181 << Op->getType() << T
3182 << static_cast<unsigned>(SrcAlign.getQuantity())
3183 << static_cast<unsigned>(DestAlign.getQuantity())
3184 << TRange << Op->getSourceRange();
3185}
3186
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003187static void CheckArrayAccess_Check(Sema &S,
3188 const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003189 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003190 const ConstantArrayType *ArrayTy =
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003191 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003192 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003193 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003194
Chandler Carruth34064582011-02-17 20:55:08 +00003195 const Expr *IndexExpr = E->getIdx();
3196 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003197 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003198 llvm::APSInt index;
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003199 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003200 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003201
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003202 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003203 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003204 if (!size.isStrictlyPositive())
3205 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003206 if (size.getBitWidth() > index.getBitWidth())
3207 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003208 else if (size.getBitWidth() < index.getBitWidth())
3209 size = size.sext(index.getBitWidth());
3210
Chandler Carruth34064582011-02-17 20:55:08 +00003211 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003212 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003213
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003214 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3215 S.PDiag(diag::warn_array_index_exceeds_bounds)
3216 << index.toString(10, true)
3217 << size.toString(10, true)
3218 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003219 } else {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003220 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3221 S.PDiag(diag::warn_array_index_precedes_bounds)
3222 << index.toString(10, true)
3223 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003224 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003225
3226 const NamedDecl *ND = NULL;
3227 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3228 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3229 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3230 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3231 if (ND)
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003232 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3233 S.PDiag(diag::note_array_index_out_of_bounds)
3234 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003235}
3236
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003237void Sema::CheckArrayAccess(const Expr *expr) {
3238 while (true)
3239 switch (expr->getStmtClass()) {
3240 case Stmt::ParenExprClass:
3241 expr = cast<ParenExpr>(expr)->getSubExpr();
3242 continue;
3243 case Stmt::ArraySubscriptExprClass:
3244 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3245 return;
3246 case Stmt::ConditionalOperatorClass: {
3247 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3248 if (const Expr *lhs = cond->getLHS())
3249 CheckArrayAccess(lhs);
3250 if (const Expr *rhs = cond->getRHS())
3251 CheckArrayAccess(rhs);
3252 return;
3253 }
3254 default:
3255 return;
3256 }
3257}