blob: 10773309a3bfbe9704a6e3dc47be20ce18b12e92 [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) {
Sean Huntcf807c42010-08-18 23:23:40 +0000316 CheckNonNullArguments(*i, TheCall);
Ted Kremenekc82faca2010-09-09 04:33:05 +0000317 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000318
Anders Carlssond406bf02009-08-16 01:56:34 +0000319 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000320}
321
Anders Carlssond406bf02009-08-16 01:56:34 +0000322bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000323 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000324 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000325 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000326 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000328 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
329 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000330 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000332 QualType Ty = V->getType();
333 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000334 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Ted Kremenek826a3452010-07-16 02:11:22 +0000336 const bool b = Format->getType() == "scanf";
337 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000338 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Anders Carlssond406bf02009-08-16 01:56:34 +0000340 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000341 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
342 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000343
344 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000345}
346
Chris Lattner5caa3702009-05-08 06:58:22 +0000347/// SemaBuiltinAtomicOverloaded - We have a call to a function like
348/// __sync_fetch_and_add, which is an overloaded function based on the pointer
349/// type of its first argument. The main ActOnCallExpr routines have already
350/// promoted the types of arguments because all of these calls are prototyped as
351/// void(...).
352///
353/// This function goes through and does final semantic checking for these
354/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000355ExprResult
356Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000357 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000358 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
359 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
360
361 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000362 if (TheCall->getNumArgs() < 1) {
363 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
364 << 0 << 1 << TheCall->getNumArgs()
365 << TheCall->getCallee()->getSourceRange();
366 return ExprError();
367 }
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Chris Lattner5caa3702009-05-08 06:58:22 +0000369 // Inspect the first argument of the atomic builtin. This should always be
370 // a pointer type, whose element is an integral scalar or pointer type.
371 // Because it is a pointer type, we don't have to worry about any implicit
372 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000373 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000374 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruthd2014572010-07-09 18:59:35 +0000375 if (!FirstArg->getType()->isPointerType()) {
376 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
377 << FirstArg->getType() << FirstArg->getSourceRange();
378 return ExprError();
379 }
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Chandler Carruthd2014572010-07-09 18:59:35 +0000381 QualType ValType =
382 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000383 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000384 !ValType->isBlockPointerType()) {
385 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
386 << FirstArg->getType() << FirstArg->getSourceRange();
387 return ExprError();
388 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000389
Chandler Carruth8d13d222010-07-18 20:54:12 +0000390 // The majority of builtins return a value, but a few have special return
391 // types, so allow them to override appropriately below.
392 QualType ResultType = ValType;
393
Chris Lattner5caa3702009-05-08 06:58:22 +0000394 // We need to figure out which concrete builtin this maps onto. For example,
395 // __sync_fetch_and_add with a 2 byte object turns into
396 // __sync_fetch_and_add_2.
397#define BUILTIN_ROW(x) \
398 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
399 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner5caa3702009-05-08 06:58:22 +0000401 static const unsigned BuiltinIndices[][5] = {
402 BUILTIN_ROW(__sync_fetch_and_add),
403 BUILTIN_ROW(__sync_fetch_and_sub),
404 BUILTIN_ROW(__sync_fetch_and_or),
405 BUILTIN_ROW(__sync_fetch_and_and),
406 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner5caa3702009-05-08 06:58:22 +0000408 BUILTIN_ROW(__sync_add_and_fetch),
409 BUILTIN_ROW(__sync_sub_and_fetch),
410 BUILTIN_ROW(__sync_and_and_fetch),
411 BUILTIN_ROW(__sync_or_and_fetch),
412 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner5caa3702009-05-08 06:58:22 +0000414 BUILTIN_ROW(__sync_val_compare_and_swap),
415 BUILTIN_ROW(__sync_bool_compare_and_swap),
416 BUILTIN_ROW(__sync_lock_test_and_set),
417 BUILTIN_ROW(__sync_lock_release)
418 };
Mike Stump1eb44332009-09-09 15:08:12 +0000419#undef BUILTIN_ROW
420
Chris Lattner5caa3702009-05-08 06:58:22 +0000421 // Determine the index of the size.
422 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000423 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000424 case 1: SizeIndex = 0; break;
425 case 2: SizeIndex = 1; break;
426 case 4: SizeIndex = 2; break;
427 case 8: SizeIndex = 3; break;
428 case 16: SizeIndex = 4; break;
429 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000430 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
431 << FirstArg->getType() << FirstArg->getSourceRange();
432 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000433 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner5caa3702009-05-08 06:58:22 +0000435 // Each of these builtins has one pointer argument, followed by some number of
436 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
437 // that we ignore. Find out which row of BuiltinIndices to read from as well
438 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000439 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000440 unsigned BuiltinIndex, NumFixed = 1;
441 switch (BuiltinID) {
442 default: assert(0 && "Unknown overloaded atomic builtin!");
443 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
444 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
445 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
446 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
447 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000449 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
450 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
451 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
452 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
453 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Chris Lattner5caa3702009-05-08 06:58:22 +0000455 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000456 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000457 NumFixed = 2;
458 break;
459 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000460 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000461 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000462 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000463 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000464 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000465 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000466 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000467 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000468 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000469 break;
470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Chris Lattner5caa3702009-05-08 06:58:22 +0000472 // Now that we know how many fixed arguments we expect, first check that we
473 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000474 if (TheCall->getNumArgs() < 1+NumFixed) {
475 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
476 << 0 << 1+NumFixed << TheCall->getNumArgs()
477 << TheCall->getCallee()->getSourceRange();
478 return ExprError();
479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000481 // Get the decl for the concrete builtin from this, we can tell what the
482 // concrete integer type we should convert to is.
483 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
484 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
485 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000486 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000487 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
488 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000489
John McCallf871d0c2010-08-07 06:22:56 +0000490 // The first argument --- the pointer --- has a fixed type; we
491 // deduce the types of the rest of the arguments accordingly. Walk
492 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000493 for (unsigned i = 0; i != NumFixed; ++i) {
494 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Chris Lattner5caa3702009-05-08 06:58:22 +0000496 // If the argument is an implicit cast, then there was a promotion due to
497 // "...", just remove it now.
498 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
499 Arg = ICE->getSubExpr();
500 ICE->setSubExpr(0);
Chris Lattner5caa3702009-05-08 06:58:22 +0000501 TheCall->setArg(i+1, Arg);
502 }
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Chris Lattner5caa3702009-05-08 06:58:22 +0000504 // GCC does an implicit conversion to the pointer or integer ValType. This
505 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000506 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000507 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000508 CXXCastPath BasePath;
John McCallf89e55a2010-11-18 06:31:45 +0000509 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, VK, BasePath))
Chandler Carruthd2014572010-07-09 18:59:35 +0000510 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Chris Lattner5caa3702009-05-08 06:58:22 +0000512 // Okay, we have something that *can* be converted to the right type. Check
513 // to see if there is a potentially weird extension going on here. This can
514 // happen when you do an atomic operation on something like an char* and
515 // pass in 42. The 42 gets converted to char. This is even more strange
516 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000517 // FIXME: Do this check.
John McCallf89e55a2010-11-18 06:31:45 +0000518 ImpCastExprToType(Arg, ValType, Kind, VK, &BasePath);
Chris Lattner5caa3702009-05-08 06:58:22 +0000519 TheCall->setArg(i+1, Arg);
520 }
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Chris Lattner5caa3702009-05-08 06:58:22 +0000522 // Switch the DeclRefExpr to refer to the new decl.
523 DRE->setDecl(NewBuiltinDecl);
524 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Chris Lattner5caa3702009-05-08 06:58:22 +0000526 // Set the callee in the CallExpr.
527 // FIXME: This leaks the original parens and implicit casts.
528 Expr *PromotedCall = DRE;
529 UsualUnaryConversions(PromotedCall);
530 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000532 // Change the result type of the call to match the original value type. This
533 // is arbitrary, but the codegen for these builtins ins design to handle it
534 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000535 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000536
537 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000538}
539
540
Chris Lattner69039812009-02-18 06:01:06 +0000541/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000542/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000543/// Note: It might also make sense to do the UTF-16 conversion here (would
544/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000545bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000546 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000547 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
548
549 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000550 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
551 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000552 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000555 size_t NulPos = Literal->getString().find('\0');
556 if (NulPos != llvm::StringRef::npos) {
557 Diag(getLocationOfStringLiteralByte(Literal, NulPos),
558 diag::warn_cfstring_literal_contains_nul_character)
559 << Arg->getSourceRange();
Daniel Dunbarf015b032009-09-22 10:03:52 +0000560 }
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000561 if (Literal->containsNonAsciiOrNull()) {
562 llvm::StringRef String = Literal->getString();
563 unsigned NumBytes = String.size();
564 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
565 const UTF8 *FromPtr = (UTF8 *)String.data();
566 UTF16 *ToPtr = &ToBuf[0];
567
568 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
569 &ToPtr, ToPtr + NumBytes,
570 strictConversion);
571 // Check for conversion failure.
572 if (Result != conversionOK)
573 Diag(Arg->getLocStart(),
574 diag::warn_cfstring_truncated) << Arg->getSourceRange();
575 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000576 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000577}
578
Chris Lattnerc27c6652007-12-20 00:05:45 +0000579/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
580/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000581bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
582 Expr *Fn = TheCall->getCallee();
583 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000584 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000585 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000586 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
587 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000588 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000589 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000590 return true;
591 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000592
593 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000594 return Diag(TheCall->getLocEnd(),
595 diag::err_typecheck_call_too_few_args_at_least)
596 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000597 }
598
Chris Lattnerc27c6652007-12-20 00:05:45 +0000599 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000600 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000601 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000602 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000603 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000604 else if (FunctionDecl *FD = getCurFunctionDecl())
605 isVariadic = FD->isVariadic();
606 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000607 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattnerc27c6652007-12-20 00:05:45 +0000609 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000610 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
611 return true;
612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Chris Lattner30ce3442007-12-19 23:59:04 +0000614 // Verify that the second argument to the builtin is the last argument of the
615 // current function or method.
616 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000617 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Anders Carlsson88cf2262008-02-11 04:20:54 +0000619 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
620 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000621 // FIXME: This isn't correct for methods (results in bogus warning).
622 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000623 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000624 if (CurBlock)
625 LastArg = *(CurBlock->TheDecl->param_end()-1);
626 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000627 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000628 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000629 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000630 SecondArgIsLastNamedArgument = PV == LastArg;
631 }
632 }
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattner30ce3442007-12-19 23:59:04 +0000634 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000635 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000636 diag::warn_second_parameter_of_va_start_not_last_named_argument);
637 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000638}
Chris Lattner30ce3442007-12-19 23:59:04 +0000639
Chris Lattner1b9a0792007-12-20 00:26:33 +0000640/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
641/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000642bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
643 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000644 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000645 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000646 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000647 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000648 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000649 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000650 << SourceRange(TheCall->getArg(2)->getLocStart(),
651 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Chris Lattner925e60d2007-12-28 05:29:59 +0000653 Expr *OrigArg0 = TheCall->getArg(0);
654 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000655
Chris Lattner1b9a0792007-12-20 00:26:33 +0000656 // Do standard promotions between the two arguments, returning their common
657 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000658 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000659
660 // Make sure any conversions are pushed back into the call; this is
661 // type safe since unordered compare builtins are declared as "_Bool
662 // foo(...)".
663 TheCall->setArg(0, OrigArg0);
664 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Douglas Gregorcde01732009-05-19 22:10:17 +0000666 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
667 return false;
668
Chris Lattner1b9a0792007-12-20 00:26:33 +0000669 // If the common type isn't a real floating type, then the arguments were
670 // invalid for this operation.
671 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000672 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000673 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000674 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000675 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Chris Lattner1b9a0792007-12-20 00:26:33 +0000677 return false;
678}
679
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000680/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
681/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000682/// to check everything. We expect the last argument to be a floating point
683/// value.
684bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
685 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000686 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000687 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000688 if (TheCall->getNumArgs() > NumArgs)
689 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000690 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000691 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000692 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000693 (*(TheCall->arg_end()-1))->getLocEnd());
694
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000695 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Eli Friedman9ac6f622009-08-31 20:06:00 +0000697 if (OrigArg->isTypeDependent())
698 return false;
699
Chris Lattner81368fb2010-05-06 05:50:07 +0000700 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000701 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000702 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000703 diag::err_typecheck_call_invalid_unary_fp)
704 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Chris Lattner81368fb2010-05-06 05:50:07 +0000706 // If this is an implicit conversion from float -> double, remove it.
707 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
708 Expr *CastArg = Cast->getSubExpr();
709 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
710 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
711 "promotion from float to double is the only expected cast here");
712 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000713 TheCall->setArg(NumArgs-1, CastArg);
714 OrigArg = CastArg;
715 }
716 }
717
Eli Friedman9ac6f622009-08-31 20:06:00 +0000718 return false;
719}
720
Eli Friedmand38617c2008-05-14 19:38:39 +0000721/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
722// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000723ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000724 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000725 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000726 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000727 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000728 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000729
Nate Begeman37b6a572010-06-08 00:16:34 +0000730 // Determine which of the following types of shufflevector we're checking:
731 // 1) unary, vector mask: (lhs, mask)
732 // 2) binary, vector mask: (lhs, rhs, mask)
733 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
734 QualType resType = TheCall->getArg(0)->getType();
735 unsigned numElements = 0;
736
Douglas Gregorcde01732009-05-19 22:10:17 +0000737 if (!TheCall->getArg(0)->isTypeDependent() &&
738 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000739 QualType LHSType = TheCall->getArg(0)->getType();
740 QualType RHSType = TheCall->getArg(1)->getType();
741
742 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000743 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000744 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000745 TheCall->getArg(1)->getLocEnd());
746 return ExprError();
747 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000748
749 numElements = LHSType->getAs<VectorType>()->getNumElements();
750 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Nate Begeman37b6a572010-06-08 00:16:34 +0000752 // Check to see if we have a call with 2 vector arguments, the unary shuffle
753 // with mask. If so, verify that RHS is an integer vector type with the
754 // same number of elts as lhs.
755 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000756 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000757 RHSType->getAs<VectorType>()->getNumElements() != numElements)
758 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
759 << SourceRange(TheCall->getArg(1)->getLocStart(),
760 TheCall->getArg(1)->getLocEnd());
761 numResElements = numElements;
762 }
763 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000764 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000765 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000766 TheCall->getArg(1)->getLocEnd());
767 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000768 } else if (numElements != numResElements) {
769 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000770 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000771 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000772 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000773 }
774
775 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000776 if (TheCall->getArg(i)->isTypeDependent() ||
777 TheCall->getArg(i)->isValueDependent())
778 continue;
779
Nate Begeman37b6a572010-06-08 00:16:34 +0000780 llvm::APSInt Result(32);
781 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
782 return ExprError(Diag(TheCall->getLocStart(),
783 diag::err_shufflevector_nonconstant_argument)
784 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000785
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000786 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000787 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000788 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000789 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000790 }
791
792 llvm::SmallVector<Expr*, 32> exprs;
793
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000794 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000795 exprs.push_back(TheCall->getArg(i));
796 TheCall->setArg(i, 0);
797 }
798
Nate Begemana88dc302009-08-12 02:10:25 +0000799 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000800 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000801 TheCall->getCallee()->getLocStart(),
802 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000803}
Chris Lattner30ce3442007-12-19 23:59:04 +0000804
Daniel Dunbar4493f792008-07-21 22:59:13 +0000805/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
806// This is declared to take (const void*, ...) and can take two
807// optional constant int args.
808bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000809 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000810
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000811 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000812 return Diag(TheCall->getLocEnd(),
813 diag::err_typecheck_call_too_many_args_at_most)
814 << 0 /*function call*/ << 3 << NumArgs
815 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000816
817 // Argument 0 is checked for us and the remaining arguments must be
818 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000819 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000820 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000821
Eli Friedman9aef7262009-12-04 00:30:06 +0000822 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000823 if (SemaBuiltinConstantArg(TheCall, i, Result))
824 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Daniel Dunbar4493f792008-07-21 22:59:13 +0000826 // FIXME: gcc issues a warning and rewrites these to 0. These
827 // seems especially odd for the third argument since the default
828 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000829 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000830 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000831 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000832 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000833 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000834 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000835 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000836 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000837 }
838 }
839
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000840 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000841}
842
Eric Christopher691ebc32010-04-17 02:26:23 +0000843/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
844/// TheCall is a constant expression.
845bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
846 llvm::APSInt &Result) {
847 Expr *Arg = TheCall->getArg(ArgNum);
848 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
849 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
850
851 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
852
853 if (!Arg->isIntegerConstantExpr(Result, Context))
854 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000855 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000856
Chris Lattner21fb98e2009-09-23 06:06:36 +0000857 return false;
858}
859
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000860/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
861/// int type). This simply type checks that type is one of the defined
862/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000863// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000864bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000865 llvm::APSInt Result;
866
867 // Check constant-ness first.
868 if (SemaBuiltinConstantArg(TheCall, 1, Result))
869 return true;
870
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000871 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000872 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000873 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
874 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000875 }
876
877 return false;
878}
879
Eli Friedman586d6a82009-05-03 06:04:26 +0000880/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000881/// This checks that val is a constant 1.
882bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
883 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000884 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000885
Eric Christopher691ebc32010-04-17 02:26:23 +0000886 // TODO: This is less than ideal. Overload this to take a value.
887 if (SemaBuiltinConstantArg(TheCall, 1, Result))
888 return true;
889
890 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000891 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
892 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
893
894 return false;
895}
896
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000897// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000898bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
899 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000900 unsigned format_idx, unsigned firstDataArg,
901 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000902 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000903 if (E->isTypeDependent() || E->isValueDependent())
904 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000905
906 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000907 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000908 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000909 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000910 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
911 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000912 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000913 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000914 }
915
Ted Kremenek95355bb2010-09-09 03:51:42 +0000916 case Stmt::IntegerLiteralClass:
917 // Technically -Wformat-nonliteral does not warn about this case.
918 // The behavior of printf and friends in this case is implementation
919 // dependent. Ideally if the format string cannot be null then
920 // it should have a 'nonnull' attribute in the function prototype.
921 return true;
922
Ted Kremenekd30ef872009-01-12 23:09:09 +0000923 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000924 E = cast<ImplicitCastExpr>(E)->getSubExpr();
925 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000926 }
927
928 case Stmt::ParenExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000929 E = cast<ParenExpr>(E)->getSubExpr();
930 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000931 }
Mike Stump1eb44332009-09-09 15:08:12 +0000932
John McCall56ca35d2011-02-17 10:25:35 +0000933 case Stmt::OpaqueValueExprClass:
934 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
935 E = src;
936 goto tryAgain;
937 }
938 return false;
939
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000940 case Stmt::PredefinedExprClass:
941 // While __func__, etc., are technically not string literals, they
942 // cannot contain format specifiers and thus are not a security
943 // liability.
944 return true;
945
Ted Kremenek082d9362009-03-20 21:35:28 +0000946 case Stmt::DeclRefExprClass: {
947 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Ted Kremenek082d9362009-03-20 21:35:28 +0000949 // As an exception, do not flag errors for variables binding to
950 // const string literals.
951 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
952 bool isConstant = false;
953 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000954
Ted Kremenek082d9362009-03-20 21:35:28 +0000955 if (const ArrayType *AT = Context.getAsArrayType(T)) {
956 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000957 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000958 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000959 PT->getPointeeType().isConstant(Context);
960 }
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Ted Kremenek082d9362009-03-20 21:35:28 +0000962 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000963 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000964 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000965 HasVAListArg, format_idx, firstDataArg,
966 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000967 }
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Anders Carlssond966a552009-06-28 19:55:58 +0000969 // For vprintf* functions (i.e., HasVAListArg==true), we add a
970 // special check to see if the format string is a function parameter
971 // of the function calling the printf function. If the function
972 // has an attribute indicating it is a printf-like function, then we
973 // should suppress warnings concerning non-literals being used in a call
974 // to a vprintf function. For example:
975 //
976 // void
977 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
978 // va_list ap;
979 // va_start(ap, fmt);
980 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
981 // ...
982 //
983 //
984 // FIXME: We don't have full attribute support yet, so just check to see
985 // if the argument is a DeclRefExpr that references a parameter. We'll
986 // add proper support for checking the attribute later.
987 if (HasVAListArg)
988 if (isa<ParmVarDecl>(VD))
989 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000990 }
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Ted Kremenek082d9362009-03-20 21:35:28 +0000992 return false;
993 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000994
Anders Carlsson8f031b32009-06-27 04:05:33 +0000995 case Stmt::CallExprClass: {
996 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000997 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000998 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
999 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1000 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001001 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001002 unsigned ArgIndex = FA->getFormatIdx();
1003 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001004
1005 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001006 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001007 }
1008 }
1009 }
1010 }
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Anders Carlsson8f031b32009-06-27 04:05:33 +00001012 return false;
1013 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001014 case Stmt::ObjCStringLiteralClass:
1015 case Stmt::StringLiteralClass: {
1016 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Ted Kremenek082d9362009-03-20 21:35:28 +00001018 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001019 StrE = ObjCFExpr->getString();
1020 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001021 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Ted Kremenekd30ef872009-01-12 23:09:09 +00001023 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001024 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1025 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001026 return true;
1027 }
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Ted Kremenekd30ef872009-01-12 23:09:09 +00001029 return false;
1030 }
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Ted Kremenek082d9362009-03-20 21:35:28 +00001032 default:
1033 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001034 }
1035}
1036
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001037void
Mike Stump1eb44332009-09-09 15:08:12 +00001038Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1039 const CallExpr *TheCall) {
Sean Huntcf807c42010-08-18 23:23:40 +00001040 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1041 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001042 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +00001043 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001044 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001045 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +00001046 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1047 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001048 }
1049}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001050
Ted Kremenek826a3452010-07-16 02:11:22 +00001051/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1052/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001053void
Ted Kremenek826a3452010-07-16 02:11:22 +00001054Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1055 unsigned format_idx, unsigned firstDataArg,
1056 bool isPrintf) {
1057
Ted Kremenek082d9362009-03-20 21:35:28 +00001058 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001059
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001060 // The way the format attribute works in GCC, the implicit this argument
1061 // of member functions is counted. However, it doesn't appear in our own
1062 // lists, so decrement format_idx in that case.
1063 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001064 const CXXMethodDecl *method_decl =
1065 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1066 if (method_decl && method_decl->isInstance()) {
1067 // Catch a format attribute mistakenly referring to the object argument.
1068 if (format_idx == 0)
1069 return;
1070 --format_idx;
1071 if(firstDataArg != 0)
1072 --firstDataArg;
1073 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001074 }
1075
Ted Kremenek826a3452010-07-16 02:11:22 +00001076 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001077 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001078 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001079 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001080 return;
1081 }
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Ted Kremenek082d9362009-03-20 21:35:28 +00001083 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Chris Lattner59907c42007-08-10 20:18:51 +00001085 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001086 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001087 // Dynamically generated format strings are difficult to
1088 // automatically vet at compile time. Requiring that format strings
1089 // are string literals: (1) permits the checking of format strings by
1090 // the compiler and thereby (2) can practically remove the source of
1091 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001092
Mike Stump1eb44332009-09-09 15:08:12 +00001093 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001094 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001095 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001096 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001097 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001098 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001099 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001100
Chris Lattner655f1412009-04-29 04:59:47 +00001101 // If there are no arguments specified, warn with -Wformat-security, otherwise
1102 // warn only with -Wformat-nonliteral.
1103 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001104 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001105 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001106 << OrigFormatExpr->getSourceRange();
1107 else
Mike Stump1eb44332009-09-09 15:08:12 +00001108 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001109 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001110 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001111}
Ted Kremenek71895b92007-08-14 17:39:48 +00001112
Ted Kremeneke0e53132010-01-28 23:39:18 +00001113namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001114class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1115protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001116 Sema &S;
1117 const StringLiteral *FExpr;
1118 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001119 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001120 const unsigned NumDataArgs;
1121 const bool IsObjCLiteral;
1122 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001123 const bool HasVAListArg;
1124 const CallExpr *TheCall;
1125 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001126 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001127 bool usesPositionalArgs;
1128 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001129public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001130 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001131 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001132 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001133 const char *beg, bool hasVAListArg,
1134 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001135 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001136 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001137 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001138 IsObjCLiteral(isObjCLiteral), Beg(beg),
1139 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001140 TheCall(theCall), FormatIdx(formatIdx),
1141 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001142 CoveredArgs.resize(numDataArgs);
1143 CoveredArgs.reset();
1144 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001145
Ted Kremenek07d161f2010-01-29 01:50:07 +00001146 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001147
Ted Kremenek826a3452010-07-16 02:11:22 +00001148 void HandleIncompleteSpecifier(const char *startSpecifier,
1149 unsigned specifierLen);
1150
Ted Kremenekefaff192010-02-27 01:41:03 +00001151 virtual void HandleInvalidPosition(const char *startSpecifier,
1152 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001153 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001154
1155 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1156
Ted Kremeneke0e53132010-01-28 23:39:18 +00001157 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001158
Ted Kremenek826a3452010-07-16 02:11:22 +00001159protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001160 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1161 const char *startSpec,
1162 unsigned specifierLen,
1163 const char *csStart, unsigned csLen);
1164
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001165 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001166 CharSourceRange getSpecifierRange(const char *startSpecifier,
1167 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001168 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001169
Ted Kremenek0d277352010-01-29 01:06:55 +00001170 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001171
1172 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1173 const analyze_format_string::ConversionSpecifier &CS,
1174 const char *startSpecifier, unsigned specifierLen,
1175 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001176};
1177}
1178
Ted Kremenek826a3452010-07-16 02:11:22 +00001179SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001180 return OrigFormatExpr->getSourceRange();
1181}
1182
Ted Kremenek826a3452010-07-16 02:11:22 +00001183CharSourceRange CheckFormatHandler::
1184getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001185 SourceLocation Start = getLocationOfByte(startSpecifier);
1186 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1187
1188 // Advance the end SourceLocation by one due to half-open ranges.
1189 End = End.getFileLocWithOffset(1);
1190
1191 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001192}
1193
Ted Kremenek826a3452010-07-16 02:11:22 +00001194SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001195 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001196}
1197
Ted Kremenek826a3452010-07-16 02:11:22 +00001198void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1199 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001200 SourceLocation Loc = getLocationOfByte(startSpecifier);
1201 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001202 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001203}
1204
Ted Kremenekefaff192010-02-27 01:41:03 +00001205void
Ted Kremenek826a3452010-07-16 02:11:22 +00001206CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1207 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001208 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001209 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1210 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001211}
1212
Ted Kremenek826a3452010-07-16 02:11:22 +00001213void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001214 unsigned posLen) {
1215 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001216 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1217 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001218}
1219
Ted Kremenek826a3452010-07-16 02:11:22 +00001220void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1221 // The presence of a null character is likely an error.
1222 S.Diag(getLocationOfByte(nullCharacter),
1223 diag::warn_printf_format_string_contains_null_char)
1224 << getFormatStringRange();
1225}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001226
Ted Kremenek826a3452010-07-16 02:11:22 +00001227const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1228 return TheCall->getArg(FirstDataArg + i);
1229}
1230
1231void CheckFormatHandler::DoneProcessing() {
1232 // Does the number of data arguments exceed the number of
1233 // format conversions in the format string?
1234 if (!HasVAListArg) {
1235 // Find any arguments that weren't covered.
1236 CoveredArgs.flip();
1237 signed notCoveredArg = CoveredArgs.find_first();
1238 if (notCoveredArg >= 0) {
1239 assert((unsigned)notCoveredArg < NumDataArgs);
1240 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1241 diag::warn_printf_data_arg_not_used)
1242 << getFormatStringRange();
1243 }
1244 }
1245}
1246
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001247bool
1248CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1249 SourceLocation Loc,
1250 const char *startSpec,
1251 unsigned specifierLen,
1252 const char *csStart,
1253 unsigned csLen) {
1254
1255 bool keepGoing = true;
1256 if (argIndex < NumDataArgs) {
1257 // Consider the argument coverered, even though the specifier doesn't
1258 // make sense.
1259 CoveredArgs.set(argIndex);
1260 }
1261 else {
1262 // If argIndex exceeds the number of data arguments we
1263 // don't issue a warning because that is just a cascade of warnings (and
1264 // they may have intended '%%' anyway). We don't want to continue processing
1265 // the format string after this point, however, as we will like just get
1266 // gibberish when trying to match arguments.
1267 keepGoing = false;
1268 }
1269
1270 S.Diag(Loc, diag::warn_format_invalid_conversion)
1271 << llvm::StringRef(csStart, csLen)
1272 << getSpecifierRange(startSpec, specifierLen);
1273
1274 return keepGoing;
1275}
1276
Ted Kremenek666a1972010-07-26 19:45:42 +00001277bool
1278CheckFormatHandler::CheckNumArgs(
1279 const analyze_format_string::FormatSpecifier &FS,
1280 const analyze_format_string::ConversionSpecifier &CS,
1281 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1282
1283 if (argIndex >= NumDataArgs) {
1284 if (FS.usesPositionalArg()) {
1285 S.Diag(getLocationOfByte(CS.getStart()),
1286 diag::warn_printf_positional_arg_exceeds_data_args)
1287 << (argIndex+1) << NumDataArgs
1288 << getSpecifierRange(startSpecifier, specifierLen);
1289 }
1290 else {
1291 S.Diag(getLocationOfByte(CS.getStart()),
1292 diag::warn_printf_insufficient_data_args)
1293 << getSpecifierRange(startSpecifier, specifierLen);
1294 }
1295
1296 return false;
1297 }
1298 return true;
1299}
1300
Ted Kremenek826a3452010-07-16 02:11:22 +00001301//===--- CHECK: Printf format string checking ------------------------------===//
1302
1303namespace {
1304class CheckPrintfHandler : public CheckFormatHandler {
1305public:
1306 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1307 const Expr *origFormatExpr, unsigned firstDataArg,
1308 unsigned numDataArgs, bool isObjCLiteral,
1309 const char *beg, bool hasVAListArg,
1310 const CallExpr *theCall, unsigned formatIdx)
1311 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1312 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1313 theCall, formatIdx) {}
1314
1315
1316 bool HandleInvalidPrintfConversionSpecifier(
1317 const analyze_printf::PrintfSpecifier &FS,
1318 const char *startSpecifier,
1319 unsigned specifierLen);
1320
1321 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1322 const char *startSpecifier,
1323 unsigned specifierLen);
1324
1325 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1326 const char *startSpecifier, unsigned specifierLen);
1327 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1328 const analyze_printf::OptionalAmount &Amt,
1329 unsigned type,
1330 const char *startSpecifier, unsigned specifierLen);
1331 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1332 const analyze_printf::OptionalFlag &flag,
1333 const char *startSpecifier, unsigned specifierLen);
1334 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1335 const analyze_printf::OptionalFlag &ignoredFlag,
1336 const analyze_printf::OptionalFlag &flag,
1337 const char *startSpecifier, unsigned specifierLen);
1338};
1339}
1340
1341bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1342 const analyze_printf::PrintfSpecifier &FS,
1343 const char *startSpecifier,
1344 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001345 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001346 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001347
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001348 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1349 getLocationOfByte(CS.getStart()),
1350 startSpecifier, specifierLen,
1351 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001352}
1353
Ted Kremenek826a3452010-07-16 02:11:22 +00001354bool CheckPrintfHandler::HandleAmount(
1355 const analyze_format_string::OptionalAmount &Amt,
1356 unsigned k, const char *startSpecifier,
1357 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001358
1359 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001360 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001361 unsigned argIndex = Amt.getArgIndex();
1362 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001363 S.Diag(getLocationOfByte(Amt.getStart()),
1364 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001365 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001366 // Don't do any more checking. We will just emit
1367 // spurious errors.
1368 return false;
1369 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001370
Ted Kremenek0d277352010-01-29 01:06:55 +00001371 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001372 // Although not in conformance with C99, we also allow the argument to be
1373 // an 'unsigned int' as that is a reasonably safe case. GCC also
1374 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001375 CoveredArgs.set(argIndex);
1376 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001377 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001378
1379 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1380 assert(ATR.isValid());
1381
1382 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001383 S.Diag(getLocationOfByte(Amt.getStart()),
1384 diag::warn_printf_asterisk_wrong_type)
1385 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001386 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001387 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001388 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001389 // Don't do any more checking. We will just emit
1390 // spurious errors.
1391 return false;
1392 }
1393 }
1394 }
1395 return true;
1396}
Ted Kremenek0d277352010-01-29 01:06:55 +00001397
Tom Caree4ee9662010-06-17 19:00:27 +00001398void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001399 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001400 const analyze_printf::OptionalAmount &Amt,
1401 unsigned type,
1402 const char *startSpecifier,
1403 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001404 const analyze_printf::PrintfConversionSpecifier &CS =
1405 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001406 switch (Amt.getHowSpecified()) {
1407 case analyze_printf::OptionalAmount::Constant:
1408 S.Diag(getLocationOfByte(Amt.getStart()),
1409 diag::warn_printf_nonsensical_optional_amount)
1410 << type
1411 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001412 << getSpecifierRange(startSpecifier, specifierLen)
1413 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001414 Amt.getConstantLength()));
1415 break;
1416
1417 default:
1418 S.Diag(getLocationOfByte(Amt.getStart()),
1419 diag::warn_printf_nonsensical_optional_amount)
1420 << type
1421 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001422 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001423 break;
1424 }
1425}
1426
Ted Kremenek826a3452010-07-16 02:11:22 +00001427void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001428 const analyze_printf::OptionalFlag &flag,
1429 const char *startSpecifier,
1430 unsigned specifierLen) {
1431 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001432 const analyze_printf::PrintfConversionSpecifier &CS =
1433 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001434 S.Diag(getLocationOfByte(flag.getPosition()),
1435 diag::warn_printf_nonsensical_flag)
1436 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001437 << getSpecifierRange(startSpecifier, specifierLen)
1438 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001439}
1440
1441void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001442 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001443 const analyze_printf::OptionalFlag &ignoredFlag,
1444 const analyze_printf::OptionalFlag &flag,
1445 const char *startSpecifier,
1446 unsigned specifierLen) {
1447 // Warn about ignored flag with a fixit removal.
1448 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1449 diag::warn_printf_ignored_flag)
1450 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001451 << getSpecifierRange(startSpecifier, specifierLen)
1452 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001453 ignoredFlag.getPosition(), 1));
1454}
1455
Ted Kremeneke0e53132010-01-28 23:39:18 +00001456bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001457CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001458 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001459 const char *startSpecifier,
1460 unsigned specifierLen) {
1461
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001462 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001463 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001464 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001465
Ted Kremenekbaa40062010-07-19 22:01:06 +00001466 if (FS.consumesDataArgument()) {
1467 if (atFirstArg) {
1468 atFirstArg = false;
1469 usesPositionalArgs = FS.usesPositionalArg();
1470 }
1471 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1472 // Cannot mix-and-match positional and non-positional arguments.
1473 S.Diag(getLocationOfByte(CS.getStart()),
1474 diag::warn_format_mix_positional_nonpositional_args)
1475 << getSpecifierRange(startSpecifier, specifierLen);
1476 return false;
1477 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001478 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001479
Ted Kremenekefaff192010-02-27 01:41:03 +00001480 // First check if the field width, precision, and conversion specifier
1481 // have matching data arguments.
1482 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1483 startSpecifier, specifierLen)) {
1484 return false;
1485 }
1486
1487 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1488 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001489 return false;
1490 }
1491
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001492 if (!CS.consumesDataArgument()) {
1493 // FIXME: Technically specifying a precision or field width here
1494 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001495 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001496 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001497
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001498 // Consume the argument.
1499 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001500 if (argIndex < NumDataArgs) {
1501 // The check to see if the argIndex is valid will come later.
1502 // We set the bit here because we may exit early from this
1503 // function if we encounter some other error.
1504 CoveredArgs.set(argIndex);
1505 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001506
1507 // Check for using an Objective-C specific conversion specifier
1508 // in a non-ObjC literal.
1509 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001510 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1511 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001512 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001513
Tom Caree4ee9662010-06-17 19:00:27 +00001514 // Check for invalid use of field width
1515 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001516 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001517 startSpecifier, specifierLen);
1518 }
1519
1520 // Check for invalid use of precision
1521 if (!FS.hasValidPrecision()) {
1522 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1523 startSpecifier, specifierLen);
1524 }
1525
1526 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001527 if (!FS.hasValidThousandsGroupingPrefix())
1528 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001529 if (!FS.hasValidLeadingZeros())
1530 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1531 if (!FS.hasValidPlusPrefix())
1532 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001533 if (!FS.hasValidSpacePrefix())
1534 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001535 if (!FS.hasValidAlternativeForm())
1536 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1537 if (!FS.hasValidLeftJustified())
1538 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1539
1540 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001541 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1542 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1543 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001544 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1545 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1546 startSpecifier, specifierLen);
1547
1548 // Check the length modifier is valid with the given conversion specifier.
1549 const LengthModifier &LM = FS.getLengthModifier();
1550 if (!FS.hasValidLengthModifier())
1551 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001552 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001553 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001554 << getSpecifierRange(startSpecifier, specifierLen)
1555 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001556 LM.getLength()));
1557
1558 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001559 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001560 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001561 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001562 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001563 // Continue checking the other format specifiers.
1564 return true;
1565 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001566
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001567 // The remaining checks depend on the data arguments.
1568 if (HasVAListArg)
1569 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001570
Ted Kremenek666a1972010-07-26 19:45:42 +00001571 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001572 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001573
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001574 // Now type check the data expression that matches the
1575 // format specifier.
1576 const Expr *Ex = getDataArg(argIndex);
1577 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1578 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1579 // Check if we didn't match because of an implicit cast from a 'char'
1580 // or 'short' to an 'int'. This is done because printf is a varargs
1581 // function.
1582 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001583 if (ICE->getType() == S.Context.IntTy) {
1584 // All further checking is done on the subexpression.
1585 Ex = ICE->getSubExpr();
1586 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001587 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001588 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001589
1590 // We may be able to offer a FixItHint if it is a supported type.
1591 PrintfSpecifier fixedFS = FS;
1592 bool success = fixedFS.fixType(Ex->getType());
1593
1594 if (success) {
1595 // Get the fix string from the fixed format specifier
1596 llvm::SmallString<128> buf;
1597 llvm::raw_svector_ostream os(buf);
1598 fixedFS.toString(os);
1599
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001600 // FIXME: getRepresentativeType() perhaps should return a string
1601 // instead of a QualType to better handle when the representative
1602 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001603 S.Diag(getLocationOfByte(CS.getStart()),
1604 diag::warn_printf_conversion_argument_type_mismatch)
1605 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1606 << getSpecifierRange(startSpecifier, specifierLen)
1607 << Ex->getSourceRange()
1608 << FixItHint::CreateReplacement(
1609 getSpecifierRange(startSpecifier, specifierLen),
1610 os.str());
1611 }
1612 else {
1613 S.Diag(getLocationOfByte(CS.getStart()),
1614 diag::warn_printf_conversion_argument_type_mismatch)
1615 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1616 << getSpecifierRange(startSpecifier, specifierLen)
1617 << Ex->getSourceRange();
1618 }
1619 }
1620
Ted Kremeneke0e53132010-01-28 23:39:18 +00001621 return true;
1622}
1623
Ted Kremenek826a3452010-07-16 02:11:22 +00001624//===--- CHECK: Scanf format string checking ------------------------------===//
1625
1626namespace {
1627class CheckScanfHandler : public CheckFormatHandler {
1628public:
1629 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1630 const Expr *origFormatExpr, unsigned firstDataArg,
1631 unsigned numDataArgs, bool isObjCLiteral,
1632 const char *beg, bool hasVAListArg,
1633 const CallExpr *theCall, unsigned formatIdx)
1634 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1635 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1636 theCall, formatIdx) {}
1637
1638 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1639 const char *startSpecifier,
1640 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001641
1642 bool HandleInvalidScanfConversionSpecifier(
1643 const analyze_scanf::ScanfSpecifier &FS,
1644 const char *startSpecifier,
1645 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001646
1647 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001648};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001649}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001650
Ted Kremenekb7c21012010-07-16 18:28:03 +00001651void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1652 const char *end) {
1653 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1654 << getSpecifierRange(start, end - start);
1655}
1656
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001657bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1658 const analyze_scanf::ScanfSpecifier &FS,
1659 const char *startSpecifier,
1660 unsigned specifierLen) {
1661
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001662 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001663 FS.getConversionSpecifier();
1664
1665 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1666 getLocationOfByte(CS.getStart()),
1667 startSpecifier, specifierLen,
1668 CS.getStart(), CS.getLength());
1669}
1670
Ted Kremenek826a3452010-07-16 02:11:22 +00001671bool CheckScanfHandler::HandleScanfSpecifier(
1672 const analyze_scanf::ScanfSpecifier &FS,
1673 const char *startSpecifier,
1674 unsigned specifierLen) {
1675
1676 using namespace analyze_scanf;
1677 using namespace analyze_format_string;
1678
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001679 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001680
Ted Kremenekbaa40062010-07-19 22:01:06 +00001681 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1682 // be used to decide if we are using positional arguments consistently.
1683 if (FS.consumesDataArgument()) {
1684 if (atFirstArg) {
1685 atFirstArg = false;
1686 usesPositionalArgs = FS.usesPositionalArg();
1687 }
1688 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1689 // Cannot mix-and-match positional and non-positional arguments.
1690 S.Diag(getLocationOfByte(CS.getStart()),
1691 diag::warn_format_mix_positional_nonpositional_args)
1692 << getSpecifierRange(startSpecifier, specifierLen);
1693 return false;
1694 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001695 }
1696
1697 // Check if the field with is non-zero.
1698 const OptionalAmount &Amt = FS.getFieldWidth();
1699 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1700 if (Amt.getConstantAmount() == 0) {
1701 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1702 Amt.getConstantLength());
1703 S.Diag(getLocationOfByte(Amt.getStart()),
1704 diag::warn_scanf_nonzero_width)
1705 << R << FixItHint::CreateRemoval(R);
1706 }
1707 }
1708
1709 if (!FS.consumesDataArgument()) {
1710 // FIXME: Technically specifying a precision or field width here
1711 // makes no sense. Worth issuing a warning at some point.
1712 return true;
1713 }
1714
1715 // Consume the argument.
1716 unsigned argIndex = FS.getArgIndex();
1717 if (argIndex < NumDataArgs) {
1718 // The check to see if the argIndex is valid will come later.
1719 // We set the bit here because we may exit early from this
1720 // function if we encounter some other error.
1721 CoveredArgs.set(argIndex);
1722 }
1723
Ted Kremenek1e51c202010-07-20 20:04:47 +00001724 // Check the length modifier is valid with the given conversion specifier.
1725 const LengthModifier &LM = FS.getLengthModifier();
1726 if (!FS.hasValidLengthModifier()) {
1727 S.Diag(getLocationOfByte(LM.getStart()),
1728 diag::warn_format_nonsensical_length)
1729 << LM.toString() << CS.toString()
1730 << getSpecifierRange(startSpecifier, specifierLen)
1731 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1732 LM.getLength()));
1733 }
1734
Ted Kremenek826a3452010-07-16 02:11:22 +00001735 // The remaining checks depend on the data arguments.
1736 if (HasVAListArg)
1737 return true;
1738
Ted Kremenek666a1972010-07-26 19:45:42 +00001739 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001740 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001741
1742 // FIXME: Check that the argument type matches the format specifier.
1743
1744 return true;
1745}
1746
1747void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001748 const Expr *OrigFormatExpr,
1749 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001750 unsigned format_idx, unsigned firstDataArg,
1751 bool isPrintf) {
1752
Ted Kremeneke0e53132010-01-28 23:39:18 +00001753 // CHECK: is the format string a wide literal?
1754 if (FExpr->isWide()) {
1755 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001756 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001757 << OrigFormatExpr->getSourceRange();
1758 return;
1759 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001760
Ted Kremeneke0e53132010-01-28 23:39:18 +00001761 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001762 llvm::StringRef StrRef = FExpr->getString();
1763 const char *Str = StrRef.data();
1764 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001765
Ted Kremeneke0e53132010-01-28 23:39:18 +00001766 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001767 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001768 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001769 << OrigFormatExpr->getSourceRange();
1770 return;
1771 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001772
1773 if (isPrintf) {
1774 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1775 TheCall->getNumArgs() - firstDataArg,
1776 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1777 HasVAListArg, TheCall, format_idx);
1778
1779 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1780 H.DoneProcessing();
1781 }
1782 else {
1783 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1784 TheCall->getNumArgs() - firstDataArg,
1785 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1786 HasVAListArg, TheCall, format_idx);
1787
1788 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1789 H.DoneProcessing();
1790 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001791}
1792
Ted Kremenek06de2762007-08-17 16:46:58 +00001793//===--- CHECK: Return Address of Stack Variable --------------------------===//
1794
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001795static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1796static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001797
1798/// CheckReturnStackAddr - Check if a return statement returns the address
1799/// of a stack variable.
1800void
1801Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1802 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001804 Expr *stackE = 0;
1805 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1806
1807 // Perform checking for returned stack addresses, local blocks,
1808 // label addresses or references to temporaries.
Steve Naroffdd972f22008-09-05 22:11:13 +00001809 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001810 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001811 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001812 stackE = EvalVal(RetValExp, refVars);
1813 }
1814
1815 if (stackE == 0)
1816 return; // Nothing suspicious was found.
1817
1818 SourceLocation diagLoc;
1819 SourceRange diagRange;
1820 if (refVars.empty()) {
1821 diagLoc = stackE->getLocStart();
1822 diagRange = stackE->getSourceRange();
1823 } else {
1824 // We followed through a reference variable. 'stackE' contains the
1825 // problematic expression but we will warn at the return statement pointing
1826 // at the reference variable. We will later display the "trail" of
1827 // reference variables using notes.
1828 diagLoc = refVars[0]->getLocStart();
1829 diagRange = refVars[0]->getSourceRange();
1830 }
1831
1832 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1833 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1834 : diag::warn_ret_stack_addr)
1835 << DR->getDecl()->getDeclName() << diagRange;
1836 } else if (isa<BlockExpr>(stackE)) { // local block.
1837 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1838 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1839 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1840 } else { // local temporary.
1841 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1842 : diag::warn_ret_local_temp_addr)
1843 << diagRange;
1844 }
1845
1846 // Display the "trail" of reference variables that we followed until we
1847 // found the problematic expression using notes.
1848 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1849 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1850 // If this var binds to another reference var, show the range of the next
1851 // var, otherwise the var binds to the problematic expression, in which case
1852 // show the range of the expression.
1853 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1854 : stackE->getSourceRange();
1855 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1856 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00001857 }
1858}
1859
1860/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1861/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001862/// to a location on the stack, a local block, an address of a label, or a
1863/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00001864/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001865/// encounter a subexpression that (1) clearly does not lead to one of the
1866/// above problematic expressions (2) is something we cannot determine leads to
1867/// a problematic expression based on such local checking.
1868///
1869/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1870/// the expression that they point to. Such variables are added to the
1871/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00001872///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001873/// EvalAddr processes expressions that are pointers that are used as
1874/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001875/// At the base case of the recursion is a check for the above problematic
1876/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00001877///
1878/// This implementation handles:
1879///
1880/// * pointer-to-pointer casts
1881/// * implicit conversions from array references to pointers
1882/// * taking the address of fields
1883/// * arbitrary interplay between "&" and "*" operators
1884/// * pointer arithmetic from an address of a stack variable
1885/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001886static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1887 if (E->isTypeDependent())
1888 return NULL;
1889
Ted Kremenek06de2762007-08-17 16:46:58 +00001890 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001891 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001892 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001893 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001894 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Ted Kremenek06de2762007-08-17 16:46:58 +00001896 // Our "symbolic interpreter" is just a dispatch off the currently
1897 // viewed AST node. We then recursively traverse the AST by calling
1898 // EvalAddr and EvalVal appropriately.
1899 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001900 case Stmt::ParenExprClass:
1901 // Ignore parentheses.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001902 return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1903
1904 case Stmt::DeclRefExprClass: {
1905 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1906
1907 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1908 // If this is a reference variable, follow through to the expression that
1909 // it points to.
1910 if (V->hasLocalStorage() &&
1911 V->getType()->isReferenceType() && V->hasInit()) {
1912 // Add the reference variable to the "trail".
1913 refVars.push_back(DR);
1914 return EvalAddr(V->getInit(), refVars);
1915 }
1916
1917 return NULL;
1918 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001919
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001920 case Stmt::UnaryOperatorClass: {
1921 // The only unary operator that make sense to handle here
1922 // is AddrOf. All others don't make sense as pointers.
1923 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001924
John McCall2de56d12010-08-25 11:45:40 +00001925 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001926 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001927 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001928 return NULL;
1929 }
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001931 case Stmt::BinaryOperatorClass: {
1932 // Handle pointer arithmetic. All other binary operators are not valid
1933 // in this context.
1934 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001935 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001936
John McCall2de56d12010-08-25 11:45:40 +00001937 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001938 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001940 Expr *Base = B->getLHS();
1941
1942 // Determine which argument is the real pointer base. It could be
1943 // the RHS argument instead of the LHS.
1944 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001946 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001947 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001948 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001949
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001950 // For conditional operators we need to see if either the LHS or RHS are
1951 // valid DeclRefExpr*s. If one of them is valid, we return it.
1952 case Stmt::ConditionalOperatorClass: {
1953 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001955 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001956 if (Expr *lhsExpr = C->getLHS()) {
1957 // In C++, we can have a throw-expression, which has 'void' type.
1958 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001959 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001960 return LHS;
1961 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001962
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001963 // In C++, we can have a throw-expression, which has 'void' type.
1964 if (C->getRHS()->getType()->isVoidType())
1965 return NULL;
1966
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001967 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001968 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001969
1970 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00001971 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001972 return E; // local block.
1973 return NULL;
1974
1975 case Stmt::AddrLabelExprClass:
1976 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Ted Kremenek54b52742008-08-07 00:49:01 +00001978 // For casts, we need to handle conversions from arrays to
1979 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001980 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001981 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001982 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001983 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001984 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Steve Naroffdd972f22008-09-05 22:11:13 +00001986 if (SubExpr->getType()->isPointerType() ||
1987 SubExpr->getType()->isBlockPointerType() ||
1988 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001989 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00001990 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001991 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001992 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001993 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001994 }
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001996 // C++ casts. For dynamic casts, static casts, and const casts, we
1997 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001998 // through the cast. In the case the dynamic cast doesn't fail (and
1999 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002000 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002001 // FIXME: The comment about is wrong; we're not always converting
2002 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002003 // handle references to objects.
2004 case Stmt::CXXStaticCastExprClass:
2005 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002006 case Stmt::CXXConstCastExprClass:
2007 case Stmt::CXXReinterpretCastExprClass: {
2008 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002009 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002010 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002011 else
2012 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002013 }
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002015 // Everything else: we simply don't reason about them.
2016 default:
2017 return NULL;
2018 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002019}
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Ted Kremenek06de2762007-08-17 16:46:58 +00002021
2022/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2023/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002024static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002025do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002026 // We should only be called for evaluating non-pointer expressions, or
2027 // expressions with a pointer type that are not used as references but instead
2028 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Ted Kremenek06de2762007-08-17 16:46:58 +00002030 // Our "symbolic interpreter" is just a dispatch off the currently
2031 // viewed AST node. We then recursively traverse the AST by calling
2032 // EvalAddr and EvalVal appropriately.
2033 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002034 case Stmt::ImplicitCastExprClass: {
2035 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002036 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002037 E = IE->getSubExpr();
2038 continue;
2039 }
2040 return NULL;
2041 }
2042
Douglas Gregora2813ce2009-10-23 18:54:35 +00002043 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002044 // When we hit a DeclRefExpr we are looking at code that refers to a
2045 // variable's name. If it's not a reference variable we check if it has
2046 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002047 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Ted Kremenek06de2762007-08-17 16:46:58 +00002049 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002050 if (V->hasLocalStorage()) {
2051 if (!V->getType()->isReferenceType())
2052 return DR;
2053
2054 // Reference variable, follow through to the expression that
2055 // it points to.
2056 if (V->hasInit()) {
2057 // Add the reference variable to the "trail".
2058 refVars.push_back(DR);
2059 return EvalVal(V->getInit(), refVars);
2060 }
2061 }
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Ted Kremenek06de2762007-08-17 16:46:58 +00002063 return NULL;
2064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Ted Kremenek68957a92010-08-04 20:01:07 +00002066 case Stmt::ParenExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002067 // Ignore parentheses.
Ted Kremenek68957a92010-08-04 20:01:07 +00002068 E = cast<ParenExpr>(E)->getSubExpr();
2069 continue;
2070 }
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Ted Kremenek06de2762007-08-17 16:46:58 +00002072 case Stmt::UnaryOperatorClass: {
2073 // The only unary operator that make sense to handle here
2074 // is Deref. All others don't resolve to a "name." This includes
2075 // handling all sorts of rvalues passed to a unary operator.
2076 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002077
John McCall2de56d12010-08-25 11:45:40 +00002078 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002079 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002080
2081 return NULL;
2082 }
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Ted Kremenek06de2762007-08-17 16:46:58 +00002084 case Stmt::ArraySubscriptExprClass: {
2085 // Array subscripts are potential references to data on the stack. We
2086 // retrieve the DeclRefExpr* for the array variable if it indeed
2087 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002088 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002089 }
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Ted Kremenek06de2762007-08-17 16:46:58 +00002091 case Stmt::ConditionalOperatorClass: {
2092 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002093 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002094 ConditionalOperator *C = cast<ConditionalOperator>(E);
2095
Anders Carlsson39073232007-11-30 19:04:31 +00002096 // Handle the GNU extension for missing LHS.
2097 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002098 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002099 return LHS;
2100
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002101 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002102 }
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Ted Kremenek06de2762007-08-17 16:46:58 +00002104 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002105 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002106 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Ted Kremenek06de2762007-08-17 16:46:58 +00002108 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002109 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002110 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002111
2112 // Check whether the member type is itself a reference, in which case
2113 // we're not going to refer to the member, but to what the member refers to.
2114 if (M->getMemberDecl()->getType()->isReferenceType())
2115 return NULL;
2116
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002117 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002118 }
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Ted Kremenek06de2762007-08-17 16:46:58 +00002120 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002121 // Check that we don't return or take the address of a reference to a
2122 // temporary. This is only useful in C++.
2123 if (!E->isTypeDependent() && E->isRValue())
2124 return E;
2125
2126 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002127 return NULL;
2128 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002129} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002130}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002131
2132//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2133
2134/// Check for comparisons of floating point operands using != and ==.
2135/// Issue a warning if these are no self-comparisons, as they are not likely
2136/// to do what the programmer intended.
2137void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2138 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002139
John McCallf6a16482010-12-04 03:47:34 +00002140 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2141 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002142
2143 // Special case: check for x == x (which is OK).
2144 // Do not emit warnings for such cases.
2145 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2146 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2147 if (DRL->getDecl() == DRR->getDecl())
2148 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002149
2150
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002151 // Special case: check for comparisons against literals that can be exactly
2152 // represented by APFloat. In such cases, do not emit a warning. This
2153 // is a heuristic: often comparison against such literals are used to
2154 // detect if a value in a variable has not changed. This clearly can
2155 // lead to false negatives.
2156 if (EmitWarning) {
2157 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2158 if (FLL->isExact())
2159 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002160 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002161 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2162 if (FLR->isExact())
2163 EmitWarning = false;
2164 }
2165 }
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002167 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002168 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002169 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002170 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002171 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Sebastian Redl0eb23302009-01-19 00:08:26 +00002173 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002174 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002175 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002176 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002178 // Emit the diagnostic.
2179 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002180 Diag(loc, diag::warn_floatingpoint_eq)
2181 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002182}
John McCallba26e582010-01-04 23:21:16 +00002183
John McCallf2370c92010-01-06 05:24:50 +00002184//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2185//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002186
John McCallf2370c92010-01-06 05:24:50 +00002187namespace {
John McCallba26e582010-01-04 23:21:16 +00002188
John McCallf2370c92010-01-06 05:24:50 +00002189/// Structure recording the 'active' range of an integer-valued
2190/// expression.
2191struct IntRange {
2192 /// The number of bits active in the int.
2193 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002194
John McCallf2370c92010-01-06 05:24:50 +00002195 /// True if the int is known not to have negative values.
2196 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002197
John McCallf2370c92010-01-06 05:24:50 +00002198 IntRange(unsigned Width, bool NonNegative)
2199 : Width(Width), NonNegative(NonNegative)
2200 {}
John McCallba26e582010-01-04 23:21:16 +00002201
John McCall1844a6e2010-11-10 23:38:19 +00002202 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002203 static IntRange forBoolType() {
2204 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002205 }
2206
John McCall1844a6e2010-11-10 23:38:19 +00002207 /// Returns the range of an opaque value of the given integral type.
2208 static IntRange forValueOfType(ASTContext &C, QualType T) {
2209 return forValueOfCanonicalType(C,
2210 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002211 }
2212
John McCall1844a6e2010-11-10 23:38:19 +00002213 /// Returns the range of an opaque value of a canonical integral type.
2214 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002215 assert(T->isCanonicalUnqualified());
2216
2217 if (const VectorType *VT = dyn_cast<VectorType>(T))
2218 T = VT->getElementType().getTypePtr();
2219 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2220 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002221
John McCall091f23f2010-11-09 22:22:12 +00002222 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002223 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2224 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002225 if (!Enum->isDefinition())
2226 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2227
John McCall323ed742010-05-06 08:58:33 +00002228 unsigned NumPositive = Enum->getNumPositiveBits();
2229 unsigned NumNegative = Enum->getNumNegativeBits();
2230
2231 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2232 }
John McCallf2370c92010-01-06 05:24:50 +00002233
2234 const BuiltinType *BT = cast<BuiltinType>(T);
2235 assert(BT->isInteger());
2236
2237 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2238 }
2239
John McCall1844a6e2010-11-10 23:38:19 +00002240 /// Returns the "target" range of a canonical integral type, i.e.
2241 /// the range of values expressible in the type.
2242 ///
2243 /// This matches forValueOfCanonicalType except that enums have the
2244 /// full range of their type, not the range of their enumerators.
2245 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2246 assert(T->isCanonicalUnqualified());
2247
2248 if (const VectorType *VT = dyn_cast<VectorType>(T))
2249 T = VT->getElementType().getTypePtr();
2250 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2251 T = CT->getElementType().getTypePtr();
2252 if (const EnumType *ET = dyn_cast<EnumType>(T))
2253 T = ET->getDecl()->getIntegerType().getTypePtr();
2254
2255 const BuiltinType *BT = cast<BuiltinType>(T);
2256 assert(BT->isInteger());
2257
2258 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2259 }
2260
2261 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002262 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002263 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002264 L.NonNegative && R.NonNegative);
2265 }
2266
John McCall1844a6e2010-11-10 23:38:19 +00002267 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002268 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002269 return IntRange(std::min(L.Width, R.Width),
2270 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002271 }
2272};
2273
2274IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2275 if (value.isSigned() && value.isNegative())
2276 return IntRange(value.getMinSignedBits(), false);
2277
2278 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002279 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002280
2281 // isNonNegative() just checks the sign bit without considering
2282 // signedness.
2283 return IntRange(value.getActiveBits(), true);
2284}
2285
John McCall0acc3112010-01-06 22:57:21 +00002286IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002287 unsigned MaxWidth) {
2288 if (result.isInt())
2289 return GetValueRange(C, result.getInt(), MaxWidth);
2290
2291 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002292 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2293 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2294 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2295 R = IntRange::join(R, El);
2296 }
John McCallf2370c92010-01-06 05:24:50 +00002297 return R;
2298 }
2299
2300 if (result.isComplexInt()) {
2301 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2302 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2303 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002304 }
2305
2306 // This can happen with lossless casts to intptr_t of "based" lvalues.
2307 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002308 // FIXME: The only reason we need to pass the type in here is to get
2309 // the sign right on this one case. It would be nice if APValue
2310 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002311 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002312 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002313}
John McCallf2370c92010-01-06 05:24:50 +00002314
2315/// Pseudo-evaluate the given integer expression, estimating the
2316/// range of values it might take.
2317///
2318/// \param MaxWidth - the width to which the value will be truncated
2319IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2320 E = E->IgnoreParens();
2321
2322 // Try a full evaluation first.
2323 Expr::EvalResult result;
2324 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002325 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002326
2327 // I think we only want to look through implicit casts here; if the
2328 // user has an explicit widening cast, we should treat the value as
2329 // being of the new, wider type.
2330 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002331 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002332 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2333
John McCall1844a6e2010-11-10 23:38:19 +00002334 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002335
John McCall2de56d12010-08-25 11:45:40 +00002336 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002337
John McCallf2370c92010-01-06 05:24:50 +00002338 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002339 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002340 return OutputTypeRange;
2341
2342 IntRange SubRange
2343 = GetExprRange(C, CE->getSubExpr(),
2344 std::min(MaxWidth, OutputTypeRange.Width));
2345
2346 // Bail out if the subexpr's range is as wide as the cast type.
2347 if (SubRange.Width >= OutputTypeRange.Width)
2348 return OutputTypeRange;
2349
2350 // Otherwise, we take the smaller width, and we're non-negative if
2351 // either the output type or the subexpr is.
2352 return IntRange(SubRange.Width,
2353 SubRange.NonNegative || OutputTypeRange.NonNegative);
2354 }
2355
2356 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2357 // If we can fold the condition, just take that operand.
2358 bool CondResult;
2359 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2360 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2361 : CO->getFalseExpr(),
2362 MaxWidth);
2363
2364 // Otherwise, conservatively merge.
2365 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2366 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2367 return IntRange::join(L, R);
2368 }
2369
2370 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2371 switch (BO->getOpcode()) {
2372
2373 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002374 case BO_LAnd:
2375 case BO_LOr:
2376 case BO_LT:
2377 case BO_GT:
2378 case BO_LE:
2379 case BO_GE:
2380 case BO_EQ:
2381 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002382 return IntRange::forBoolType();
2383
John McCallc0cd21d2010-02-23 19:22:29 +00002384 // The type of these compound assignments is the type of the LHS,
2385 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002386 case BO_MulAssign:
2387 case BO_DivAssign:
2388 case BO_RemAssign:
2389 case BO_AddAssign:
2390 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002391 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002392
John McCallf2370c92010-01-06 05:24:50 +00002393 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002394 case BO_PtrMemD:
2395 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002396 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002397
John McCall60fad452010-01-06 22:07:33 +00002398 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002399 case BO_And:
2400 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002401 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2402 GetExprRange(C, BO->getRHS(), MaxWidth));
2403
John McCallf2370c92010-01-06 05:24:50 +00002404 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002405 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002406 // ...except that we want to treat '1 << (blah)' as logically
2407 // positive. It's an important idiom.
2408 if (IntegerLiteral *I
2409 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2410 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002411 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002412 return IntRange(R.Width, /*NonNegative*/ true);
2413 }
2414 }
2415 // fallthrough
2416
John McCall2de56d12010-08-25 11:45:40 +00002417 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002418 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002419
John McCall60fad452010-01-06 22:07:33 +00002420 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002421 case BO_Shr:
2422 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002423 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2424
2425 // If the shift amount is a positive constant, drop the width by
2426 // that much.
2427 llvm::APSInt shift;
2428 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2429 shift.isNonNegative()) {
2430 unsigned zext = shift.getZExtValue();
2431 if (zext >= L.Width)
2432 L.Width = (L.NonNegative ? 0 : 1);
2433 else
2434 L.Width -= zext;
2435 }
2436
2437 return L;
2438 }
2439
2440 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002441 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002442 return GetExprRange(C, BO->getRHS(), MaxWidth);
2443
John McCall60fad452010-01-06 22:07:33 +00002444 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002445 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002446 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002447 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002448 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002449
John McCallf2370c92010-01-06 05:24:50 +00002450 default:
2451 break;
2452 }
2453
2454 // Treat every other operator as if it were closed on the
2455 // narrowest type that encompasses both operands.
2456 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2457 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2458 return IntRange::join(L, R);
2459 }
2460
2461 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2462 switch (UO->getOpcode()) {
2463 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002464 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002465 return IntRange::forBoolType();
2466
2467 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002468 case UO_Deref:
2469 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002470 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002471
2472 default:
2473 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2474 }
2475 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002476
2477 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002478 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002479 }
John McCallf2370c92010-01-06 05:24:50 +00002480
2481 FieldDecl *BitField = E->getBitField();
2482 if (BitField) {
2483 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2484 unsigned BitWidth = BitWidthAP.getZExtValue();
2485
2486 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2487 }
2488
John McCall1844a6e2010-11-10 23:38:19 +00002489 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002490}
John McCall51313c32010-01-04 23:31:57 +00002491
John McCall323ed742010-05-06 08:58:33 +00002492IntRange GetExprRange(ASTContext &C, Expr *E) {
2493 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2494}
2495
John McCall51313c32010-01-04 23:31:57 +00002496/// Checks whether the given value, which currently has the given
2497/// source semantics, has the same value when coerced through the
2498/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002499bool IsSameFloatAfterCast(const llvm::APFloat &value,
2500 const llvm::fltSemantics &Src,
2501 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002502 llvm::APFloat truncated = value;
2503
2504 bool ignored;
2505 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2506 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2507
2508 return truncated.bitwiseIsEqual(value);
2509}
2510
2511/// Checks whether the given value, which currently has the given
2512/// source semantics, has the same value when coerced through the
2513/// target semantics.
2514///
2515/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002516bool IsSameFloatAfterCast(const APValue &value,
2517 const llvm::fltSemantics &Src,
2518 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002519 if (value.isFloat())
2520 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2521
2522 if (value.isVector()) {
2523 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2524 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2525 return false;
2526 return true;
2527 }
2528
2529 assert(value.isComplexFloat());
2530 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2531 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2532}
2533
John McCallb4eb64d2010-10-08 02:01:28 +00002534void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002535
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002536static bool IsZero(Sema &S, Expr *E) {
2537 // Suppress cases where we are comparing against an enum constant.
2538 if (const DeclRefExpr *DR =
2539 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2540 if (isa<EnumConstantDecl>(DR->getDecl()))
2541 return false;
2542
2543 // Suppress cases where the '0' value is expanded from a macro.
2544 if (E->getLocStart().isMacroID())
2545 return false;
2546
John McCall323ed742010-05-06 08:58:33 +00002547 llvm::APSInt Value;
2548 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2549}
2550
John McCall372e1032010-10-06 00:25:24 +00002551static bool HasEnumType(Expr *E) {
2552 // Strip off implicit integral promotions.
2553 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002554 if (ICE->getCastKind() != CK_IntegralCast &&
2555 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002556 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002557 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002558 }
2559
2560 return E->getType()->isEnumeralType();
2561}
2562
John McCall323ed742010-05-06 08:58:33 +00002563void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002564 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002565 if (E->isValueDependent())
2566 return;
2567
John McCall2de56d12010-08-25 11:45:40 +00002568 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002569 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002570 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002571 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002572 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002573 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002574 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002575 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002576 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002577 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002578 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002579 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002580 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002581 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002582 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002583 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2584 }
2585}
2586
2587/// Analyze the operands of the given comparison. Implements the
2588/// fallback case from AnalyzeComparison.
2589void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002590 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2591 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002592}
John McCall51313c32010-01-04 23:31:57 +00002593
John McCallba26e582010-01-04 23:21:16 +00002594/// \brief Implements -Wsign-compare.
2595///
2596/// \param lex the left-hand expression
2597/// \param rex the right-hand expression
2598/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002599/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002600void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2601 // The type the comparison is being performed in.
2602 QualType T = E->getLHS()->getType();
2603 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2604 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002605
John McCall323ed742010-05-06 08:58:33 +00002606 // We don't do anything special if this isn't an unsigned integral
2607 // comparison: we're only interested in integral comparisons, and
2608 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002609 //
2610 // We also don't care about value-dependent expressions or expressions
2611 // whose result is a constant.
2612 if (!T->hasUnsignedIntegerRepresentation()
2613 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002614 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002615
John McCall323ed742010-05-06 08:58:33 +00002616 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2617 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002618
John McCall323ed742010-05-06 08:58:33 +00002619 // Check to see if one of the (unmodified) operands is of different
2620 // signedness.
2621 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002622 if (lex->getType()->hasSignedIntegerRepresentation()) {
2623 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002624 "unsigned comparison between two signed integer expressions?");
2625 signedOperand = lex;
2626 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002627 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002628 signedOperand = rex;
2629 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002630 } else {
John McCall323ed742010-05-06 08:58:33 +00002631 CheckTrivialUnsignedComparison(S, E);
2632 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002633 }
2634
John McCall323ed742010-05-06 08:58:33 +00002635 // Otherwise, calculate the effective range of the signed operand.
2636 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002637
John McCall323ed742010-05-06 08:58:33 +00002638 // Go ahead and analyze implicit conversions in the operands. Note
2639 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002640 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2641 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002642
John McCall323ed742010-05-06 08:58:33 +00002643 // If the signed range is non-negative, -Wsign-compare won't fire,
2644 // but we should still check for comparisons which are always true
2645 // or false.
2646 if (signedRange.NonNegative)
2647 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002648
2649 // For (in)equality comparisons, if the unsigned operand is a
2650 // constant which cannot collide with a overflowed signed operand,
2651 // then reinterpreting the signed operand as unsigned will not
2652 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002653 if (E->isEqualityOp()) {
2654 unsigned comparisonWidth = S.Context.getIntWidth(T);
2655 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002656
John McCall323ed742010-05-06 08:58:33 +00002657 // We should never be unable to prove that the unsigned operand is
2658 // non-negative.
2659 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2660
2661 if (unsignedRange.Width < comparisonWidth)
2662 return;
2663 }
2664
2665 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2666 << lex->getType() << rex->getType()
2667 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002668}
2669
John McCall15d7d122010-11-11 03:21:53 +00002670/// Analyzes an attempt to assign the given value to a bitfield.
2671///
2672/// Returns true if there was something fishy about the attempt.
2673bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2674 SourceLocation InitLoc) {
2675 assert(Bitfield->isBitField());
2676 if (Bitfield->isInvalidDecl())
2677 return false;
2678
John McCall91b60142010-11-11 05:33:51 +00002679 // White-list bool bitfields.
2680 if (Bitfield->getType()->isBooleanType())
2681 return false;
2682
Douglas Gregor46ff3032011-02-04 13:09:01 +00002683 // Ignore value- or type-dependent expressions.
2684 if (Bitfield->getBitWidth()->isValueDependent() ||
2685 Bitfield->getBitWidth()->isTypeDependent() ||
2686 Init->isValueDependent() ||
2687 Init->isTypeDependent())
2688 return false;
2689
John McCall15d7d122010-11-11 03:21:53 +00002690 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2691
2692 llvm::APSInt Width(32);
2693 Expr::EvalResult InitValue;
2694 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002695 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002696 !InitValue.Val.isInt())
2697 return false;
2698
2699 const llvm::APSInt &Value = InitValue.Val.getInt();
2700 unsigned OriginalWidth = Value.getBitWidth();
2701 unsigned FieldWidth = Width.getZExtValue();
2702
2703 if (OriginalWidth <= FieldWidth)
2704 return false;
2705
Jay Foad9f71a8f2010-12-07 08:25:34 +00002706 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002707
2708 // It's fairly common to write values into signed bitfields
2709 // that, if sign-extended, would end up becoming a different
2710 // value. We don't want to warn about that.
2711 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002712 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002713 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002714 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002715
2716 if (Value == TruncatedValue)
2717 return false;
2718
2719 std::string PrettyValue = Value.toString(10);
2720 std::string PrettyTrunc = TruncatedValue.toString(10);
2721
2722 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2723 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2724 << Init->getSourceRange();
2725
2726 return true;
2727}
2728
John McCallbeb22aa2010-11-09 23:24:47 +00002729/// Analyze the given simple or compound assignment for warning-worthy
2730/// operations.
2731void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2732 // Just recurse on the LHS.
2733 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2734
2735 // We want to recurse on the RHS as normal unless we're assigning to
2736 // a bitfield.
2737 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002738 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2739 E->getOperatorLoc())) {
2740 // Recurse, ignoring any implicit conversions on the RHS.
2741 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2742 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002743 }
2744 }
2745
2746 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2747}
2748
John McCall51313c32010-01-04 23:31:57 +00002749/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCallb4eb64d2010-10-08 02:01:28 +00002750void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2751 unsigned diag) {
2752 S.Diag(E->getExprLoc(), diag)
2753 << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
John McCall51313c32010-01-04 23:31:57 +00002754}
2755
John McCall091f23f2010-11-09 22:22:12 +00002756std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2757 if (!Range.Width) return "0";
2758
2759 llvm::APSInt ValueInRange = Value;
2760 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002761 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002762 return ValueInRange.toString(10);
2763}
2764
Ted Kremenekef9ff882011-03-10 20:03:42 +00002765static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2766 SourceManager &smgr = S.Context.getSourceManager();
2767 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2768}
2769
John McCall323ed742010-05-06 08:58:33 +00002770void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002771 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002772 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002773
John McCall323ed742010-05-06 08:58:33 +00002774 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2775 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2776 if (Source == Target) return;
2777 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002778
Ted Kremenekef9ff882011-03-10 20:03:42 +00002779 // If the conversion context location is invalid don't complain.
2780 // We also don't want to emit a warning if the issue occurs from the
2781 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2782 // is slow, so we delay this check as long as possible. Once we detect
2783 // we are in that scenario, we just return.
2784 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00002785 return;
2786
John McCall51313c32010-01-04 23:31:57 +00002787 // Never diagnose implicit casts to bool.
2788 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2789 return;
2790
2791 // Strip vector types.
2792 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002793 if (!isa<VectorType>(Target)) {
2794 if (isFromSystemMacro(S, CC))
2795 return;
John McCallb4eb64d2010-10-08 02:01:28 +00002796 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002797 }
John McCall51313c32010-01-04 23:31:57 +00002798
2799 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2800 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2801 }
2802
2803 // Strip complex types.
2804 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002805 if (!isa<ComplexType>(Target)) {
2806 if (isFromSystemMacro(S, CC))
2807 return;
2808
John McCallb4eb64d2010-10-08 02:01:28 +00002809 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002810 }
John McCall51313c32010-01-04 23:31:57 +00002811
2812 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2813 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2814 }
2815
2816 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2817 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2818
2819 // If the source is floating point...
2820 if (SourceBT && SourceBT->isFloatingPoint()) {
2821 // ...and the target is floating point...
2822 if (TargetBT && TargetBT->isFloatingPoint()) {
2823 // ...then warn if we're dropping FP rank.
2824
2825 // Builtin FP kinds are ordered by increasing FP rank.
2826 if (SourceBT->getKind() > TargetBT->getKind()) {
2827 // Don't warn about float constants that are precisely
2828 // representable in the target type.
2829 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002830 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002831 // Value might be a float, a float vector, or a float complex.
2832 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002833 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2834 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002835 return;
2836 }
2837
Ted Kremenekef9ff882011-03-10 20:03:42 +00002838 if (isFromSystemMacro(S, CC))
2839 return;
2840
John McCallb4eb64d2010-10-08 02:01:28 +00002841 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002842 }
2843 return;
2844 }
2845
Ted Kremenekef9ff882011-03-10 20:03:42 +00002846 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00002847 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002848 if (isFromSystemMacro(S, CC))
2849 return;
2850
Chandler Carrutha5b93322011-02-17 11:05:49 +00002851 Expr *InnerE = E->IgnoreParenImpCasts();
2852 if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) {
2853 DiagnoseImpCast(S, LiteralExpr, T, CC,
2854 diag::warn_impcast_literal_float_to_integer);
2855 } else {
2856 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2857 }
2858 }
John McCall51313c32010-01-04 23:31:57 +00002859
2860 return;
2861 }
2862
John McCallf2370c92010-01-06 05:24:50 +00002863 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002864 return;
2865
John McCall323ed742010-05-06 08:58:33 +00002866 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002867 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002868
2869 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002870 // If the source is a constant, use a default-on diagnostic.
2871 // TODO: this should happen for bitfield stores, too.
2872 llvm::APSInt Value(32);
2873 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002874 if (isFromSystemMacro(S, CC))
2875 return;
2876
John McCall091f23f2010-11-09 22:22:12 +00002877 std::string PrettySourceValue = Value.toString(10);
2878 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2879
2880 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2881 << PrettySourceValue << PrettyTargetValue
2882 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2883 return;
2884 }
2885
John McCall51313c32010-01-04 23:31:57 +00002886 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2887 // and by god we'll let them.
Ted Kremenekef9ff882011-03-10 20:03:42 +00002888
2889 if (isFromSystemMacro(S, CC))
2890 return;
2891
John McCallf2370c92010-01-06 05:24:50 +00002892 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002893 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2894 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002895 }
2896
2897 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2898 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2899 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002900
2901 if (isFromSystemMacro(S, CC))
2902 return;
2903
John McCall323ed742010-05-06 08:58:33 +00002904 unsigned DiagID = diag::warn_impcast_integer_sign;
2905
2906 // Traditionally, gcc has warned about this under -Wsign-compare.
2907 // We also want to warn about it in -Wconversion.
2908 // So if -Wconversion is off, use a completely identical diagnostic
2909 // in the sign-compare group.
2910 // The conditional-checking code will
2911 if (ICContext) {
2912 DiagID = diag::warn_impcast_integer_sign_conditional;
2913 *ICContext = true;
2914 }
2915
John McCallb4eb64d2010-10-08 02:01:28 +00002916 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002917 }
2918
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002919 // Diagnose conversions between different enumeration types.
2920 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
2921 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
2922 if ((SourceEnum->getDecl()->getIdentifier() ||
2923 SourceEnum->getDecl()->getTypedefForAnonDecl()) &&
2924 (TargetEnum->getDecl()->getIdentifier() ||
2925 TargetEnum->getDecl()->getTypedefForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00002926 SourceEnum != TargetEnum) {
2927 if (isFromSystemMacro(S, CC))
2928 return;
2929
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002930 return DiagnoseImpCast(S, E, T, CC,
2931 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002932 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002933
John McCall51313c32010-01-04 23:31:57 +00002934 return;
2935}
2936
John McCall323ed742010-05-06 08:58:33 +00002937void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2938
2939void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002940 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00002941 E = E->IgnoreParenImpCasts();
2942
2943 if (isa<ConditionalOperator>(E))
2944 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2945
John McCallb4eb64d2010-10-08 02:01:28 +00002946 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002947 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002948 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00002949 return;
2950}
2951
2952void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00002953 SourceLocation CC = E->getQuestionLoc();
2954
2955 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00002956
2957 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00002958 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2959 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002960
2961 // If -Wconversion would have warned about either of the candidates
2962 // for a signedness conversion to the context type...
2963 if (!Suspicious) return;
2964
2965 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002966 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
2967 CC))
John McCall323ed742010-05-06 08:58:33 +00002968 return;
2969
2970 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002971 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00002972 return;
2973
2974 // ...then check whether it would have warned about either of the
2975 // candidates for a signedness conversion to the condition type.
2976 if (E->getType() != T) {
2977 Suspicious = false;
2978 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002979 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002980 if (!Suspicious)
2981 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002982 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002983 if (!Suspicious)
2984 return;
2985 }
2986
2987 // If so, emit a diagnostic under -Wsign-compare.
2988 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2989 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2990 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2991 << lex->getType() << rex->getType()
2992 << lex->getSourceRange() << rex->getSourceRange();
2993}
2994
2995/// AnalyzeImplicitConversions - Find and report any interesting
2996/// implicit conversions in the given expression. There are a couple
2997/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00002998void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00002999 QualType T = OrigE->getType();
3000 Expr *E = OrigE->IgnoreParenImpCasts();
3001
3002 // For conditional operators, we analyze the arguments as if they
3003 // were being fed directly into the output.
3004 if (isa<ConditionalOperator>(E)) {
3005 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3006 CheckConditionalOperator(S, CO, T);
3007 return;
3008 }
3009
3010 // Go ahead and check any implicit conversions we might have skipped.
3011 // The non-canonical typecheck is just an optimization;
3012 // CheckImplicitConversion will filter out dead implicit conversions.
3013 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003014 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003015
3016 // Now continue drilling into this expression.
3017
3018 // Skip past explicit casts.
3019 if (isa<ExplicitCastExpr>(E)) {
3020 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003021 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003022 }
3023
John McCallbeb22aa2010-11-09 23:24:47 +00003024 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3025 // Do a somewhat different check with comparison operators.
3026 if (BO->isComparisonOp())
3027 return AnalyzeComparison(S, BO);
3028
3029 // And with assignments and compound assignments.
3030 if (BO->isAssignmentOp())
3031 return AnalyzeAssignment(S, BO);
3032 }
John McCall323ed742010-05-06 08:58:33 +00003033
3034 // These break the otherwise-useful invariant below. Fortunately,
3035 // we don't really need to recurse into them, because any internal
3036 // expressions should have been analyzed already when they were
3037 // built into statements.
3038 if (isa<StmtExpr>(E)) return;
3039
3040 // Don't descend into unevaluated contexts.
3041 if (isa<SizeOfAlignOfExpr>(E)) return;
3042
3043 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003044 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003045 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003046 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003047}
3048
3049} // end anonymous namespace
3050
3051/// Diagnoses "dangerous" implicit conversions within the given
3052/// expression (which is a full expression). Implements -Wconversion
3053/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003054///
3055/// \param CC the "context" location of the implicit conversion, i.e.
3056/// the most location of the syntactic entity requiring the implicit
3057/// conversion
3058void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003059 // Don't diagnose in unevaluated contexts.
3060 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3061 return;
3062
3063 // Don't diagnose for value- or type-dependent expressions.
3064 if (E->isTypeDependent() || E->isValueDependent())
3065 return;
3066
John McCallb4eb64d2010-10-08 02:01:28 +00003067 // This is not the right CC for (e.g.) a variable initialization.
3068 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003069}
3070
John McCall15d7d122010-11-11 03:21:53 +00003071void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3072 FieldDecl *BitField,
3073 Expr *Init) {
3074 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3075}
3076
Mike Stumpf8c49212010-01-21 03:59:47 +00003077/// CheckParmsForFunctionDef - Check that the parameters of the given
3078/// function are appropriate for the definition of a function. This
3079/// takes care of any checks that cannot be performed on the
3080/// declaration itself, e.g., that the types of each of the function
3081/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003082bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3083 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003084 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003085 for (; P != PEnd; ++P) {
3086 ParmVarDecl *Param = *P;
3087
Mike Stumpf8c49212010-01-21 03:59:47 +00003088 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3089 // function declarator that is part of a function definition of
3090 // that function shall not have incomplete type.
3091 //
3092 // This is also C++ [dcl.fct]p6.
3093 if (!Param->isInvalidDecl() &&
3094 RequireCompleteType(Param->getLocation(), Param->getType(),
3095 diag::err_typecheck_decl_incomplete_type)) {
3096 Param->setInvalidDecl();
3097 HasInvalidParm = true;
3098 }
3099
3100 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3101 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003102 if (CheckParameterNames &&
3103 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003104 !Param->isImplicit() &&
3105 !getLangOptions().CPlusPlus)
3106 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003107
3108 // C99 6.7.5.3p12:
3109 // If the function declarator is not part of a definition of that
3110 // function, parameters may have incomplete type and may use the [*]
3111 // notation in their sequences of declarator specifiers to specify
3112 // variable length array types.
3113 QualType PType = Param->getOriginalType();
3114 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3115 if (AT->getSizeModifier() == ArrayType::Star) {
3116 // FIXME: This diagnosic should point the the '[*]' if source-location
3117 // information is added for it.
3118 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3119 }
3120 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003121 }
3122
3123 return HasInvalidParm;
3124}
John McCallb7f4ffe2010-08-12 21:44:57 +00003125
3126/// CheckCastAlign - Implements -Wcast-align, which warns when a
3127/// pointer cast increases the alignment requirements.
3128void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3129 // This is actually a lot of work to potentially be doing on every
3130 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003131 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3132 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003133 == Diagnostic::Ignored)
3134 return;
3135
3136 // Ignore dependent types.
3137 if (T->isDependentType() || Op->getType()->isDependentType())
3138 return;
3139
3140 // Require that the destination be a pointer type.
3141 const PointerType *DestPtr = T->getAs<PointerType>();
3142 if (!DestPtr) return;
3143
3144 // If the destination has alignment 1, we're done.
3145 QualType DestPointee = DestPtr->getPointeeType();
3146 if (DestPointee->isIncompleteType()) return;
3147 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3148 if (DestAlign.isOne()) return;
3149
3150 // Require that the source be a pointer type.
3151 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3152 if (!SrcPtr) return;
3153 QualType SrcPointee = SrcPtr->getPointeeType();
3154
3155 // Whitelist casts from cv void*. We already implicitly
3156 // whitelisted casts to cv void*, since they have alignment 1.
3157 // Also whitelist casts involving incomplete types, which implicitly
3158 // includes 'void'.
3159 if (SrcPointee->isIncompleteType()) return;
3160
3161 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3162 if (SrcAlign >= DestAlign) return;
3163
3164 Diag(TRange.getBegin(), diag::warn_cast_align)
3165 << Op->getType() << T
3166 << static_cast<unsigned>(SrcAlign.getQuantity())
3167 << static_cast<unsigned>(DestAlign.getQuantity())
3168 << TRange << Op->getSourceRange();
3169}
3170
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003171static void CheckArrayAccess_Check(Sema &S,
3172 const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003173 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003174 const ConstantArrayType *ArrayTy =
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003175 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003176 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003177 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003178
Chandler Carruth34064582011-02-17 20:55:08 +00003179 const Expr *IndexExpr = E->getIdx();
3180 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003181 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003182 llvm::APSInt index;
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003183 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003184 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003185
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003186 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003187 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003188 if (!size.isStrictlyPositive())
3189 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003190 if (size.getBitWidth() > index.getBitWidth())
3191 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003192 else if (size.getBitWidth() < index.getBitWidth())
3193 size = size.sext(index.getBitWidth());
3194
Chandler Carruth34064582011-02-17 20:55:08 +00003195 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003196 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003197
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003198 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3199 S.PDiag(diag::warn_array_index_exceeds_bounds)
3200 << index.toString(10, true)
3201 << size.toString(10, true)
3202 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003203 } else {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003204 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3205 S.PDiag(diag::warn_array_index_precedes_bounds)
3206 << index.toString(10, true)
3207 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003208 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003209
3210 const NamedDecl *ND = NULL;
3211 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3212 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3213 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3214 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3215 if (ND)
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003216 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3217 S.PDiag(diag::note_array_index_out_of_bounds)
3218 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003219}
3220
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003221void Sema::CheckArrayAccess(const Expr *expr) {
3222 while (true)
3223 switch (expr->getStmtClass()) {
3224 case Stmt::ParenExprClass:
3225 expr = cast<ParenExpr>(expr)->getSubExpr();
3226 continue;
3227 case Stmt::ArraySubscriptExprClass:
3228 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3229 return;
3230 case Stmt::ConditionalOperatorClass: {
3231 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3232 if (const Expr *lhs = cond->getLHS())
3233 CheckArrayAccess(lhs);
3234 if (const Expr *rhs = cond->getRHS())
3235 CheckArrayAccess(rhs);
3236 return;
3237 }
3238 default:
3239 return;
3240 }
3241}