blob: 24cf23bf436def522d41e9b2d5c5528133b8100c [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) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001221 if (!IsObjCLiteral) {
1222 // The presence of a null character is likely an error.
1223 S.Diag(getLocationOfByte(nullCharacter),
1224 diag::warn_printf_format_string_contains_null_char)
1225 << getFormatStringRange();
1226 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001227}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001228
Ted Kremenek826a3452010-07-16 02:11:22 +00001229const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1230 return TheCall->getArg(FirstDataArg + i);
1231}
1232
1233void CheckFormatHandler::DoneProcessing() {
1234 // Does the number of data arguments exceed the number of
1235 // format conversions in the format string?
1236 if (!HasVAListArg) {
1237 // Find any arguments that weren't covered.
1238 CoveredArgs.flip();
1239 signed notCoveredArg = CoveredArgs.find_first();
1240 if (notCoveredArg >= 0) {
1241 assert((unsigned)notCoveredArg < NumDataArgs);
1242 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1243 diag::warn_printf_data_arg_not_used)
1244 << getFormatStringRange();
1245 }
1246 }
1247}
1248
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001249bool
1250CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1251 SourceLocation Loc,
1252 const char *startSpec,
1253 unsigned specifierLen,
1254 const char *csStart,
1255 unsigned csLen) {
1256
1257 bool keepGoing = true;
1258 if (argIndex < NumDataArgs) {
1259 // Consider the argument coverered, even though the specifier doesn't
1260 // make sense.
1261 CoveredArgs.set(argIndex);
1262 }
1263 else {
1264 // If argIndex exceeds the number of data arguments we
1265 // don't issue a warning because that is just a cascade of warnings (and
1266 // they may have intended '%%' anyway). We don't want to continue processing
1267 // the format string after this point, however, as we will like just get
1268 // gibberish when trying to match arguments.
1269 keepGoing = false;
1270 }
1271
1272 S.Diag(Loc, diag::warn_format_invalid_conversion)
1273 << llvm::StringRef(csStart, csLen)
1274 << getSpecifierRange(startSpec, specifierLen);
1275
1276 return keepGoing;
1277}
1278
Ted Kremenek666a1972010-07-26 19:45:42 +00001279bool
1280CheckFormatHandler::CheckNumArgs(
1281 const analyze_format_string::FormatSpecifier &FS,
1282 const analyze_format_string::ConversionSpecifier &CS,
1283 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1284
1285 if (argIndex >= NumDataArgs) {
1286 if (FS.usesPositionalArg()) {
1287 S.Diag(getLocationOfByte(CS.getStart()),
1288 diag::warn_printf_positional_arg_exceeds_data_args)
1289 << (argIndex+1) << NumDataArgs
1290 << getSpecifierRange(startSpecifier, specifierLen);
1291 }
1292 else {
1293 S.Diag(getLocationOfByte(CS.getStart()),
1294 diag::warn_printf_insufficient_data_args)
1295 << getSpecifierRange(startSpecifier, specifierLen);
1296 }
1297
1298 return false;
1299 }
1300 return true;
1301}
1302
Ted Kremenek826a3452010-07-16 02:11:22 +00001303//===--- CHECK: Printf format string checking ------------------------------===//
1304
1305namespace {
1306class CheckPrintfHandler : public CheckFormatHandler {
1307public:
1308 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1309 const Expr *origFormatExpr, unsigned firstDataArg,
1310 unsigned numDataArgs, bool isObjCLiteral,
1311 const char *beg, bool hasVAListArg,
1312 const CallExpr *theCall, unsigned formatIdx)
1313 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1314 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1315 theCall, formatIdx) {}
1316
1317
1318 bool HandleInvalidPrintfConversionSpecifier(
1319 const analyze_printf::PrintfSpecifier &FS,
1320 const char *startSpecifier,
1321 unsigned specifierLen);
1322
1323 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1324 const char *startSpecifier,
1325 unsigned specifierLen);
1326
1327 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1328 const char *startSpecifier, unsigned specifierLen);
1329 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1330 const analyze_printf::OptionalAmount &Amt,
1331 unsigned type,
1332 const char *startSpecifier, unsigned specifierLen);
1333 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1334 const analyze_printf::OptionalFlag &flag,
1335 const char *startSpecifier, unsigned specifierLen);
1336 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1337 const analyze_printf::OptionalFlag &ignoredFlag,
1338 const analyze_printf::OptionalFlag &flag,
1339 const char *startSpecifier, unsigned specifierLen);
1340};
1341}
1342
1343bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1344 const analyze_printf::PrintfSpecifier &FS,
1345 const char *startSpecifier,
1346 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001347 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001348 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001349
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001350 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1351 getLocationOfByte(CS.getStart()),
1352 startSpecifier, specifierLen,
1353 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001354}
1355
Ted Kremenek826a3452010-07-16 02:11:22 +00001356bool CheckPrintfHandler::HandleAmount(
1357 const analyze_format_string::OptionalAmount &Amt,
1358 unsigned k, const char *startSpecifier,
1359 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001360
1361 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001362 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001363 unsigned argIndex = Amt.getArgIndex();
1364 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001365 S.Diag(getLocationOfByte(Amt.getStart()),
1366 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001367 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001368 // Don't do any more checking. We will just emit
1369 // spurious errors.
1370 return false;
1371 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001372
Ted Kremenek0d277352010-01-29 01:06:55 +00001373 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001374 // Although not in conformance with C99, we also allow the argument to be
1375 // an 'unsigned int' as that is a reasonably safe case. GCC also
1376 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001377 CoveredArgs.set(argIndex);
1378 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001379 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001380
1381 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1382 assert(ATR.isValid());
1383
1384 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001385 S.Diag(getLocationOfByte(Amt.getStart()),
1386 diag::warn_printf_asterisk_wrong_type)
1387 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001388 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001389 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001390 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001391 // Don't do any more checking. We will just emit
1392 // spurious errors.
1393 return false;
1394 }
1395 }
1396 }
1397 return true;
1398}
Ted Kremenek0d277352010-01-29 01:06:55 +00001399
Tom Caree4ee9662010-06-17 19:00:27 +00001400void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001401 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001402 const analyze_printf::OptionalAmount &Amt,
1403 unsigned type,
1404 const char *startSpecifier,
1405 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001406 const analyze_printf::PrintfConversionSpecifier &CS =
1407 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001408 switch (Amt.getHowSpecified()) {
1409 case analyze_printf::OptionalAmount::Constant:
1410 S.Diag(getLocationOfByte(Amt.getStart()),
1411 diag::warn_printf_nonsensical_optional_amount)
1412 << type
1413 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001414 << getSpecifierRange(startSpecifier, specifierLen)
1415 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001416 Amt.getConstantLength()));
1417 break;
1418
1419 default:
1420 S.Diag(getLocationOfByte(Amt.getStart()),
1421 diag::warn_printf_nonsensical_optional_amount)
1422 << type
1423 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001424 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001425 break;
1426 }
1427}
1428
Ted Kremenek826a3452010-07-16 02:11:22 +00001429void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001430 const analyze_printf::OptionalFlag &flag,
1431 const char *startSpecifier,
1432 unsigned specifierLen) {
1433 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001434 const analyze_printf::PrintfConversionSpecifier &CS =
1435 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001436 S.Diag(getLocationOfByte(flag.getPosition()),
1437 diag::warn_printf_nonsensical_flag)
1438 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001439 << getSpecifierRange(startSpecifier, specifierLen)
1440 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001441}
1442
1443void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001444 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001445 const analyze_printf::OptionalFlag &ignoredFlag,
1446 const analyze_printf::OptionalFlag &flag,
1447 const char *startSpecifier,
1448 unsigned specifierLen) {
1449 // Warn about ignored flag with a fixit removal.
1450 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1451 diag::warn_printf_ignored_flag)
1452 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001453 << getSpecifierRange(startSpecifier, specifierLen)
1454 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001455 ignoredFlag.getPosition(), 1));
1456}
1457
Ted Kremeneke0e53132010-01-28 23:39:18 +00001458bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001459CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001460 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001461 const char *startSpecifier,
1462 unsigned specifierLen) {
1463
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001464 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001465 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001466 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001467
Ted Kremenekbaa40062010-07-19 22:01:06 +00001468 if (FS.consumesDataArgument()) {
1469 if (atFirstArg) {
1470 atFirstArg = false;
1471 usesPositionalArgs = FS.usesPositionalArg();
1472 }
1473 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1474 // Cannot mix-and-match positional and non-positional arguments.
1475 S.Diag(getLocationOfByte(CS.getStart()),
1476 diag::warn_format_mix_positional_nonpositional_args)
1477 << getSpecifierRange(startSpecifier, specifierLen);
1478 return false;
1479 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001480 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001481
Ted Kremenekefaff192010-02-27 01:41:03 +00001482 // First check if the field width, precision, and conversion specifier
1483 // have matching data arguments.
1484 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1485 startSpecifier, specifierLen)) {
1486 return false;
1487 }
1488
1489 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1490 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001491 return false;
1492 }
1493
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001494 if (!CS.consumesDataArgument()) {
1495 // FIXME: Technically specifying a precision or field width here
1496 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001497 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001498 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001499
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001500 // Consume the argument.
1501 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001502 if (argIndex < NumDataArgs) {
1503 // The check to see if the argIndex is valid will come later.
1504 // We set the bit here because we may exit early from this
1505 // function if we encounter some other error.
1506 CoveredArgs.set(argIndex);
1507 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001508
1509 // Check for using an Objective-C specific conversion specifier
1510 // in a non-ObjC literal.
1511 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001512 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1513 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001514 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001515
Tom Caree4ee9662010-06-17 19:00:27 +00001516 // Check for invalid use of field width
1517 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001518 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001519 startSpecifier, specifierLen);
1520 }
1521
1522 // Check for invalid use of precision
1523 if (!FS.hasValidPrecision()) {
1524 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1525 startSpecifier, specifierLen);
1526 }
1527
1528 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001529 if (!FS.hasValidThousandsGroupingPrefix())
1530 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001531 if (!FS.hasValidLeadingZeros())
1532 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1533 if (!FS.hasValidPlusPrefix())
1534 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001535 if (!FS.hasValidSpacePrefix())
1536 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001537 if (!FS.hasValidAlternativeForm())
1538 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1539 if (!FS.hasValidLeftJustified())
1540 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1541
1542 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001543 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1544 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1545 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001546 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1547 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1548 startSpecifier, specifierLen);
1549
1550 // Check the length modifier is valid with the given conversion specifier.
1551 const LengthModifier &LM = FS.getLengthModifier();
1552 if (!FS.hasValidLengthModifier())
1553 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001554 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001555 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001556 << getSpecifierRange(startSpecifier, specifierLen)
1557 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001558 LM.getLength()));
1559
1560 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001561 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001562 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001563 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001564 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001565 // Continue checking the other format specifiers.
1566 return true;
1567 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001568
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001569 // The remaining checks depend on the data arguments.
1570 if (HasVAListArg)
1571 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001572
Ted Kremenek666a1972010-07-26 19:45:42 +00001573 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001574 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001575
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001576 // Now type check the data expression that matches the
1577 // format specifier.
1578 const Expr *Ex = getDataArg(argIndex);
1579 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1580 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1581 // Check if we didn't match because of an implicit cast from a 'char'
1582 // or 'short' to an 'int'. This is done because printf is a varargs
1583 // function.
1584 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001585 if (ICE->getType() == S.Context.IntTy) {
1586 // All further checking is done on the subexpression.
1587 Ex = ICE->getSubExpr();
1588 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001589 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001590 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001591
1592 // We may be able to offer a FixItHint if it is a supported type.
1593 PrintfSpecifier fixedFS = FS;
1594 bool success = fixedFS.fixType(Ex->getType());
1595
1596 if (success) {
1597 // Get the fix string from the fixed format specifier
1598 llvm::SmallString<128> buf;
1599 llvm::raw_svector_ostream os(buf);
1600 fixedFS.toString(os);
1601
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001602 // FIXME: getRepresentativeType() perhaps should return a string
1603 // instead of a QualType to better handle when the representative
1604 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001605 S.Diag(getLocationOfByte(CS.getStart()),
1606 diag::warn_printf_conversion_argument_type_mismatch)
1607 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1608 << getSpecifierRange(startSpecifier, specifierLen)
1609 << Ex->getSourceRange()
1610 << FixItHint::CreateReplacement(
1611 getSpecifierRange(startSpecifier, specifierLen),
1612 os.str());
1613 }
1614 else {
1615 S.Diag(getLocationOfByte(CS.getStart()),
1616 diag::warn_printf_conversion_argument_type_mismatch)
1617 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1618 << getSpecifierRange(startSpecifier, specifierLen)
1619 << Ex->getSourceRange();
1620 }
1621 }
1622
Ted Kremeneke0e53132010-01-28 23:39:18 +00001623 return true;
1624}
1625
Ted Kremenek826a3452010-07-16 02:11:22 +00001626//===--- CHECK: Scanf format string checking ------------------------------===//
1627
1628namespace {
1629class CheckScanfHandler : public CheckFormatHandler {
1630public:
1631 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1632 const Expr *origFormatExpr, unsigned firstDataArg,
1633 unsigned numDataArgs, bool isObjCLiteral,
1634 const char *beg, bool hasVAListArg,
1635 const CallExpr *theCall, unsigned formatIdx)
1636 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1637 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1638 theCall, formatIdx) {}
1639
1640 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1641 const char *startSpecifier,
1642 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001643
1644 bool HandleInvalidScanfConversionSpecifier(
1645 const analyze_scanf::ScanfSpecifier &FS,
1646 const char *startSpecifier,
1647 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001648
1649 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001650};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001651}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001652
Ted Kremenekb7c21012010-07-16 18:28:03 +00001653void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1654 const char *end) {
1655 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1656 << getSpecifierRange(start, end - start);
1657}
1658
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001659bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1660 const analyze_scanf::ScanfSpecifier &FS,
1661 const char *startSpecifier,
1662 unsigned specifierLen) {
1663
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001664 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001665 FS.getConversionSpecifier();
1666
1667 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1668 getLocationOfByte(CS.getStart()),
1669 startSpecifier, specifierLen,
1670 CS.getStart(), CS.getLength());
1671}
1672
Ted Kremenek826a3452010-07-16 02:11:22 +00001673bool CheckScanfHandler::HandleScanfSpecifier(
1674 const analyze_scanf::ScanfSpecifier &FS,
1675 const char *startSpecifier,
1676 unsigned specifierLen) {
1677
1678 using namespace analyze_scanf;
1679 using namespace analyze_format_string;
1680
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001681 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001682
Ted Kremenekbaa40062010-07-19 22:01:06 +00001683 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1684 // be used to decide if we are using positional arguments consistently.
1685 if (FS.consumesDataArgument()) {
1686 if (atFirstArg) {
1687 atFirstArg = false;
1688 usesPositionalArgs = FS.usesPositionalArg();
1689 }
1690 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1691 // Cannot mix-and-match positional and non-positional arguments.
1692 S.Diag(getLocationOfByte(CS.getStart()),
1693 diag::warn_format_mix_positional_nonpositional_args)
1694 << getSpecifierRange(startSpecifier, specifierLen);
1695 return false;
1696 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001697 }
1698
1699 // Check if the field with is non-zero.
1700 const OptionalAmount &Amt = FS.getFieldWidth();
1701 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1702 if (Amt.getConstantAmount() == 0) {
1703 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1704 Amt.getConstantLength());
1705 S.Diag(getLocationOfByte(Amt.getStart()),
1706 diag::warn_scanf_nonzero_width)
1707 << R << FixItHint::CreateRemoval(R);
1708 }
1709 }
1710
1711 if (!FS.consumesDataArgument()) {
1712 // FIXME: Technically specifying a precision or field width here
1713 // makes no sense. Worth issuing a warning at some point.
1714 return true;
1715 }
1716
1717 // Consume the argument.
1718 unsigned argIndex = FS.getArgIndex();
1719 if (argIndex < NumDataArgs) {
1720 // The check to see if the argIndex is valid will come later.
1721 // We set the bit here because we may exit early from this
1722 // function if we encounter some other error.
1723 CoveredArgs.set(argIndex);
1724 }
1725
Ted Kremenek1e51c202010-07-20 20:04:47 +00001726 // Check the length modifier is valid with the given conversion specifier.
1727 const LengthModifier &LM = FS.getLengthModifier();
1728 if (!FS.hasValidLengthModifier()) {
1729 S.Diag(getLocationOfByte(LM.getStart()),
1730 diag::warn_format_nonsensical_length)
1731 << LM.toString() << CS.toString()
1732 << getSpecifierRange(startSpecifier, specifierLen)
1733 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1734 LM.getLength()));
1735 }
1736
Ted Kremenek826a3452010-07-16 02:11:22 +00001737 // The remaining checks depend on the data arguments.
1738 if (HasVAListArg)
1739 return true;
1740
Ted Kremenek666a1972010-07-26 19:45:42 +00001741 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001742 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001743
1744 // FIXME: Check that the argument type matches the format specifier.
1745
1746 return true;
1747}
1748
1749void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001750 const Expr *OrigFormatExpr,
1751 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001752 unsigned format_idx, unsigned firstDataArg,
1753 bool isPrintf) {
1754
Ted Kremeneke0e53132010-01-28 23:39:18 +00001755 // CHECK: is the format string a wide literal?
1756 if (FExpr->isWide()) {
1757 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001758 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001759 << OrigFormatExpr->getSourceRange();
1760 return;
1761 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001762
Ted Kremeneke0e53132010-01-28 23:39:18 +00001763 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001764 llvm::StringRef StrRef = FExpr->getString();
1765 const char *Str = StrRef.data();
1766 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001767
Ted Kremeneke0e53132010-01-28 23:39:18 +00001768 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001769 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001770 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001771 << OrigFormatExpr->getSourceRange();
1772 return;
1773 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001774
1775 if (isPrintf) {
1776 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1777 TheCall->getNumArgs() - firstDataArg,
1778 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1779 HasVAListArg, TheCall, format_idx);
1780
1781 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1782 H.DoneProcessing();
1783 }
1784 else {
1785 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1786 TheCall->getNumArgs() - firstDataArg,
1787 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1788 HasVAListArg, TheCall, format_idx);
1789
1790 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1791 H.DoneProcessing();
1792 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001793}
1794
Ted Kremenek06de2762007-08-17 16:46:58 +00001795//===--- CHECK: Return Address of Stack Variable --------------------------===//
1796
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001797static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1798static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001799
1800/// CheckReturnStackAddr - Check if a return statement returns the address
1801/// of a stack variable.
1802void
1803Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1804 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001806 Expr *stackE = 0;
1807 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1808
1809 // Perform checking for returned stack addresses, local blocks,
1810 // label addresses or references to temporaries.
Steve Naroffdd972f22008-09-05 22:11:13 +00001811 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001812 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001813 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001814 stackE = EvalVal(RetValExp, refVars);
1815 }
1816
1817 if (stackE == 0)
1818 return; // Nothing suspicious was found.
1819
1820 SourceLocation diagLoc;
1821 SourceRange diagRange;
1822 if (refVars.empty()) {
1823 diagLoc = stackE->getLocStart();
1824 diagRange = stackE->getSourceRange();
1825 } else {
1826 // We followed through a reference variable. 'stackE' contains the
1827 // problematic expression but we will warn at the return statement pointing
1828 // at the reference variable. We will later display the "trail" of
1829 // reference variables using notes.
1830 diagLoc = refVars[0]->getLocStart();
1831 diagRange = refVars[0]->getSourceRange();
1832 }
1833
1834 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1835 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1836 : diag::warn_ret_stack_addr)
1837 << DR->getDecl()->getDeclName() << diagRange;
1838 } else if (isa<BlockExpr>(stackE)) { // local block.
1839 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1840 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1841 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1842 } else { // local temporary.
1843 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1844 : diag::warn_ret_local_temp_addr)
1845 << diagRange;
1846 }
1847
1848 // Display the "trail" of reference variables that we followed until we
1849 // found the problematic expression using notes.
1850 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1851 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1852 // If this var binds to another reference var, show the range of the next
1853 // var, otherwise the var binds to the problematic expression, in which case
1854 // show the range of the expression.
1855 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1856 : stackE->getSourceRange();
1857 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1858 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00001859 }
1860}
1861
1862/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1863/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001864/// to a location on the stack, a local block, an address of a label, or a
1865/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00001866/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001867/// encounter a subexpression that (1) clearly does not lead to one of the
1868/// above problematic expressions (2) is something we cannot determine leads to
1869/// a problematic expression based on such local checking.
1870///
1871/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1872/// the expression that they point to. Such variables are added to the
1873/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00001874///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001875/// EvalAddr processes expressions that are pointers that are used as
1876/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001877/// At the base case of the recursion is a check for the above problematic
1878/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00001879///
1880/// This implementation handles:
1881///
1882/// * pointer-to-pointer casts
1883/// * implicit conversions from array references to pointers
1884/// * taking the address of fields
1885/// * arbitrary interplay between "&" and "*" operators
1886/// * pointer arithmetic from an address of a stack variable
1887/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001888static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1889 if (E->isTypeDependent())
1890 return NULL;
1891
Ted Kremenek06de2762007-08-17 16:46:58 +00001892 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001893 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001894 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001895 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001896 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001897
Ted Kremenek06de2762007-08-17 16:46:58 +00001898 // Our "symbolic interpreter" is just a dispatch off the currently
1899 // viewed AST node. We then recursively traverse the AST by calling
1900 // EvalAddr and EvalVal appropriately.
1901 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001902 case Stmt::ParenExprClass:
1903 // Ignore parentheses.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001904 return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1905
1906 case Stmt::DeclRefExprClass: {
1907 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1908
1909 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1910 // If this is a reference variable, follow through to the expression that
1911 // it points to.
1912 if (V->hasLocalStorage() &&
1913 V->getType()->isReferenceType() && V->hasInit()) {
1914 // Add the reference variable to the "trail".
1915 refVars.push_back(DR);
1916 return EvalAddr(V->getInit(), refVars);
1917 }
1918
1919 return NULL;
1920 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001921
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001922 case Stmt::UnaryOperatorClass: {
1923 // The only unary operator that make sense to handle here
1924 // is AddrOf. All others don't make sense as pointers.
1925 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001926
John McCall2de56d12010-08-25 11:45:40 +00001927 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001928 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001929 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001930 return NULL;
1931 }
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001933 case Stmt::BinaryOperatorClass: {
1934 // Handle pointer arithmetic. All other binary operators are not valid
1935 // in this context.
1936 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001937 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001938
John McCall2de56d12010-08-25 11:45:40 +00001939 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001940 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001942 Expr *Base = B->getLHS();
1943
1944 // Determine which argument is the real pointer base. It could be
1945 // the RHS argument instead of the LHS.
1946 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001948 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001949 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001950 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001951
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001952 // For conditional operators we need to see if either the LHS or RHS are
1953 // valid DeclRefExpr*s. If one of them is valid, we return it.
1954 case Stmt::ConditionalOperatorClass: {
1955 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001957 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001958 if (Expr *lhsExpr = C->getLHS()) {
1959 // In C++, we can have a throw-expression, which has 'void' type.
1960 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001961 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001962 return LHS;
1963 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001964
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001965 // In C++, we can have a throw-expression, which has 'void' type.
1966 if (C->getRHS()->getType()->isVoidType())
1967 return NULL;
1968
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001969 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001970 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001971
1972 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00001973 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001974 return E; // local block.
1975 return NULL;
1976
1977 case Stmt::AddrLabelExprClass:
1978 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Ted Kremenek54b52742008-08-07 00:49:01 +00001980 // For casts, we need to handle conversions from arrays to
1981 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001982 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001983 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001984 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001985 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001986 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Steve Naroffdd972f22008-09-05 22:11:13 +00001988 if (SubExpr->getType()->isPointerType() ||
1989 SubExpr->getType()->isBlockPointerType() ||
1990 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001991 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00001992 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001993 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001994 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001995 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001996 }
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001998 // C++ casts. For dynamic casts, static casts, and const casts, we
1999 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002000 // through the cast. In the case the dynamic cast doesn't fail (and
2001 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002002 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002003 // FIXME: The comment about is wrong; we're not always converting
2004 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002005 // handle references to objects.
2006 case Stmt::CXXStaticCastExprClass:
2007 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002008 case Stmt::CXXConstCastExprClass:
2009 case Stmt::CXXReinterpretCastExprClass: {
2010 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002011 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002012 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002013 else
2014 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002015 }
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002017 // Everything else: we simply don't reason about them.
2018 default:
2019 return NULL;
2020 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002021}
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Ted Kremenek06de2762007-08-17 16:46:58 +00002023
2024/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2025/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002026static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002027do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002028 // We should only be called for evaluating non-pointer expressions, or
2029 // expressions with a pointer type that are not used as references but instead
2030 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Ted Kremenek06de2762007-08-17 16:46:58 +00002032 // Our "symbolic interpreter" is just a dispatch off the currently
2033 // viewed AST node. We then recursively traverse the AST by calling
2034 // EvalAddr and EvalVal appropriately.
2035 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002036 case Stmt::ImplicitCastExprClass: {
2037 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002038 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002039 E = IE->getSubExpr();
2040 continue;
2041 }
2042 return NULL;
2043 }
2044
Douglas Gregora2813ce2009-10-23 18:54:35 +00002045 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002046 // When we hit a DeclRefExpr we are looking at code that refers to a
2047 // variable's name. If it's not a reference variable we check if it has
2048 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002049 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Ted Kremenek06de2762007-08-17 16:46:58 +00002051 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002052 if (V->hasLocalStorage()) {
2053 if (!V->getType()->isReferenceType())
2054 return DR;
2055
2056 // Reference variable, follow through to the expression that
2057 // it points to.
2058 if (V->hasInit()) {
2059 // Add the reference variable to the "trail".
2060 refVars.push_back(DR);
2061 return EvalVal(V->getInit(), refVars);
2062 }
2063 }
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Ted Kremenek06de2762007-08-17 16:46:58 +00002065 return NULL;
2066 }
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Ted Kremenek68957a92010-08-04 20:01:07 +00002068 case Stmt::ParenExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002069 // Ignore parentheses.
Ted Kremenek68957a92010-08-04 20:01:07 +00002070 E = cast<ParenExpr>(E)->getSubExpr();
2071 continue;
2072 }
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Ted Kremenek06de2762007-08-17 16:46:58 +00002074 case Stmt::UnaryOperatorClass: {
2075 // The only unary operator that make sense to handle here
2076 // is Deref. All others don't resolve to a "name." This includes
2077 // handling all sorts of rvalues passed to a unary operator.
2078 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002079
John McCall2de56d12010-08-25 11:45:40 +00002080 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002081 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002082
2083 return NULL;
2084 }
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Ted Kremenek06de2762007-08-17 16:46:58 +00002086 case Stmt::ArraySubscriptExprClass: {
2087 // Array subscripts are potential references to data on the stack. We
2088 // retrieve the DeclRefExpr* for the array variable if it indeed
2089 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002090 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002091 }
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Ted Kremenek06de2762007-08-17 16:46:58 +00002093 case Stmt::ConditionalOperatorClass: {
2094 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002095 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002096 ConditionalOperator *C = cast<ConditionalOperator>(E);
2097
Anders Carlsson39073232007-11-30 19:04:31 +00002098 // Handle the GNU extension for missing LHS.
2099 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002100 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002101 return LHS;
2102
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002103 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Ted Kremenek06de2762007-08-17 16:46:58 +00002106 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002107 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002108 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Ted Kremenek06de2762007-08-17 16:46:58 +00002110 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002111 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002112 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002113
2114 // Check whether the member type is itself a reference, in which case
2115 // we're not going to refer to the member, but to what the member refers to.
2116 if (M->getMemberDecl()->getType()->isReferenceType())
2117 return NULL;
2118
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002119 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002120 }
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Ted Kremenek06de2762007-08-17 16:46:58 +00002122 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002123 // Check that we don't return or take the address of a reference to a
2124 // temporary. This is only useful in C++.
2125 if (!E->isTypeDependent() && E->isRValue())
2126 return E;
2127
2128 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002129 return NULL;
2130 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002131} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002132}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002133
2134//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2135
2136/// Check for comparisons of floating point operands using != and ==.
2137/// Issue a warning if these are no self-comparisons, as they are not likely
2138/// to do what the programmer intended.
2139void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2140 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002141
John McCallf6a16482010-12-04 03:47:34 +00002142 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2143 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002144
2145 // Special case: check for x == x (which is OK).
2146 // Do not emit warnings for such cases.
2147 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2148 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2149 if (DRL->getDecl() == DRR->getDecl())
2150 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002151
2152
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002153 // Special case: check for comparisons against literals that can be exactly
2154 // represented by APFloat. In such cases, do not emit a warning. This
2155 // is a heuristic: often comparison against such literals are used to
2156 // detect if a value in a variable has not changed. This clearly can
2157 // lead to false negatives.
2158 if (EmitWarning) {
2159 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2160 if (FLL->isExact())
2161 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002162 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002163 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2164 if (FLR->isExact())
2165 EmitWarning = false;
2166 }
2167 }
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002169 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002170 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002171 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002172 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002173 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Sebastian Redl0eb23302009-01-19 00:08:26 +00002175 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002176 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002177 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002178 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002180 // Emit the diagnostic.
2181 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002182 Diag(loc, diag::warn_floatingpoint_eq)
2183 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002184}
John McCallba26e582010-01-04 23:21:16 +00002185
John McCallf2370c92010-01-06 05:24:50 +00002186//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2187//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002188
John McCallf2370c92010-01-06 05:24:50 +00002189namespace {
John McCallba26e582010-01-04 23:21:16 +00002190
John McCallf2370c92010-01-06 05:24:50 +00002191/// Structure recording the 'active' range of an integer-valued
2192/// expression.
2193struct IntRange {
2194 /// The number of bits active in the int.
2195 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002196
John McCallf2370c92010-01-06 05:24:50 +00002197 /// True if the int is known not to have negative values.
2198 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002199
John McCallf2370c92010-01-06 05:24:50 +00002200 IntRange(unsigned Width, bool NonNegative)
2201 : Width(Width), NonNegative(NonNegative)
2202 {}
John McCallba26e582010-01-04 23:21:16 +00002203
John McCall1844a6e2010-11-10 23:38:19 +00002204 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002205 static IntRange forBoolType() {
2206 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002207 }
2208
John McCall1844a6e2010-11-10 23:38:19 +00002209 /// Returns the range of an opaque value of the given integral type.
2210 static IntRange forValueOfType(ASTContext &C, QualType T) {
2211 return forValueOfCanonicalType(C,
2212 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002213 }
2214
John McCall1844a6e2010-11-10 23:38:19 +00002215 /// Returns the range of an opaque value of a canonical integral type.
2216 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002217 assert(T->isCanonicalUnqualified());
2218
2219 if (const VectorType *VT = dyn_cast<VectorType>(T))
2220 T = VT->getElementType().getTypePtr();
2221 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2222 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002223
John McCall091f23f2010-11-09 22:22:12 +00002224 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002225 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2226 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002227 if (!Enum->isDefinition())
2228 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2229
John McCall323ed742010-05-06 08:58:33 +00002230 unsigned NumPositive = Enum->getNumPositiveBits();
2231 unsigned NumNegative = Enum->getNumNegativeBits();
2232
2233 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2234 }
John McCallf2370c92010-01-06 05:24:50 +00002235
2236 const BuiltinType *BT = cast<BuiltinType>(T);
2237 assert(BT->isInteger());
2238
2239 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2240 }
2241
John McCall1844a6e2010-11-10 23:38:19 +00002242 /// Returns the "target" range of a canonical integral type, i.e.
2243 /// the range of values expressible in the type.
2244 ///
2245 /// This matches forValueOfCanonicalType except that enums have the
2246 /// full range of their type, not the range of their enumerators.
2247 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2248 assert(T->isCanonicalUnqualified());
2249
2250 if (const VectorType *VT = dyn_cast<VectorType>(T))
2251 T = VT->getElementType().getTypePtr();
2252 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2253 T = CT->getElementType().getTypePtr();
2254 if (const EnumType *ET = dyn_cast<EnumType>(T))
2255 T = ET->getDecl()->getIntegerType().getTypePtr();
2256
2257 const BuiltinType *BT = cast<BuiltinType>(T);
2258 assert(BT->isInteger());
2259
2260 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2261 }
2262
2263 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002264 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002265 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002266 L.NonNegative && R.NonNegative);
2267 }
2268
John McCall1844a6e2010-11-10 23:38:19 +00002269 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002270 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002271 return IntRange(std::min(L.Width, R.Width),
2272 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002273 }
2274};
2275
2276IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2277 if (value.isSigned() && value.isNegative())
2278 return IntRange(value.getMinSignedBits(), false);
2279
2280 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002281 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002282
2283 // isNonNegative() just checks the sign bit without considering
2284 // signedness.
2285 return IntRange(value.getActiveBits(), true);
2286}
2287
John McCall0acc3112010-01-06 22:57:21 +00002288IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002289 unsigned MaxWidth) {
2290 if (result.isInt())
2291 return GetValueRange(C, result.getInt(), MaxWidth);
2292
2293 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002294 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2295 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2296 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2297 R = IntRange::join(R, El);
2298 }
John McCallf2370c92010-01-06 05:24:50 +00002299 return R;
2300 }
2301
2302 if (result.isComplexInt()) {
2303 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2304 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2305 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002306 }
2307
2308 // This can happen with lossless casts to intptr_t of "based" lvalues.
2309 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002310 // FIXME: The only reason we need to pass the type in here is to get
2311 // the sign right on this one case. It would be nice if APValue
2312 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002313 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002314 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002315}
John McCallf2370c92010-01-06 05:24:50 +00002316
2317/// Pseudo-evaluate the given integer expression, estimating the
2318/// range of values it might take.
2319///
2320/// \param MaxWidth - the width to which the value will be truncated
2321IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2322 E = E->IgnoreParens();
2323
2324 // Try a full evaluation first.
2325 Expr::EvalResult result;
2326 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002327 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002328
2329 // I think we only want to look through implicit casts here; if the
2330 // user has an explicit widening cast, we should treat the value as
2331 // being of the new, wider type.
2332 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002333 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002334 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2335
John McCall1844a6e2010-11-10 23:38:19 +00002336 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002337
John McCall2de56d12010-08-25 11:45:40 +00002338 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002339
John McCallf2370c92010-01-06 05:24:50 +00002340 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002341 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002342 return OutputTypeRange;
2343
2344 IntRange SubRange
2345 = GetExprRange(C, CE->getSubExpr(),
2346 std::min(MaxWidth, OutputTypeRange.Width));
2347
2348 // Bail out if the subexpr's range is as wide as the cast type.
2349 if (SubRange.Width >= OutputTypeRange.Width)
2350 return OutputTypeRange;
2351
2352 // Otherwise, we take the smaller width, and we're non-negative if
2353 // either the output type or the subexpr is.
2354 return IntRange(SubRange.Width,
2355 SubRange.NonNegative || OutputTypeRange.NonNegative);
2356 }
2357
2358 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2359 // If we can fold the condition, just take that operand.
2360 bool CondResult;
2361 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2362 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2363 : CO->getFalseExpr(),
2364 MaxWidth);
2365
2366 // Otherwise, conservatively merge.
2367 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2368 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2369 return IntRange::join(L, R);
2370 }
2371
2372 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2373 switch (BO->getOpcode()) {
2374
2375 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002376 case BO_LAnd:
2377 case BO_LOr:
2378 case BO_LT:
2379 case BO_GT:
2380 case BO_LE:
2381 case BO_GE:
2382 case BO_EQ:
2383 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002384 return IntRange::forBoolType();
2385
John McCallc0cd21d2010-02-23 19:22:29 +00002386 // The type of these compound assignments is the type of the LHS,
2387 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002388 case BO_MulAssign:
2389 case BO_DivAssign:
2390 case BO_RemAssign:
2391 case BO_AddAssign:
2392 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002393 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002394
John McCallf2370c92010-01-06 05:24:50 +00002395 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002396 case BO_PtrMemD:
2397 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002398 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002399
John McCall60fad452010-01-06 22:07:33 +00002400 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002401 case BO_And:
2402 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002403 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2404 GetExprRange(C, BO->getRHS(), MaxWidth));
2405
John McCallf2370c92010-01-06 05:24:50 +00002406 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002407 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002408 // ...except that we want to treat '1 << (blah)' as logically
2409 // positive. It's an important idiom.
2410 if (IntegerLiteral *I
2411 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2412 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002413 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002414 return IntRange(R.Width, /*NonNegative*/ true);
2415 }
2416 }
2417 // fallthrough
2418
John McCall2de56d12010-08-25 11:45:40 +00002419 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002420 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002421
John McCall60fad452010-01-06 22:07:33 +00002422 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002423 case BO_Shr:
2424 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002425 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2426
2427 // If the shift amount is a positive constant, drop the width by
2428 // that much.
2429 llvm::APSInt shift;
2430 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2431 shift.isNonNegative()) {
2432 unsigned zext = shift.getZExtValue();
2433 if (zext >= L.Width)
2434 L.Width = (L.NonNegative ? 0 : 1);
2435 else
2436 L.Width -= zext;
2437 }
2438
2439 return L;
2440 }
2441
2442 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002443 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002444 return GetExprRange(C, BO->getRHS(), MaxWidth);
2445
John McCall60fad452010-01-06 22:07:33 +00002446 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002447 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002448 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002449 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002450 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002451
John McCallf2370c92010-01-06 05:24:50 +00002452 default:
2453 break;
2454 }
2455
2456 // Treat every other operator as if it were closed on the
2457 // narrowest type that encompasses both operands.
2458 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2459 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2460 return IntRange::join(L, R);
2461 }
2462
2463 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2464 switch (UO->getOpcode()) {
2465 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002466 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002467 return IntRange::forBoolType();
2468
2469 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002470 case UO_Deref:
2471 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002472 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002473
2474 default:
2475 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2476 }
2477 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002478
2479 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002480 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002481 }
John McCallf2370c92010-01-06 05:24:50 +00002482
2483 FieldDecl *BitField = E->getBitField();
2484 if (BitField) {
2485 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2486 unsigned BitWidth = BitWidthAP.getZExtValue();
2487
2488 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2489 }
2490
John McCall1844a6e2010-11-10 23:38:19 +00002491 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002492}
John McCall51313c32010-01-04 23:31:57 +00002493
John McCall323ed742010-05-06 08:58:33 +00002494IntRange GetExprRange(ASTContext &C, Expr *E) {
2495 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2496}
2497
John McCall51313c32010-01-04 23:31:57 +00002498/// Checks whether the given value, which currently has the given
2499/// source semantics, has the same value when coerced through the
2500/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002501bool IsSameFloatAfterCast(const llvm::APFloat &value,
2502 const llvm::fltSemantics &Src,
2503 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002504 llvm::APFloat truncated = value;
2505
2506 bool ignored;
2507 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2508 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2509
2510 return truncated.bitwiseIsEqual(value);
2511}
2512
2513/// Checks whether the given value, which currently has the given
2514/// source semantics, has the same value when coerced through the
2515/// target semantics.
2516///
2517/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002518bool IsSameFloatAfterCast(const APValue &value,
2519 const llvm::fltSemantics &Src,
2520 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002521 if (value.isFloat())
2522 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2523
2524 if (value.isVector()) {
2525 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2526 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2527 return false;
2528 return true;
2529 }
2530
2531 assert(value.isComplexFloat());
2532 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2533 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2534}
2535
John McCallb4eb64d2010-10-08 02:01:28 +00002536void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002537
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002538static bool IsZero(Sema &S, Expr *E) {
2539 // Suppress cases where we are comparing against an enum constant.
2540 if (const DeclRefExpr *DR =
2541 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2542 if (isa<EnumConstantDecl>(DR->getDecl()))
2543 return false;
2544
2545 // Suppress cases where the '0' value is expanded from a macro.
2546 if (E->getLocStart().isMacroID())
2547 return false;
2548
John McCall323ed742010-05-06 08:58:33 +00002549 llvm::APSInt Value;
2550 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2551}
2552
John McCall372e1032010-10-06 00:25:24 +00002553static bool HasEnumType(Expr *E) {
2554 // Strip off implicit integral promotions.
2555 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002556 if (ICE->getCastKind() != CK_IntegralCast &&
2557 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002558 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002559 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002560 }
2561
2562 return E->getType()->isEnumeralType();
2563}
2564
John McCall323ed742010-05-06 08:58:33 +00002565void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002566 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002567 if (E->isValueDependent())
2568 return;
2569
John McCall2de56d12010-08-25 11:45:40 +00002570 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002571 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002572 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002573 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002574 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002575 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002576 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002577 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002578 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002579 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002580 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002581 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002582 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002583 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002584 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002585 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2586 }
2587}
2588
2589/// Analyze the operands of the given comparison. Implements the
2590/// fallback case from AnalyzeComparison.
2591void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002592 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2593 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002594}
John McCall51313c32010-01-04 23:31:57 +00002595
John McCallba26e582010-01-04 23:21:16 +00002596/// \brief Implements -Wsign-compare.
2597///
2598/// \param lex the left-hand expression
2599/// \param rex the right-hand expression
2600/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002601/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002602void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2603 // The type the comparison is being performed in.
2604 QualType T = E->getLHS()->getType();
2605 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2606 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002607
John McCall323ed742010-05-06 08:58:33 +00002608 // We don't do anything special if this isn't an unsigned integral
2609 // comparison: we're only interested in integral comparisons, and
2610 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002611 //
2612 // We also don't care about value-dependent expressions or expressions
2613 // whose result is a constant.
2614 if (!T->hasUnsignedIntegerRepresentation()
2615 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002616 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002617
John McCall323ed742010-05-06 08:58:33 +00002618 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2619 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002620
John McCall323ed742010-05-06 08:58:33 +00002621 // Check to see if one of the (unmodified) operands is of different
2622 // signedness.
2623 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002624 if (lex->getType()->hasSignedIntegerRepresentation()) {
2625 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002626 "unsigned comparison between two signed integer expressions?");
2627 signedOperand = lex;
2628 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002629 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002630 signedOperand = rex;
2631 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002632 } else {
John McCall323ed742010-05-06 08:58:33 +00002633 CheckTrivialUnsignedComparison(S, E);
2634 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002635 }
2636
John McCall323ed742010-05-06 08:58:33 +00002637 // Otherwise, calculate the effective range of the signed operand.
2638 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002639
John McCall323ed742010-05-06 08:58:33 +00002640 // Go ahead and analyze implicit conversions in the operands. Note
2641 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002642 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2643 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002644
John McCall323ed742010-05-06 08:58:33 +00002645 // If the signed range is non-negative, -Wsign-compare won't fire,
2646 // but we should still check for comparisons which are always true
2647 // or false.
2648 if (signedRange.NonNegative)
2649 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002650
2651 // For (in)equality comparisons, if the unsigned operand is a
2652 // constant which cannot collide with a overflowed signed operand,
2653 // then reinterpreting the signed operand as unsigned will not
2654 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002655 if (E->isEqualityOp()) {
2656 unsigned comparisonWidth = S.Context.getIntWidth(T);
2657 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002658
John McCall323ed742010-05-06 08:58:33 +00002659 // We should never be unable to prove that the unsigned operand is
2660 // non-negative.
2661 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2662
2663 if (unsignedRange.Width < comparisonWidth)
2664 return;
2665 }
2666
2667 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2668 << lex->getType() << rex->getType()
2669 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002670}
2671
John McCall15d7d122010-11-11 03:21:53 +00002672/// Analyzes an attempt to assign the given value to a bitfield.
2673///
2674/// Returns true if there was something fishy about the attempt.
2675bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2676 SourceLocation InitLoc) {
2677 assert(Bitfield->isBitField());
2678 if (Bitfield->isInvalidDecl())
2679 return false;
2680
John McCall91b60142010-11-11 05:33:51 +00002681 // White-list bool bitfields.
2682 if (Bitfield->getType()->isBooleanType())
2683 return false;
2684
Douglas Gregor46ff3032011-02-04 13:09:01 +00002685 // Ignore value- or type-dependent expressions.
2686 if (Bitfield->getBitWidth()->isValueDependent() ||
2687 Bitfield->getBitWidth()->isTypeDependent() ||
2688 Init->isValueDependent() ||
2689 Init->isTypeDependent())
2690 return false;
2691
John McCall15d7d122010-11-11 03:21:53 +00002692 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2693
2694 llvm::APSInt Width(32);
2695 Expr::EvalResult InitValue;
2696 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002697 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002698 !InitValue.Val.isInt())
2699 return false;
2700
2701 const llvm::APSInt &Value = InitValue.Val.getInt();
2702 unsigned OriginalWidth = Value.getBitWidth();
2703 unsigned FieldWidth = Width.getZExtValue();
2704
2705 if (OriginalWidth <= FieldWidth)
2706 return false;
2707
Jay Foad9f71a8f2010-12-07 08:25:34 +00002708 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002709
2710 // It's fairly common to write values into signed bitfields
2711 // that, if sign-extended, would end up becoming a different
2712 // value. We don't want to warn about that.
2713 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002714 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002715 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002716 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002717
2718 if (Value == TruncatedValue)
2719 return false;
2720
2721 std::string PrettyValue = Value.toString(10);
2722 std::string PrettyTrunc = TruncatedValue.toString(10);
2723
2724 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2725 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2726 << Init->getSourceRange();
2727
2728 return true;
2729}
2730
John McCallbeb22aa2010-11-09 23:24:47 +00002731/// Analyze the given simple or compound assignment for warning-worthy
2732/// operations.
2733void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2734 // Just recurse on the LHS.
2735 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2736
2737 // We want to recurse on the RHS as normal unless we're assigning to
2738 // a bitfield.
2739 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002740 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2741 E->getOperatorLoc())) {
2742 // Recurse, ignoring any implicit conversions on the RHS.
2743 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2744 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002745 }
2746 }
2747
2748 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2749}
2750
John McCall51313c32010-01-04 23:31:57 +00002751/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCallb4eb64d2010-10-08 02:01:28 +00002752void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2753 unsigned diag) {
2754 S.Diag(E->getExprLoc(), diag)
2755 << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
John McCall51313c32010-01-04 23:31:57 +00002756}
2757
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002758/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2759void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2760 SourceLocation CContext, unsigned diag) {
2761 S.Diag(E->getExprLoc(), diag)
2762 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2763}
2764
John McCall091f23f2010-11-09 22:22:12 +00002765std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2766 if (!Range.Width) return "0";
2767
2768 llvm::APSInt ValueInRange = Value;
2769 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002770 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002771 return ValueInRange.toString(10);
2772}
2773
Ted Kremenekef9ff882011-03-10 20:03:42 +00002774static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2775 SourceManager &smgr = S.Context.getSourceManager();
2776 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2777}
2778
John McCall323ed742010-05-06 08:58:33 +00002779void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002780 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002781 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002782
John McCall323ed742010-05-06 08:58:33 +00002783 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2784 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2785 if (Source == Target) return;
2786 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002787
Ted Kremenekef9ff882011-03-10 20:03:42 +00002788 // If the conversion context location is invalid don't complain.
2789 // We also don't want to emit a warning if the issue occurs from the
2790 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2791 // is slow, so we delay this check as long as possible. Once we detect
2792 // we are in that scenario, we just return.
2793 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00002794 return;
2795
John McCall51313c32010-01-04 23:31:57 +00002796 // Never diagnose implicit casts to bool.
2797 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2798 return;
2799
2800 // Strip vector types.
2801 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002802 if (!isa<VectorType>(Target)) {
2803 if (isFromSystemMacro(S, CC))
2804 return;
John McCallb4eb64d2010-10-08 02:01:28 +00002805 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002806 }
John McCall51313c32010-01-04 23:31:57 +00002807
2808 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2809 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2810 }
2811
2812 // Strip complex types.
2813 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002814 if (!isa<ComplexType>(Target)) {
2815 if (isFromSystemMacro(S, CC))
2816 return;
2817
John McCallb4eb64d2010-10-08 02:01:28 +00002818 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002819 }
John McCall51313c32010-01-04 23:31:57 +00002820
2821 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2822 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2823 }
2824
2825 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2826 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2827
2828 // If the source is floating point...
2829 if (SourceBT && SourceBT->isFloatingPoint()) {
2830 // ...and the target is floating point...
2831 if (TargetBT && TargetBT->isFloatingPoint()) {
2832 // ...then warn if we're dropping FP rank.
2833
2834 // Builtin FP kinds are ordered by increasing FP rank.
2835 if (SourceBT->getKind() > TargetBT->getKind()) {
2836 // Don't warn about float constants that are precisely
2837 // representable in the target type.
2838 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002839 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002840 // Value might be a float, a float vector, or a float complex.
2841 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002842 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2843 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002844 return;
2845 }
2846
Ted Kremenekef9ff882011-03-10 20:03:42 +00002847 if (isFromSystemMacro(S, CC))
2848 return;
2849
John McCallb4eb64d2010-10-08 02:01:28 +00002850 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002851 }
2852 return;
2853 }
2854
Ted Kremenekef9ff882011-03-10 20:03:42 +00002855 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00002856 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002857 if (isFromSystemMacro(S, CC))
2858 return;
2859
Chandler Carrutha5b93322011-02-17 11:05:49 +00002860 Expr *InnerE = E->IgnoreParenImpCasts();
2861 if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) {
2862 DiagnoseImpCast(S, LiteralExpr, T, CC,
2863 diag::warn_impcast_literal_float_to_integer);
2864 } else {
2865 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2866 }
2867 }
John McCall51313c32010-01-04 23:31:57 +00002868
2869 return;
2870 }
2871
John McCallf2370c92010-01-06 05:24:50 +00002872 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002873 return;
2874
John McCall323ed742010-05-06 08:58:33 +00002875 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002876 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002877
2878 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002879 // If the source is a constant, use a default-on diagnostic.
2880 // TODO: this should happen for bitfield stores, too.
2881 llvm::APSInt Value(32);
2882 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002883 if (isFromSystemMacro(S, CC))
2884 return;
2885
John McCall091f23f2010-11-09 22:22:12 +00002886 std::string PrettySourceValue = Value.toString(10);
2887 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2888
2889 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2890 << PrettySourceValue << PrettyTargetValue
2891 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2892 return;
2893 }
2894
John McCall51313c32010-01-04 23:31:57 +00002895 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2896 // and by god we'll let them.
Ted Kremenekef9ff882011-03-10 20:03:42 +00002897
2898 if (isFromSystemMacro(S, CC))
2899 return;
2900
John McCallf2370c92010-01-06 05:24:50 +00002901 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002902 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2903 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002904 }
2905
2906 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2907 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2908 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002909
2910 if (isFromSystemMacro(S, CC))
2911 return;
2912
John McCall323ed742010-05-06 08:58:33 +00002913 unsigned DiagID = diag::warn_impcast_integer_sign;
2914
2915 // Traditionally, gcc has warned about this under -Wsign-compare.
2916 // We also want to warn about it in -Wconversion.
2917 // So if -Wconversion is off, use a completely identical diagnostic
2918 // in the sign-compare group.
2919 // The conditional-checking code will
2920 if (ICContext) {
2921 DiagID = diag::warn_impcast_integer_sign_conditional;
2922 *ICContext = true;
2923 }
2924
John McCallb4eb64d2010-10-08 02:01:28 +00002925 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002926 }
2927
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002928 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002929 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
2930 // type, to give us better diagnostics.
2931 QualType SourceType = E->getType();
2932 if (!S.getLangOptions().CPlusPlus) {
2933 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2934 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2935 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
2936 SourceType = S.Context.getTypeDeclType(Enum);
2937 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
2938 }
2939 }
2940
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002941 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
2942 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
2943 if ((SourceEnum->getDecl()->getIdentifier() ||
2944 SourceEnum->getDecl()->getTypedefForAnonDecl()) &&
2945 (TargetEnum->getDecl()->getIdentifier() ||
2946 TargetEnum->getDecl()->getTypedefForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00002947 SourceEnum != TargetEnum) {
2948 if (isFromSystemMacro(S, CC))
2949 return;
2950
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002951 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002952 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002953 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002954
John McCall51313c32010-01-04 23:31:57 +00002955 return;
2956}
2957
John McCall323ed742010-05-06 08:58:33 +00002958void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2959
2960void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002961 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00002962 E = E->IgnoreParenImpCasts();
2963
2964 if (isa<ConditionalOperator>(E))
2965 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2966
John McCallb4eb64d2010-10-08 02:01:28 +00002967 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002968 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002969 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00002970 return;
2971}
2972
2973void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00002974 SourceLocation CC = E->getQuestionLoc();
2975
2976 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00002977
2978 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00002979 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2980 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002981
2982 // If -Wconversion would have warned about either of the candidates
2983 // for a signedness conversion to the context type...
2984 if (!Suspicious) return;
2985
2986 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002987 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
2988 CC))
John McCall323ed742010-05-06 08:58:33 +00002989 return;
2990
2991 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002992 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00002993 return;
2994
2995 // ...then check whether it would have warned about either of the
2996 // candidates for a signedness conversion to the condition type.
2997 if (E->getType() != T) {
2998 Suspicious = false;
2999 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003000 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003001 if (!Suspicious)
3002 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003003 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003004 if (!Suspicious)
3005 return;
3006 }
3007
3008 // If so, emit a diagnostic under -Wsign-compare.
3009 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3010 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3011 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3012 << lex->getType() << rex->getType()
3013 << lex->getSourceRange() << rex->getSourceRange();
3014}
3015
3016/// AnalyzeImplicitConversions - Find and report any interesting
3017/// implicit conversions in the given expression. There are a couple
3018/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003019void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003020 QualType T = OrigE->getType();
3021 Expr *E = OrigE->IgnoreParenImpCasts();
3022
3023 // For conditional operators, we analyze the arguments as if they
3024 // were being fed directly into the output.
3025 if (isa<ConditionalOperator>(E)) {
3026 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3027 CheckConditionalOperator(S, CO, T);
3028 return;
3029 }
3030
3031 // Go ahead and check any implicit conversions we might have skipped.
3032 // The non-canonical typecheck is just an optimization;
3033 // CheckImplicitConversion will filter out dead implicit conversions.
3034 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003035 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003036
3037 // Now continue drilling into this expression.
3038
3039 // Skip past explicit casts.
3040 if (isa<ExplicitCastExpr>(E)) {
3041 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003042 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003043 }
3044
John McCallbeb22aa2010-11-09 23:24:47 +00003045 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3046 // Do a somewhat different check with comparison operators.
3047 if (BO->isComparisonOp())
3048 return AnalyzeComparison(S, BO);
3049
3050 // And with assignments and compound assignments.
3051 if (BO->isAssignmentOp())
3052 return AnalyzeAssignment(S, BO);
3053 }
John McCall323ed742010-05-06 08:58:33 +00003054
3055 // These break the otherwise-useful invariant below. Fortunately,
3056 // we don't really need to recurse into them, because any internal
3057 // expressions should have been analyzed already when they were
3058 // built into statements.
3059 if (isa<StmtExpr>(E)) return;
3060
3061 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003062 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003063
3064 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003065 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003066 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003067 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003068}
3069
3070} // end anonymous namespace
3071
3072/// Diagnoses "dangerous" implicit conversions within the given
3073/// expression (which is a full expression). Implements -Wconversion
3074/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003075///
3076/// \param CC the "context" location of the implicit conversion, i.e.
3077/// the most location of the syntactic entity requiring the implicit
3078/// conversion
3079void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003080 // Don't diagnose in unevaluated contexts.
3081 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3082 return;
3083
3084 // Don't diagnose for value- or type-dependent expressions.
3085 if (E->isTypeDependent() || E->isValueDependent())
3086 return;
3087
John McCallb4eb64d2010-10-08 02:01:28 +00003088 // This is not the right CC for (e.g.) a variable initialization.
3089 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003090}
3091
John McCall15d7d122010-11-11 03:21:53 +00003092void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3093 FieldDecl *BitField,
3094 Expr *Init) {
3095 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3096}
3097
Mike Stumpf8c49212010-01-21 03:59:47 +00003098/// CheckParmsForFunctionDef - Check that the parameters of the given
3099/// function are appropriate for the definition of a function. This
3100/// takes care of any checks that cannot be performed on the
3101/// declaration itself, e.g., that the types of each of the function
3102/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003103bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3104 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003105 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003106 for (; P != PEnd; ++P) {
3107 ParmVarDecl *Param = *P;
3108
Mike Stumpf8c49212010-01-21 03:59:47 +00003109 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3110 // function declarator that is part of a function definition of
3111 // that function shall not have incomplete type.
3112 //
3113 // This is also C++ [dcl.fct]p6.
3114 if (!Param->isInvalidDecl() &&
3115 RequireCompleteType(Param->getLocation(), Param->getType(),
3116 diag::err_typecheck_decl_incomplete_type)) {
3117 Param->setInvalidDecl();
3118 HasInvalidParm = true;
3119 }
3120
3121 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3122 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003123 if (CheckParameterNames &&
3124 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003125 !Param->isImplicit() &&
3126 !getLangOptions().CPlusPlus)
3127 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003128
3129 // C99 6.7.5.3p12:
3130 // If the function declarator is not part of a definition of that
3131 // function, parameters may have incomplete type and may use the [*]
3132 // notation in their sequences of declarator specifiers to specify
3133 // variable length array types.
3134 QualType PType = Param->getOriginalType();
3135 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3136 if (AT->getSizeModifier() == ArrayType::Star) {
3137 // FIXME: This diagnosic should point the the '[*]' if source-location
3138 // information is added for it.
3139 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3140 }
3141 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003142 }
3143
3144 return HasInvalidParm;
3145}
John McCallb7f4ffe2010-08-12 21:44:57 +00003146
3147/// CheckCastAlign - Implements -Wcast-align, which warns when a
3148/// pointer cast increases the alignment requirements.
3149void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3150 // This is actually a lot of work to potentially be doing on every
3151 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003152 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3153 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003154 == Diagnostic::Ignored)
3155 return;
3156
3157 // Ignore dependent types.
3158 if (T->isDependentType() || Op->getType()->isDependentType())
3159 return;
3160
3161 // Require that the destination be a pointer type.
3162 const PointerType *DestPtr = T->getAs<PointerType>();
3163 if (!DestPtr) return;
3164
3165 // If the destination has alignment 1, we're done.
3166 QualType DestPointee = DestPtr->getPointeeType();
3167 if (DestPointee->isIncompleteType()) return;
3168 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3169 if (DestAlign.isOne()) return;
3170
3171 // Require that the source be a pointer type.
3172 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3173 if (!SrcPtr) return;
3174 QualType SrcPointee = SrcPtr->getPointeeType();
3175
3176 // Whitelist casts from cv void*. We already implicitly
3177 // whitelisted casts to cv void*, since they have alignment 1.
3178 // Also whitelist casts involving incomplete types, which implicitly
3179 // includes 'void'.
3180 if (SrcPointee->isIncompleteType()) return;
3181
3182 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3183 if (SrcAlign >= DestAlign) return;
3184
3185 Diag(TRange.getBegin(), diag::warn_cast_align)
3186 << Op->getType() << T
3187 << static_cast<unsigned>(SrcAlign.getQuantity())
3188 << static_cast<unsigned>(DestAlign.getQuantity())
3189 << TRange << Op->getSourceRange();
3190}
3191
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003192static void CheckArrayAccess_Check(Sema &S,
3193 const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003194 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003195 const ConstantArrayType *ArrayTy =
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003196 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003197 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003198 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003199
Chandler Carruth34064582011-02-17 20:55:08 +00003200 const Expr *IndexExpr = E->getIdx();
3201 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003202 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003203 llvm::APSInt index;
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003204 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003205 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003206
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003207 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003208 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003209 if (!size.isStrictlyPositive())
3210 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003211 if (size.getBitWidth() > index.getBitWidth())
3212 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003213 else if (size.getBitWidth() < index.getBitWidth())
3214 size = size.sext(index.getBitWidth());
3215
Chandler Carruth34064582011-02-17 20:55:08 +00003216 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003217 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003218
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003219 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3220 S.PDiag(diag::warn_array_index_exceeds_bounds)
3221 << index.toString(10, true)
3222 << size.toString(10, true)
3223 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003224 } else {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003225 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3226 S.PDiag(diag::warn_array_index_precedes_bounds)
3227 << index.toString(10, true)
3228 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003229 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003230
3231 const NamedDecl *ND = NULL;
3232 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3233 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3234 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3235 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3236 if (ND)
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003237 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3238 S.PDiag(diag::note_array_index_out_of_bounds)
3239 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003240}
3241
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003242void Sema::CheckArrayAccess(const Expr *expr) {
3243 while (true)
3244 switch (expr->getStmtClass()) {
3245 case Stmt::ParenExprClass:
3246 expr = cast<ParenExpr>(expr)->getSubExpr();
3247 continue;
3248 case Stmt::ArraySubscriptExprClass:
3249 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3250 return;
3251 case Stmt::ConditionalOperatorClass: {
3252 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3253 if (const Expr *lhs = cond->getLHS())
3254 CheckArrayAccess(lhs);
3255 if (const Expr *rhs = cond->getRHS())
3256 CheckArrayAccess(rhs);
3257 return;
3258 }
3259 default:
3260 return;
3261 }
3262}