blob: f4968f697a05f99f661dc60e97d0bc6eb16f6422 [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
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000035#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000036#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000037#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000038#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000041
Chris Lattner60800082009-02-18 17:49:48 +000042SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000044 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000046}
Chris Lattner08f92e32010-11-17 07:37:15 +000047
Chris Lattner60800082009-02-18 17:49:48 +000048
Ryan Flynn4403a5e2009-08-06 03:00:50 +000049/// CheckablePrintfAttr - does a function call have a "printf" attribute
50/// and arguments that merit checking?
51bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52 if (Format->getType() == "printf") return true;
53 if (Format->getType() == "printf0") {
54 // printf0 allows null "format" string; if so don't check format/args
55 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000056 // Does the index refer to the implicit object argument?
57 if (isa<CXXMemberCallExpr>(TheCall)) {
58 if (format_idx == 0)
59 return false;
60 --format_idx;
61 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000062 if (format_idx < TheCall->getNumArgs()) {
63 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000064 if (!Format->isNullPointerConstant(Context,
65 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000066 return true;
67 }
68 }
69 return false;
70}
Chris Lattner60800082009-02-18 17:49:48 +000071
John McCall8e10f3b2011-02-26 05:39:39 +000072/// Checks that a call expression's argument count is the desired number.
73/// This is useful when doing custom type-checking. Returns true on error.
74static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75 unsigned argCount = call->getNumArgs();
76 if (argCount == desiredArgCount) return false;
77
78 if (argCount < desiredArgCount)
79 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80 << 0 /*function call*/ << desiredArgCount << argCount
81 << call->getSourceRange();
82
83 // Highlight all the excess arguments.
84 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85 call->getArg(argCount - 1)->getLocEnd());
86
87 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88 << 0 /*function call*/ << desiredArgCount << argCount
89 << call->getArg(1)->getSourceRange();
90}
91
Julien Lerouge77f68bb2011-09-09 22:41:49 +000092/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93/// annotation is a non wide string literal.
94static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95 Arg = Arg->IgnoreParenCasts();
96 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97 if (!Literal || !Literal->isAscii()) {
98 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99 << Arg->getSourceRange();
100 return true;
101 }
102 return false;
103}
104
John McCall60d7b3a2010-08-24 06:29:42 +0000105ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000106Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000107 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000108
Chris Lattner946928f2010-10-01 23:23:24 +0000109 // Find out if any arguments are required to be integer constant expressions.
110 unsigned ICEArguments = 0;
111 ASTContext::GetBuiltinTypeError Error;
112 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113 if (Error != ASTContext::GE_None)
114 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
115
116 // If any arguments are required to be ICE's, check and diagnose.
117 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118 // Skip arguments not required to be ICE's.
119 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120
121 llvm::APSInt Result;
122 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123 return true;
124 ICEArguments &= ~(1 << ArgNo);
125 }
126
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000129 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000130 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000131 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000134 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000135 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinVAStart(TheCall))
137 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000138 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 case Builtin::BI__builtin_isgreater:
140 case Builtin::BI__builtin_isgreaterequal:
141 case Builtin::BI__builtin_isless:
142 case Builtin::BI__builtin_islessequal:
143 case Builtin::BI__builtin_islessgreater:
144 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinUnorderedCompare(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000148 case Builtin::BI__builtin_fpclassify:
149 if (SemaBuiltinFPClassification(TheCall, 6))
150 return ExprError();
151 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 case Builtin::BI__builtin_isfinite:
153 case Builtin::BI__builtin_isinf:
154 case Builtin::BI__builtin_isinf_sign:
155 case Builtin::BI__builtin_isnan:
156 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000157 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000158 return ExprError();
159 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000160 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161 return SemaBuiltinShuffleVector(TheCall);
162 // TheCall will be freed by the smart pointer here, but that's fine, since
163 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000164 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000165 if (SemaBuiltinPrefetch(TheCall))
166 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000167 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000168 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000169 if (SemaBuiltinObjectSize(TheCall))
170 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000171 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000172 case Builtin::BI__builtin_longjmp:
173 if (SemaBuiltinLongjmp(TheCall))
174 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000175 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000176
177 case Builtin::BI__builtin_classify_type:
178 if (checkArgCount(*this, TheCall, 1)) return true;
179 TheCall->setType(Context.IntTy);
180 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000181 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000182 if (checkArgCount(*this, TheCall, 1)) return true;
183 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000184 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_add:
186 case Builtin::BI__sync_fetch_and_sub:
187 case Builtin::BI__sync_fetch_and_or:
188 case Builtin::BI__sync_fetch_and_and:
189 case Builtin::BI__sync_fetch_and_xor:
190 case Builtin::BI__sync_add_and_fetch:
191 case Builtin::BI__sync_sub_and_fetch:
192 case Builtin::BI__sync_and_and_fetch:
193 case Builtin::BI__sync_or_and_fetch:
194 case Builtin::BI__sync_xor_and_fetch:
195 case Builtin::BI__sync_val_compare_and_swap:
196 case Builtin::BI__sync_bool_compare_and_swap:
197 case Builtin::BI__sync_lock_test_and_set:
198 case Builtin::BI__sync_lock_release:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000199 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000200 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000201 case Builtin::BI__atomic_load:
202 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
203 case Builtin::BI__atomic_store:
204 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
205 case Builtin::BI__atomic_exchange:
206 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
207 case Builtin::BI__atomic_compare_exchange_strong:
208 return SemaAtomicOpsOverloaded(move(TheCallResult),
209 AtomicExpr::CmpXchgStrong);
210 case Builtin::BI__atomic_compare_exchange_weak:
211 return SemaAtomicOpsOverloaded(move(TheCallResult),
212 AtomicExpr::CmpXchgWeak);
213 case Builtin::BI__atomic_fetch_add:
214 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
215 case Builtin::BI__atomic_fetch_sub:
216 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
217 case Builtin::BI__atomic_fetch_and:
218 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
219 case Builtin::BI__atomic_fetch_or:
220 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
221 case Builtin::BI__atomic_fetch_xor:
222 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000223 case Builtin::BI__builtin_annotation:
224 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
225 return ExprError();
226 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000227 }
228
229 // Since the target specific builtins for each arch overlap, only check those
230 // of the arch we are compiling for.
231 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000232 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000233 case llvm::Triple::arm:
234 case llvm::Triple::thumb:
235 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
236 return ExprError();
237 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000238 default:
239 break;
240 }
241 }
242
243 return move(TheCallResult);
244}
245
Nate Begeman61eecf52010-06-14 05:21:25 +0000246// Get the valid immediate range for the specified NEON type code.
247static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000248 NeonTypeFlags Type(t);
249 int IsQuad = Type.isQuad();
250 switch (Type.getEltType()) {
251 case NeonTypeFlags::Int8:
252 case NeonTypeFlags::Poly8:
253 return shift ? 7 : (8 << IsQuad) - 1;
254 case NeonTypeFlags::Int16:
255 case NeonTypeFlags::Poly16:
256 return shift ? 15 : (4 << IsQuad) - 1;
257 case NeonTypeFlags::Int32:
258 return shift ? 31 : (2 << IsQuad) - 1;
259 case NeonTypeFlags::Int64:
260 return shift ? 63 : (1 << IsQuad) - 1;
261 case NeonTypeFlags::Float16:
262 assert(!shift && "cannot shift float types!");
263 return (4 << IsQuad) - 1;
264 case NeonTypeFlags::Float32:
265 assert(!shift && "cannot shift float types!");
266 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000267 }
268 return 0;
269}
270
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000271/// getNeonEltType - Return the QualType corresponding to the elements of
272/// the vector type specified by the NeonTypeFlags. This is used to check
273/// the pointer arguments for Neon load/store intrinsics.
274static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
275 switch (Flags.getEltType()) {
276 case NeonTypeFlags::Int8:
277 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
278 case NeonTypeFlags::Int16:
279 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
280 case NeonTypeFlags::Int32:
281 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
282 case NeonTypeFlags::Int64:
283 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
284 case NeonTypeFlags::Poly8:
285 return Context.SignedCharTy;
286 case NeonTypeFlags::Poly16:
287 return Context.ShortTy;
288 case NeonTypeFlags::Float16:
289 return Context.UnsignedShortTy;
290 case NeonTypeFlags::Float32:
291 return Context.FloatTy;
292 }
293 return QualType();
294}
295
Nate Begeman26a31422010-06-08 02:47:44 +0000296bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000297 llvm::APSInt Result;
298
Nate Begeman0d15c532010-06-13 04:47:52 +0000299 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000300 unsigned TV = 0;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000301 bool HasPtr = false;
302 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000303 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000304#define GET_NEON_OVERLOAD_CHECK
305#include "clang/Basic/arm_neon.inc"
306#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000307 }
308
Nate Begeman0d15c532010-06-13 04:47:52 +0000309 // For NEON intrinsics which are overloaded on vector element type, validate
310 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000311 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000312 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000313 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000314 return true;
315
Bob Wilsonda95f732011-11-08 01:16:11 +0000316 TV = Result.getLimitedValue(64);
317 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000318 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000319 << TheCall->getArg(ImmArg)->getSourceRange();
320 }
321
322 if (HasPtr || HasConstPtr) {
323 // Check that pointer arguments have the specified type.
324 for (unsigned ArgNo = 0; ArgNo < ImmArg; ++ArgNo) {
325 Expr *Arg = TheCall->getArg(ArgNo);
326 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
327 Arg = ICE->getSubExpr();
328 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
329 QualType RHSTy = RHS.get()->getType();
330 if (!RHSTy->isPointerType())
331 continue;
332 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
333 if (HasConstPtr)
334 EltTy = EltTy.withConst();
335 QualType LHSTy = Context.getPointerType(EltTy);
336 AssignConvertType ConvTy;
337 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
338 if (RHS.isInvalid())
339 return true;
340 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
341 RHS.get(), AA_Assigning))
342 return true;
343 }
Nate Begeman0d15c532010-06-13 04:47:52 +0000344 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000345
Nate Begeman0d15c532010-06-13 04:47:52 +0000346 // For NEON intrinsics which take an immediate value as part of the
347 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000348 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000349 switch (BuiltinID) {
350 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000351 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
352 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000353 case ARM::BI__builtin_arm_vcvtr_f:
354 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000355#define GET_NEON_IMMEDIATE_CHECK
356#include "clang/Basic/arm_neon.inc"
357#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000358 };
359
Nate Begeman61eecf52010-06-14 05:21:25 +0000360 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000361 if (SemaBuiltinConstantArg(TheCall, i, Result))
362 return true;
363
Nate Begeman61eecf52010-06-14 05:21:25 +0000364 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000365 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000366 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000367 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000368 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000369
Nate Begeman99c40bb2010-08-03 21:32:34 +0000370 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000371 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000372}
Daniel Dunbarde454282008-10-02 18:44:07 +0000373
Anders Carlssond406bf02009-08-16 01:56:34 +0000374/// CheckFunctionCall - Check a direct function call for various correctness
375/// and safety properties not strictly enforced by the C type system.
376bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
377 // Get the IdentifierInfo* for the called function.
378 IdentifierInfo *FnInfo = FDecl->getIdentifier();
379
380 // None of the checks below are needed for functions that don't have
381 // simple names (e.g., C++ conversion functions).
382 if (!FnInfo)
383 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Daniel Dunbarde454282008-10-02 18:44:07 +0000385 // FIXME: This mechanism should be abstracted to be less fragile and
386 // more efficient. For example, just map function ids to custom
387 // handlers.
388
Ted Kremenekc82faca2010-09-09 04:33:05 +0000389 // Printf and scanf checking.
390 for (specific_attr_iterator<FormatAttr>
391 i = FDecl->specific_attr_begin<FormatAttr>(),
392 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
393
394 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000395 const bool b = Format->getType() == "scanf";
396 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000397 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000398 CheckPrintfScanfArguments(TheCall, HasVAListArg,
399 Format->getFormatIdx() - 1,
400 HasVAListArg ? 0 : Format->getFirstArg() - 1,
401 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000402 }
Chris Lattner59907c42007-08-10 20:18:51 +0000403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Ted Kremenekc82faca2010-09-09 04:33:05 +0000405 for (specific_attr_iterator<NonNullAttr>
406 i = FDecl->specific_attr_begin<NonNullAttr>(),
407 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000408 CheckNonNullArguments(*i, TheCall->getArgs(),
409 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000410 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000411
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000412 // Builtin handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000413 int CMF = -1;
414 switch (FDecl->getBuiltinID()) {
415 case Builtin::BI__builtin_memset:
416 case Builtin::BI__builtin___memset_chk:
417 case Builtin::BImemset:
418 CMF = CMF_Memset;
419 break;
420
421 case Builtin::BI__builtin_memcpy:
422 case Builtin::BI__builtin___memcpy_chk:
423 case Builtin::BImemcpy:
424 CMF = CMF_Memcpy;
425 break;
426
427 case Builtin::BI__builtin_memmove:
428 case Builtin::BI__builtin___memmove_chk:
429 case Builtin::BImemmove:
430 CMF = CMF_Memmove;
431 break;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000432
433 case Builtin::BIstrlcpy:
434 case Builtin::BIstrlcat:
435 CheckStrlcpycatArguments(TheCall, FnInfo);
436 break;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000437
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000438 case Builtin::BI__builtin_memcmp:
439 CMF = CMF_Memcmp;
440 break;
441
Nico Webercda57822011-10-13 22:30:23 +0000442 case Builtin::BI__builtin_strncpy:
443 case Builtin::BI__builtin___strncpy_chk:
444 case Builtin::BIstrncpy:
445 CMF = CMF_Strncpy;
446 break;
447
448 case Builtin::BI__builtin_strncmp:
449 CMF = CMF_Strncmp;
450 break;
451
452 case Builtin::BI__builtin_strncasecmp:
453 CMF = CMF_Strncasecmp;
454 break;
455
456 case Builtin::BI__builtin_strncat:
457 case Builtin::BIstrncat:
458 CMF = CMF_Strncat;
459 break;
460
461 case Builtin::BI__builtin_strndup:
462 case Builtin::BIstrndup:
463 CMF = CMF_Strndup;
464 break;
465
Douglas Gregor707a23e2011-06-16 17:56:04 +0000466 default:
467 if (FDecl->getLinkage() == ExternalLinkage &&
468 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
469 if (FnInfo->isStr("memset"))
470 CMF = CMF_Memset;
471 else if (FnInfo->isStr("memcpy"))
472 CMF = CMF_Memcpy;
473 else if (FnInfo->isStr("memmove"))
474 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000475 else if (FnInfo->isStr("memcmp"))
476 CMF = CMF_Memcmp;
Nico Webercda57822011-10-13 22:30:23 +0000477 else if (FnInfo->isStr("strncpy"))
478 CMF = CMF_Strncpy;
479 else if (FnInfo->isStr("strncmp"))
480 CMF = CMF_Strncmp;
481 else if (FnInfo->isStr("strncasecmp"))
482 CMF = CMF_Strncasecmp;
483 else if (FnInfo->isStr("strncat"))
484 CMF = CMF_Strncat;
485 else if (FnInfo->isStr("strndup"))
486 CMF = CMF_Strndup;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000487 }
488 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000489 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000490
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000491 // Memset/memcpy/memmove handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000492 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000493 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000494
Anders Carlssond406bf02009-08-16 01:56:34 +0000495 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000496}
497
Anders Carlssond406bf02009-08-16 01:56:34 +0000498bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000499 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000500 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000501 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000502 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000504 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
505 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000506 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000508 QualType Ty = V->getType();
509 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000510 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Ted Kremenek826a3452010-07-16 02:11:22 +0000512 const bool b = Format->getType() == "scanf";
513 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000514 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Anders Carlssond406bf02009-08-16 01:56:34 +0000516 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000517 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
518 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000519
520 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000521}
522
Eli Friedman276b0612011-10-11 02:20:01 +0000523ExprResult
524Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
525 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
526 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000527
528 // All these operations take one of the following four forms:
529 // T __atomic_load(_Atomic(T)*, int) (loads)
530 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
531 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
532 // (cmpxchg)
533 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
534 // where T is an appropriate type, and the int paremeterss are for orderings.
535 unsigned NumVals = 1;
536 unsigned NumOrders = 1;
537 if (Op == AtomicExpr::Load) {
538 NumVals = 0;
539 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
540 NumVals = 2;
541 NumOrders = 2;
542 }
543
544 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
545 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
546 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
547 << TheCall->getCallee()->getSourceRange();
548 return ExprError();
549 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
550 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
551 diag::err_typecheck_call_too_many_args)
552 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
553 << TheCall->getCallee()->getSourceRange();
554 return ExprError();
555 }
556
557 // Inspect the first argument of the atomic operation. This should always be
558 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000559 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000560 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
561 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
562 if (!pointerType) {
563 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
564 << Ptr->getType() << Ptr->getSourceRange();
565 return ExprError();
566 }
567
568 QualType AtomTy = pointerType->getPointeeType();
569 if (!AtomTy->isAtomicType()) {
570 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
571 << Ptr->getType() << Ptr->getSourceRange();
572 return ExprError();
573 }
574 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
575
576 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
577 !ValType->isIntegerType() && !ValType->isPointerType()) {
578 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
579 << Ptr->getType() << Ptr->getSourceRange();
580 return ExprError();
581 }
582
583 if (!ValType->isIntegerType() &&
584 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
585 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
586 << Ptr->getType() << Ptr->getSourceRange();
587 return ExprError();
588 }
589
590 switch (ValType.getObjCLifetime()) {
591 case Qualifiers::OCL_None:
592 case Qualifiers::OCL_ExplicitNone:
593 // okay
594 break;
595
596 case Qualifiers::OCL_Weak:
597 case Qualifiers::OCL_Strong:
598 case Qualifiers::OCL_Autoreleasing:
599 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
600 << ValType << Ptr->getSourceRange();
601 return ExprError();
602 }
603
604 QualType ResultType = ValType;
605 if (Op == AtomicExpr::Store)
606 ResultType = Context.VoidTy;
607 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
608 ResultType = Context.BoolTy;
609
610 // The first argument --- the pointer --- has a fixed type; we
611 // deduce the types of the rest of the arguments accordingly. Walk
612 // the remaining arguments, converting them to the deduced value type.
613 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
614 ExprResult Arg = TheCall->getArg(i);
615 QualType Ty;
616 if (i < NumVals+1) {
617 // The second argument to a cmpxchg is a pointer to the data which will
618 // be exchanged. The second argument to a pointer add/subtract is the
619 // amount to add/subtract, which must be a ptrdiff_t. The third
620 // argument to a cmpxchg and the second argument in all other cases
621 // is the type of the value.
622 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
623 Op == AtomicExpr::CmpXchgStrong))
624 Ty = Context.getPointerType(ValType.getUnqualifiedType());
625 else if (!ValType->isIntegerType() &&
626 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
627 Ty = Context.getPointerDiffType();
628 else
629 Ty = ValType;
630 } else {
631 // The order(s) are always converted to int.
632 Ty = Context.IntTy;
633 }
634 InitializedEntity Entity =
635 InitializedEntity::InitializeParameter(Context, Ty, false);
636 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
637 if (Arg.isInvalid())
638 return true;
639 TheCall->setArg(i, Arg.get());
640 }
641
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000642 SmallVector<Expr*, 5> SubExprs;
643 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000644 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000645 SubExprs.push_back(TheCall->getArg(1)); // Order
Eli Friedman276b0612011-10-11 02:20:01 +0000646 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000647 SubExprs.push_back(TheCall->getArg(2)); // Order
648 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000649 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000650 SubExprs.push_back(TheCall->getArg(3)); // Order
651 SubExprs.push_back(TheCall->getArg(1)); // Val1
652 SubExprs.push_back(TheCall->getArg(2)); // Val2
653 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000654 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000655
656 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
657 SubExprs.data(), SubExprs.size(),
658 ResultType, Op,
659 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000660}
661
662
John McCall5f8d6042011-08-27 01:09:30 +0000663/// checkBuiltinArgument - Given a call to a builtin function, perform
664/// normal type-checking on the given argument, updating the call in
665/// place. This is useful when a builtin function requires custom
666/// type-checking for some of its arguments but not necessarily all of
667/// them.
668///
669/// Returns true on error.
670static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
671 FunctionDecl *Fn = E->getDirectCallee();
672 assert(Fn && "builtin call without direct callee!");
673
674 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
675 InitializedEntity Entity =
676 InitializedEntity::InitializeParameter(S.Context, Param);
677
678 ExprResult Arg = E->getArg(0);
679 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
680 if (Arg.isInvalid())
681 return true;
682
683 E->setArg(ArgIndex, Arg.take());
684 return false;
685}
686
Chris Lattner5caa3702009-05-08 06:58:22 +0000687/// SemaBuiltinAtomicOverloaded - We have a call to a function like
688/// __sync_fetch_and_add, which is an overloaded function based on the pointer
689/// type of its first argument. The main ActOnCallExpr routines have already
690/// promoted the types of arguments because all of these calls are prototyped as
691/// void(...).
692///
693/// This function goes through and does final semantic checking for these
694/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000695ExprResult
696Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000697 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000698 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
699 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
700
701 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000702 if (TheCall->getNumArgs() < 1) {
703 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
704 << 0 << 1 << TheCall->getNumArgs()
705 << TheCall->getCallee()->getSourceRange();
706 return ExprError();
707 }
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattner5caa3702009-05-08 06:58:22 +0000709 // Inspect the first argument of the atomic builtin. This should always be
710 // a pointer type, whose element is an integral scalar or pointer type.
711 // Because it is a pointer type, we don't have to worry about any implicit
712 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000713 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000714 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000715 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
716 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000717 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
718 << FirstArg->getType() << FirstArg->getSourceRange();
719 return ExprError();
720 }
Mike Stump1eb44332009-09-09 15:08:12 +0000721
John McCallf85e1932011-06-15 23:02:42 +0000722 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000723 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000724 !ValType->isBlockPointerType()) {
725 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
726 << FirstArg->getType() << FirstArg->getSourceRange();
727 return ExprError();
728 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000729
John McCallf85e1932011-06-15 23:02:42 +0000730 switch (ValType.getObjCLifetime()) {
731 case Qualifiers::OCL_None:
732 case Qualifiers::OCL_ExplicitNone:
733 // okay
734 break;
735
736 case Qualifiers::OCL_Weak:
737 case Qualifiers::OCL_Strong:
738 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000739 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000740 << ValType << FirstArg->getSourceRange();
741 return ExprError();
742 }
743
John McCallb45ae252011-10-05 07:41:44 +0000744 // Strip any qualifiers off ValType.
745 ValType = ValType.getUnqualifiedType();
746
Chandler Carruth8d13d222010-07-18 20:54:12 +0000747 // The majority of builtins return a value, but a few have special return
748 // types, so allow them to override appropriately below.
749 QualType ResultType = ValType;
750
Chris Lattner5caa3702009-05-08 06:58:22 +0000751 // We need to figure out which concrete builtin this maps onto. For example,
752 // __sync_fetch_and_add with a 2 byte object turns into
753 // __sync_fetch_and_add_2.
754#define BUILTIN_ROW(x) \
755 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
756 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Chris Lattner5caa3702009-05-08 06:58:22 +0000758 static const unsigned BuiltinIndices[][5] = {
759 BUILTIN_ROW(__sync_fetch_and_add),
760 BUILTIN_ROW(__sync_fetch_and_sub),
761 BUILTIN_ROW(__sync_fetch_and_or),
762 BUILTIN_ROW(__sync_fetch_and_and),
763 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Chris Lattner5caa3702009-05-08 06:58:22 +0000765 BUILTIN_ROW(__sync_add_and_fetch),
766 BUILTIN_ROW(__sync_sub_and_fetch),
767 BUILTIN_ROW(__sync_and_and_fetch),
768 BUILTIN_ROW(__sync_or_and_fetch),
769 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Chris Lattner5caa3702009-05-08 06:58:22 +0000771 BUILTIN_ROW(__sync_val_compare_and_swap),
772 BUILTIN_ROW(__sync_bool_compare_and_swap),
773 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000774 BUILTIN_ROW(__sync_lock_release),
775 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000776 };
Mike Stump1eb44332009-09-09 15:08:12 +0000777#undef BUILTIN_ROW
778
Chris Lattner5caa3702009-05-08 06:58:22 +0000779 // Determine the index of the size.
780 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000781 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000782 case 1: SizeIndex = 0; break;
783 case 2: SizeIndex = 1; break;
784 case 4: SizeIndex = 2; break;
785 case 8: SizeIndex = 3; break;
786 case 16: SizeIndex = 4; break;
787 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000788 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
789 << FirstArg->getType() << FirstArg->getSourceRange();
790 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000791 }
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Chris Lattner5caa3702009-05-08 06:58:22 +0000793 // Each of these builtins has one pointer argument, followed by some number of
794 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
795 // that we ignore. Find out which row of BuiltinIndices to read from as well
796 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000797 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000798 unsigned BuiltinIndex, NumFixed = 1;
799 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000800 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Chris Lattner5caa3702009-05-08 06:58:22 +0000801 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
802 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
803 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
804 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
805 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000807 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
808 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
809 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
810 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
811 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Chris Lattner5caa3702009-05-08 06:58:22 +0000813 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000814 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000815 NumFixed = 2;
816 break;
817 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000818 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000819 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000820 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000821 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000822 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000823 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000824 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000825 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000826 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000827 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000828 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000829 }
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Chris Lattner5caa3702009-05-08 06:58:22 +0000831 // Now that we know how many fixed arguments we expect, first check that we
832 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000833 if (TheCall->getNumArgs() < 1+NumFixed) {
834 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
835 << 0 << 1+NumFixed << TheCall->getNumArgs()
836 << TheCall->getCallee()->getSourceRange();
837 return ExprError();
838 }
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000840 // Get the decl for the concrete builtin from this, we can tell what the
841 // concrete integer type we should convert to is.
842 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
843 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
844 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000845 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000846 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
847 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000848
John McCallf871d0c2010-08-07 06:22:56 +0000849 // The first argument --- the pointer --- has a fixed type; we
850 // deduce the types of the rest of the arguments accordingly. Walk
851 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000852 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000853 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Chris Lattner5caa3702009-05-08 06:58:22 +0000855 // GCC does an implicit conversion to the pointer or integer ValType. This
856 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000857 // Initialize the argument.
858 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
859 ValType, /*consume*/ false);
860 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000861 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000862 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Chris Lattner5caa3702009-05-08 06:58:22 +0000864 // Okay, we have something that *can* be converted to the right type. Check
865 // to see if there is a potentially weird extension going on here. This can
866 // happen when you do an atomic operation on something like an char* and
867 // pass in 42. The 42 gets converted to char. This is even more strange
868 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000869 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000870 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000871 }
Mike Stump1eb44332009-09-09 15:08:12 +0000872
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000873 ASTContext& Context = this->getASTContext();
874
875 // Create a new DeclRefExpr to refer to the new decl.
876 DeclRefExpr* NewDRE = DeclRefExpr::Create(
877 Context,
878 DRE->getQualifierLoc(),
879 NewBuiltinDecl,
880 DRE->getLocation(),
881 NewBuiltinDecl->getType(),
882 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattner5caa3702009-05-08 06:58:22 +0000884 // Set the callee in the CallExpr.
885 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000886 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +0000887 if (PromotedCall.isInvalid())
888 return ExprError();
889 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000891 // Change the result type of the call to match the original value type. This
892 // is arbitrary, but the codegen for these builtins ins design to handle it
893 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000894 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000895
896 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000897}
898
Chris Lattner69039812009-02-18 06:01:06 +0000899/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000900/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000901/// Note: It might also make sense to do the UTF-16 conversion here (would
902/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000903bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000904 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000905 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
906
Douglas Gregor5cee1192011-07-27 05:40:30 +0000907 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000908 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
909 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000910 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000911 }
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000913 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000914 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000915 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000916 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000917 const UTF8 *FromPtr = (UTF8 *)String.data();
918 UTF16 *ToPtr = &ToBuf[0];
919
920 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
921 &ToPtr, ToPtr + NumBytes,
922 strictConversion);
923 // Check for conversion failure.
924 if (Result != conversionOK)
925 Diag(Arg->getLocStart(),
926 diag::warn_cfstring_truncated) << Arg->getSourceRange();
927 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000928 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000929}
930
Chris Lattnerc27c6652007-12-20 00:05:45 +0000931/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
932/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000933bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
934 Expr *Fn = TheCall->getCallee();
935 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000936 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000937 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000938 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
939 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000940 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000941 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000942 return true;
943 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000944
945 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000946 return Diag(TheCall->getLocEnd(),
947 diag::err_typecheck_call_too_few_args_at_least)
948 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000949 }
950
John McCall5f8d6042011-08-27 01:09:30 +0000951 // Type-check the first argument normally.
952 if (checkBuiltinArgument(*this, TheCall, 0))
953 return true;
954
Chris Lattnerc27c6652007-12-20 00:05:45 +0000955 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000956 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000957 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000958 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000959 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000960 else if (FunctionDecl *FD = getCurFunctionDecl())
961 isVariadic = FD->isVariadic();
962 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000963 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Chris Lattnerc27c6652007-12-20 00:05:45 +0000965 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000966 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
967 return true;
968 }
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattner30ce3442007-12-19 23:59:04 +0000970 // Verify that the second argument to the builtin is the last argument of the
971 // current function or method.
972 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000973 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Anders Carlsson88cf2262008-02-11 04:20:54 +0000975 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
976 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000977 // FIXME: This isn't correct for methods (results in bogus warning).
978 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000979 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000980 if (CurBlock)
981 LastArg = *(CurBlock->TheDecl->param_end()-1);
982 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000983 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000984 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000985 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000986 SecondArgIsLastNamedArgument = PV == LastArg;
987 }
988 }
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Chris Lattner30ce3442007-12-19 23:59:04 +0000990 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000991 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000992 diag::warn_second_parameter_of_va_start_not_last_named_argument);
993 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000994}
Chris Lattner30ce3442007-12-19 23:59:04 +0000995
Chris Lattner1b9a0792007-12-20 00:26:33 +0000996/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
997/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000998bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
999 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001000 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001001 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001002 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001003 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001004 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001005 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001006 << SourceRange(TheCall->getArg(2)->getLocStart(),
1007 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001008
John Wiegley429bb272011-04-08 18:41:53 +00001009 ExprResult OrigArg0 = TheCall->getArg(0);
1010 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001011
Chris Lattner1b9a0792007-12-20 00:26:33 +00001012 // Do standard promotions between the two arguments, returning their common
1013 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001014 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001015 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1016 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001017
1018 // Make sure any conversions are pushed back into the call; this is
1019 // type safe since unordered compare builtins are declared as "_Bool
1020 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001021 TheCall->setArg(0, OrigArg0.get());
1022 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001023
John Wiegley429bb272011-04-08 18:41:53 +00001024 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001025 return false;
1026
Chris Lattner1b9a0792007-12-20 00:26:33 +00001027 // If the common type isn't a real floating type, then the arguments were
1028 // invalid for this operation.
1029 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001030 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001031 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001032 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1033 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Chris Lattner1b9a0792007-12-20 00:26:33 +00001035 return false;
1036}
1037
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001038/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1039/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001040/// to check everything. We expect the last argument to be a floating point
1041/// value.
1042bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1043 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001044 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001045 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001046 if (TheCall->getNumArgs() > NumArgs)
1047 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001048 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001049 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001050 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001051 (*(TheCall->arg_end()-1))->getLocEnd());
1052
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001053 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Eli Friedman9ac6f622009-08-31 20:06:00 +00001055 if (OrigArg->isTypeDependent())
1056 return false;
1057
Chris Lattner81368fb2010-05-06 05:50:07 +00001058 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001059 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001060 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001061 diag::err_typecheck_call_invalid_unary_fp)
1062 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Chris Lattner81368fb2010-05-06 05:50:07 +00001064 // If this is an implicit conversion from float -> double, remove it.
1065 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1066 Expr *CastArg = Cast->getSubExpr();
1067 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1068 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1069 "promotion from float to double is the only expected cast here");
1070 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001071 TheCall->setArg(NumArgs-1, CastArg);
1072 OrigArg = CastArg;
1073 }
1074 }
1075
Eli Friedman9ac6f622009-08-31 20:06:00 +00001076 return false;
1077}
1078
Eli Friedmand38617c2008-05-14 19:38:39 +00001079/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1080// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001081ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001082 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001083 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001084 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001085 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001086 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001087
Nate Begeman37b6a572010-06-08 00:16:34 +00001088 // Determine which of the following types of shufflevector we're checking:
1089 // 1) unary, vector mask: (lhs, mask)
1090 // 2) binary, vector mask: (lhs, rhs, mask)
1091 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1092 QualType resType = TheCall->getArg(0)->getType();
1093 unsigned numElements = 0;
1094
Douglas Gregorcde01732009-05-19 22:10:17 +00001095 if (!TheCall->getArg(0)->isTypeDependent() &&
1096 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001097 QualType LHSType = TheCall->getArg(0)->getType();
1098 QualType RHSType = TheCall->getArg(1)->getType();
1099
1100 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001101 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001102 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001103 TheCall->getArg(1)->getLocEnd());
1104 return ExprError();
1105 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001106
1107 numElements = LHSType->getAs<VectorType>()->getNumElements();
1108 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Nate Begeman37b6a572010-06-08 00:16:34 +00001110 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1111 // with mask. If so, verify that RHS is an integer vector type with the
1112 // same number of elts as lhs.
1113 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001114 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001115 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1116 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1117 << SourceRange(TheCall->getArg(1)->getLocStart(),
1118 TheCall->getArg(1)->getLocEnd());
1119 numResElements = numElements;
1120 }
1121 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001122 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001123 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001124 TheCall->getArg(1)->getLocEnd());
1125 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001126 } else if (numElements != numResElements) {
1127 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001128 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001129 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001130 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001131 }
1132
1133 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001134 if (TheCall->getArg(i)->isTypeDependent() ||
1135 TheCall->getArg(i)->isValueDependent())
1136 continue;
1137
Nate Begeman37b6a572010-06-08 00:16:34 +00001138 llvm::APSInt Result(32);
1139 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1140 return ExprError(Diag(TheCall->getLocStart(),
1141 diag::err_shufflevector_nonconstant_argument)
1142 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001143
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001144 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001145 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001146 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001147 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001148 }
1149
Chris Lattner5f9e2722011-07-23 10:55:15 +00001150 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001151
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001152 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001153 exprs.push_back(TheCall->getArg(i));
1154 TheCall->setArg(i, 0);
1155 }
1156
Nate Begemana88dc302009-08-12 02:10:25 +00001157 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001158 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001159 TheCall->getCallee()->getLocStart(),
1160 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001161}
Chris Lattner30ce3442007-12-19 23:59:04 +00001162
Daniel Dunbar4493f792008-07-21 22:59:13 +00001163/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1164// This is declared to take (const void*, ...) and can take two
1165// optional constant int args.
1166bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001167 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001168
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001169 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001170 return Diag(TheCall->getLocEnd(),
1171 diag::err_typecheck_call_too_many_args_at_most)
1172 << 0 /*function call*/ << 3 << NumArgs
1173 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001174
1175 // Argument 0 is checked for us and the remaining arguments must be
1176 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001177 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001178 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001179
Eli Friedman9aef7262009-12-04 00:30:06 +00001180 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001181 if (SemaBuiltinConstantArg(TheCall, i, Result))
1182 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Daniel Dunbar4493f792008-07-21 22:59:13 +00001184 // FIXME: gcc issues a warning and rewrites these to 0. These
1185 // seems especially odd for the third argument since the default
1186 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001187 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001188 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001189 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001190 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001191 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001192 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001193 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001194 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001195 }
1196 }
1197
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001198 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001199}
1200
Eric Christopher691ebc32010-04-17 02:26:23 +00001201/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1202/// TheCall is a constant expression.
1203bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1204 llvm::APSInt &Result) {
1205 Expr *Arg = TheCall->getArg(ArgNum);
1206 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1207 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1208
1209 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1210
1211 if (!Arg->isIntegerConstantExpr(Result, Context))
1212 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001213 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001214
Chris Lattner21fb98e2009-09-23 06:06:36 +00001215 return false;
1216}
1217
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001218/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1219/// int type). This simply type checks that type is one of the defined
1220/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001221// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001222bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001223 llvm::APSInt Result;
1224
1225 // Check constant-ness first.
1226 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1227 return true;
1228
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001229 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001230 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001231 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1232 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001233 }
1234
1235 return false;
1236}
1237
Eli Friedman586d6a82009-05-03 06:04:26 +00001238/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001239/// This checks that val is a constant 1.
1240bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1241 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001242 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001243
Eric Christopher691ebc32010-04-17 02:26:23 +00001244 // TODO: This is less than ideal. Overload this to take a value.
1245 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1246 return true;
1247
1248 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001249 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1250 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1251
1252 return false;
1253}
1254
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001255// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +00001256bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1257 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001258 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001259 bool isPrintf, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001260 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001261 if (E->isTypeDependent() || E->isValueDependent())
1262 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001263
Peter Collingbournef111d932011-04-15 00:35:48 +00001264 E = E->IgnoreParens();
1265
Ted Kremenekd30ef872009-01-12 23:09:09 +00001266 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001267 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001268 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001269 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001270 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001271 format_idx, firstDataArg, isPrintf,
1272 inFunctionCall)
John McCall56ca35d2011-02-17 10:25:35 +00001273 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001274 format_idx, firstDataArg, isPrintf,
1275 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001276 }
1277
Ted Kremenek95355bb2010-09-09 03:51:42 +00001278 case Stmt::IntegerLiteralClass:
1279 // Technically -Wformat-nonliteral does not warn about this case.
1280 // The behavior of printf and friends in this case is implementation
1281 // dependent. Ideally if the format string cannot be null then
1282 // it should have a 'nonnull' attribute in the function prototype.
1283 return true;
1284
Ted Kremenekd30ef872009-01-12 23:09:09 +00001285 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001286 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1287 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001288 }
1289
John McCall56ca35d2011-02-17 10:25:35 +00001290 case Stmt::OpaqueValueExprClass:
1291 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1292 E = src;
1293 goto tryAgain;
1294 }
1295 return false;
1296
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001297 case Stmt::PredefinedExprClass:
1298 // While __func__, etc., are technically not string literals, they
1299 // cannot contain format specifiers and thus are not a security
1300 // liability.
1301 return true;
1302
Ted Kremenek082d9362009-03-20 21:35:28 +00001303 case Stmt::DeclRefExprClass: {
1304 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Ted Kremenek082d9362009-03-20 21:35:28 +00001306 // As an exception, do not flag errors for variables binding to
1307 // const string literals.
1308 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1309 bool isConstant = false;
1310 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001311
Ted Kremenek082d9362009-03-20 21:35:28 +00001312 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1313 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001314 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001315 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001316 PT->getPointeeType().isConstant(Context);
1317 }
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Ted Kremenek082d9362009-03-20 21:35:28 +00001319 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001320 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001321 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001322 HasVAListArg, format_idx, firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001323 isPrintf, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001324 }
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Anders Carlssond966a552009-06-28 19:55:58 +00001326 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1327 // special check to see if the format string is a function parameter
1328 // of the function calling the printf function. If the function
1329 // has an attribute indicating it is a printf-like function, then we
1330 // should suppress warnings concerning non-literals being used in a call
1331 // to a vprintf function. For example:
1332 //
1333 // void
1334 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1335 // va_list ap;
1336 // va_start(ap, fmt);
1337 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1338 // ...
1339 //
1340 //
1341 // FIXME: We don't have full attribute support yet, so just check to see
1342 // if the argument is a DeclRefExpr that references a parameter. We'll
1343 // add proper support for checking the attribute later.
1344 if (HasVAListArg)
1345 if (isa<ParmVarDecl>(VD))
1346 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001347 }
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Ted Kremenek082d9362009-03-20 21:35:28 +00001349 return false;
1350 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001351
Anders Carlsson8f031b32009-06-27 04:05:33 +00001352 case Stmt::CallExprClass: {
1353 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001354 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001355 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1356 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1357 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001358 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001359 unsigned ArgIndex = FA->getFormatIdx();
1360 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001361
1362 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001363 format_idx, firstDataArg, isPrintf,
1364 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001365 }
1366 }
1367 }
1368 }
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Anders Carlsson8f031b32009-06-27 04:05:33 +00001370 return false;
1371 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001372 case Stmt::ObjCStringLiteralClass:
1373 case Stmt::StringLiteralClass: {
1374 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Ted Kremenek082d9362009-03-20 21:35:28 +00001376 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001377 StrE = ObjCFExpr->getString();
1378 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001379 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Ted Kremenekd30ef872009-01-12 23:09:09 +00001381 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001382 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00001383 firstDataArg, isPrintf, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001384 return true;
1385 }
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Ted Kremenekd30ef872009-01-12 23:09:09 +00001387 return false;
1388 }
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Ted Kremenek082d9362009-03-20 21:35:28 +00001390 default:
1391 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001392 }
1393}
1394
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001395void
Mike Stump1eb44332009-09-09 15:08:12 +00001396Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001397 const Expr * const *ExprArgs,
1398 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001399 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1400 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001401 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001402 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001403 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001404 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001405 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001406 }
1407}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001408
Ted Kremenek826a3452010-07-16 02:11:22 +00001409/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1410/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001411void
Ted Kremenek826a3452010-07-16 02:11:22 +00001412Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1413 unsigned format_idx, unsigned firstDataArg,
1414 bool isPrintf) {
1415
Ted Kremenek082d9362009-03-20 21:35:28 +00001416 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001417
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001418 // The way the format attribute works in GCC, the implicit this argument
1419 // of member functions is counted. However, it doesn't appear in our own
1420 // lists, so decrement format_idx in that case.
1421 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001422 const CXXMethodDecl *method_decl =
1423 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1424 if (method_decl && method_decl->isInstance()) {
1425 // Catch a format attribute mistakenly referring to the object argument.
1426 if (format_idx == 0)
1427 return;
1428 --format_idx;
1429 if(firstDataArg != 0)
1430 --firstDataArg;
1431 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001432 }
1433
Ted Kremenek826a3452010-07-16 02:11:22 +00001434 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001435 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001436 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001437 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001438 return;
1439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Ted Kremenek082d9362009-03-20 21:35:28 +00001441 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Chris Lattner59907c42007-08-10 20:18:51 +00001443 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001444 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001445 // Dynamically generated format strings are difficult to
1446 // automatically vet at compile time. Requiring that format strings
1447 // are string literals: (1) permits the checking of format strings by
1448 // the compiler and thereby (2) can practically remove the source of
1449 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001450
Mike Stump1eb44332009-09-09 15:08:12 +00001451 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001452 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001453 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001454 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001455 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001456 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001457 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001458
Chris Lattner655f1412009-04-29 04:59:47 +00001459 // If there are no arguments specified, warn with -Wformat-security, otherwise
1460 // warn only with -Wformat-nonliteral.
1461 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001462 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001463 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001464 << OrigFormatExpr->getSourceRange();
1465 else
Mike Stump1eb44332009-09-09 15:08:12 +00001466 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001467 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001468 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001469}
Ted Kremenek71895b92007-08-14 17:39:48 +00001470
Ted Kremeneke0e53132010-01-28 23:39:18 +00001471namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001472class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1473protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001474 Sema &S;
1475 const StringLiteral *FExpr;
1476 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001477 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001478 const unsigned NumDataArgs;
1479 const bool IsObjCLiteral;
1480 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001481 const bool HasVAListArg;
1482 const CallExpr *TheCall;
1483 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001484 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001485 bool usesPositionalArgs;
1486 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001487 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001488public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001489 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001490 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001491 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001492 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001493 const CallExpr *theCall, unsigned formatIdx,
1494 bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001495 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001496 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001497 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001498 IsObjCLiteral(isObjCLiteral), Beg(beg),
1499 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001500 TheCall(theCall), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001501 usesPositionalArgs(false), atFirstArg(true),
1502 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001503 CoveredArgs.resize(numDataArgs);
1504 CoveredArgs.reset();
1505 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001506
Ted Kremenek07d161f2010-01-29 01:50:07 +00001507 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001508
Ted Kremenek826a3452010-07-16 02:11:22 +00001509 void HandleIncompleteSpecifier(const char *startSpecifier,
1510 unsigned specifierLen);
1511
Ted Kremenekefaff192010-02-27 01:41:03 +00001512 virtual void HandleInvalidPosition(const char *startSpecifier,
1513 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001514 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001515
1516 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1517
Ted Kremeneke0e53132010-01-28 23:39:18 +00001518 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001519
Richard Trieu55733de2011-10-28 00:41:25 +00001520 template <typename Range>
1521 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1522 const Expr *ArgumentExpr,
1523 PartialDiagnostic PDiag,
1524 SourceLocation StringLoc,
1525 bool IsStringLocation, Range StringRange,
1526 FixItHint Fixit = FixItHint());
1527
Ted Kremenek826a3452010-07-16 02:11:22 +00001528protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001529 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1530 const char *startSpec,
1531 unsigned specifierLen,
1532 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001533
1534 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1535 const char *startSpec,
1536 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001537
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001538 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001539 CharSourceRange getSpecifierRange(const char *startSpecifier,
1540 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001541 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001542
Ted Kremenek0d277352010-01-29 01:06:55 +00001543 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001544
1545 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1546 const analyze_format_string::ConversionSpecifier &CS,
1547 const char *startSpecifier, unsigned specifierLen,
1548 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001549
1550 template <typename Range>
1551 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1552 bool IsStringLocation, Range StringRange,
1553 FixItHint Fixit = FixItHint());
1554
1555 void CheckPositionalAndNonpositionalArgs(
1556 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001557};
1558}
1559
Ted Kremenek826a3452010-07-16 02:11:22 +00001560SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001561 return OrigFormatExpr->getSourceRange();
1562}
1563
Ted Kremenek826a3452010-07-16 02:11:22 +00001564CharSourceRange CheckFormatHandler::
1565getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001566 SourceLocation Start = getLocationOfByte(startSpecifier);
1567 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1568
1569 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001570 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001571
1572 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001573}
1574
Ted Kremenek826a3452010-07-16 02:11:22 +00001575SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001576 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001577}
1578
Ted Kremenek826a3452010-07-16 02:11:22 +00001579void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1580 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001581 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1582 getLocationOfByte(startSpecifier),
1583 /*IsStringLocation*/true,
1584 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001585}
1586
Ted Kremenekefaff192010-02-27 01:41:03 +00001587void
Ted Kremenek826a3452010-07-16 02:11:22 +00001588CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1589 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001590 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1591 << (unsigned) p,
1592 getLocationOfByte(startPos), /*IsStringLocation*/true,
1593 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001594}
1595
Ted Kremenek826a3452010-07-16 02:11:22 +00001596void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001597 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001598 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1599 getLocationOfByte(startPos),
1600 /*IsStringLocation*/true,
1601 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001602}
1603
Ted Kremenek826a3452010-07-16 02:11:22 +00001604void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001605 if (!IsObjCLiteral) {
1606 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001607 EmitFormatDiagnostic(
1608 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1609 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1610 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001611 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001612}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001613
Ted Kremenek826a3452010-07-16 02:11:22 +00001614const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1615 return TheCall->getArg(FirstDataArg + i);
1616}
1617
1618void CheckFormatHandler::DoneProcessing() {
1619 // Does the number of data arguments exceed the number of
1620 // format conversions in the format string?
1621 if (!HasVAListArg) {
1622 // Find any arguments that weren't covered.
1623 CoveredArgs.flip();
1624 signed notCoveredArg = CoveredArgs.find_first();
1625 if (notCoveredArg >= 0) {
1626 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001627 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1628 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1629 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001630 }
1631 }
1632}
1633
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001634bool
1635CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1636 SourceLocation Loc,
1637 const char *startSpec,
1638 unsigned specifierLen,
1639 const char *csStart,
1640 unsigned csLen) {
1641
1642 bool keepGoing = true;
1643 if (argIndex < NumDataArgs) {
1644 // Consider the argument coverered, even though the specifier doesn't
1645 // make sense.
1646 CoveredArgs.set(argIndex);
1647 }
1648 else {
1649 // If argIndex exceeds the number of data arguments we
1650 // don't issue a warning because that is just a cascade of warnings (and
1651 // they may have intended '%%' anyway). We don't want to continue processing
1652 // the format string after this point, however, as we will like just get
1653 // gibberish when trying to match arguments.
1654 keepGoing = false;
1655 }
1656
Richard Trieu55733de2011-10-28 00:41:25 +00001657 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1658 << StringRef(csStart, csLen),
1659 Loc, /*IsStringLocation*/true,
1660 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001661
1662 return keepGoing;
1663}
1664
Richard Trieu55733de2011-10-28 00:41:25 +00001665void
1666CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1667 const char *startSpec,
1668 unsigned specifierLen) {
1669 EmitFormatDiagnostic(
1670 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1671 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1672}
1673
Ted Kremenek666a1972010-07-26 19:45:42 +00001674bool
1675CheckFormatHandler::CheckNumArgs(
1676 const analyze_format_string::FormatSpecifier &FS,
1677 const analyze_format_string::ConversionSpecifier &CS,
1678 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1679
1680 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001681 PartialDiagnostic PDiag = FS.usesPositionalArg()
1682 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1683 << (argIndex+1) << NumDataArgs)
1684 : S.PDiag(diag::warn_printf_insufficient_data_args);
1685 EmitFormatDiagnostic(
1686 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1687 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001688 return false;
1689 }
1690 return true;
1691}
1692
Richard Trieu55733de2011-10-28 00:41:25 +00001693template<typename Range>
1694void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1695 SourceLocation Loc,
1696 bool IsStringLocation,
1697 Range StringRange,
1698 FixItHint FixIt) {
1699 EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
1700 Loc, IsStringLocation, StringRange, FixIt);
1701}
1702
1703/// \brief If the format string is not within the funcion call, emit a note
1704/// so that the function call and string are in diagnostic messages.
1705///
1706/// \param inFunctionCall if true, the format string is within the function
1707/// call and only one diagnostic message will be produced. Otherwise, an
1708/// extra note will be emitted pointing to location of the format string.
1709///
1710/// \param ArgumentExpr the expression that is passed as the format string
1711/// argument in the function call. Used for getting locations when two
1712/// diagnostics are emitted.
1713///
1714/// \param PDiag the callee should already have provided any strings for the
1715/// diagnostic message. This function only adds locations and fixits
1716/// to diagnostics.
1717///
1718/// \param Loc primary location for diagnostic. If two diagnostics are
1719/// required, one will be at Loc and a new SourceLocation will be created for
1720/// the other one.
1721///
1722/// \param IsStringLocation if true, Loc points to the format string should be
1723/// used for the note. Otherwise, Loc points to the argument list and will
1724/// be used with PDiag.
1725///
1726/// \param StringRange some or all of the string to highlight. This is
1727/// templated so it can accept either a CharSourceRange or a SourceRange.
1728///
1729/// \param Fixit optional fix it hint for the format string.
1730template<typename Range>
1731void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1732 const Expr *ArgumentExpr,
1733 PartialDiagnostic PDiag,
1734 SourceLocation Loc,
1735 bool IsStringLocation,
1736 Range StringRange,
1737 FixItHint FixIt) {
1738 if (InFunctionCall)
1739 S.Diag(Loc, PDiag) << StringRange << FixIt;
1740 else {
1741 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1742 << ArgumentExpr->getSourceRange();
1743 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1744 diag::note_format_string_defined)
1745 << StringRange << FixIt;
1746 }
1747}
1748
Ted Kremenek826a3452010-07-16 02:11:22 +00001749//===--- CHECK: Printf format string checking ------------------------------===//
1750
1751namespace {
1752class CheckPrintfHandler : public CheckFormatHandler {
1753public:
1754 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1755 const Expr *origFormatExpr, unsigned firstDataArg,
1756 unsigned numDataArgs, bool isObjCLiteral,
1757 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001758 const CallExpr *theCall, unsigned formatIdx,
1759 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001760 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1761 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001762 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001763
1764
1765 bool HandleInvalidPrintfConversionSpecifier(
1766 const analyze_printf::PrintfSpecifier &FS,
1767 const char *startSpecifier,
1768 unsigned specifierLen);
1769
1770 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1771 const char *startSpecifier,
1772 unsigned specifierLen);
1773
1774 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1775 const char *startSpecifier, unsigned specifierLen);
1776 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1777 const analyze_printf::OptionalAmount &Amt,
1778 unsigned type,
1779 const char *startSpecifier, unsigned specifierLen);
1780 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1781 const analyze_printf::OptionalFlag &flag,
1782 const char *startSpecifier, unsigned specifierLen);
1783 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1784 const analyze_printf::OptionalFlag &ignoredFlag,
1785 const analyze_printf::OptionalFlag &flag,
1786 const char *startSpecifier, unsigned specifierLen);
1787};
1788}
1789
1790bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1791 const analyze_printf::PrintfSpecifier &FS,
1792 const char *startSpecifier,
1793 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001794 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001795 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001796
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001797 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1798 getLocationOfByte(CS.getStart()),
1799 startSpecifier, specifierLen,
1800 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001801}
1802
Ted Kremenek826a3452010-07-16 02:11:22 +00001803bool CheckPrintfHandler::HandleAmount(
1804 const analyze_format_string::OptionalAmount &Amt,
1805 unsigned k, const char *startSpecifier,
1806 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001807
1808 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001809 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001810 unsigned argIndex = Amt.getArgIndex();
1811 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001812 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1813 << k,
1814 getLocationOfByte(Amt.getStart()),
1815 /*IsStringLocation*/true,
1816 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001817 // Don't do any more checking. We will just emit
1818 // spurious errors.
1819 return false;
1820 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001821
Ted Kremenek0d277352010-01-29 01:06:55 +00001822 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001823 // Although not in conformance with C99, we also allow the argument to be
1824 // an 'unsigned int' as that is a reasonably safe case. GCC also
1825 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001826 CoveredArgs.set(argIndex);
1827 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001828 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001829
1830 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1831 assert(ATR.isValid());
1832
1833 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00001834 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
1835 << k << ATR.getRepresentativeType(S.Context)
1836 << T << Arg->getSourceRange(),
1837 getLocationOfByte(Amt.getStart()),
1838 /*IsStringLocation*/true,
1839 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001840 // Don't do any more checking. We will just emit
1841 // spurious errors.
1842 return false;
1843 }
1844 }
1845 }
1846 return true;
1847}
Ted Kremenek0d277352010-01-29 01:06:55 +00001848
Tom Caree4ee9662010-06-17 19:00:27 +00001849void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001850 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001851 const analyze_printf::OptionalAmount &Amt,
1852 unsigned type,
1853 const char *startSpecifier,
1854 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001855 const analyze_printf::PrintfConversionSpecifier &CS =
1856 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001857
Richard Trieu55733de2011-10-28 00:41:25 +00001858 FixItHint fixit =
1859 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
1860 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1861 Amt.getConstantLength()))
1862 : FixItHint();
1863
1864 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
1865 << type << CS.toString(),
1866 getLocationOfByte(Amt.getStart()),
1867 /*IsStringLocation*/true,
1868 getSpecifierRange(startSpecifier, specifierLen),
1869 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00001870}
1871
Ted Kremenek826a3452010-07-16 02:11:22 +00001872void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001873 const analyze_printf::OptionalFlag &flag,
1874 const char *startSpecifier,
1875 unsigned specifierLen) {
1876 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001877 const analyze_printf::PrintfConversionSpecifier &CS =
1878 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00001879 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
1880 << flag.toString() << CS.toString(),
1881 getLocationOfByte(flag.getPosition()),
1882 /*IsStringLocation*/true,
1883 getSpecifierRange(startSpecifier, specifierLen),
1884 FixItHint::CreateRemoval(
1885 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00001886}
1887
1888void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001889 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001890 const analyze_printf::OptionalFlag &ignoredFlag,
1891 const analyze_printf::OptionalFlag &flag,
1892 const char *startSpecifier,
1893 unsigned specifierLen) {
1894 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00001895 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
1896 << ignoredFlag.toString() << flag.toString(),
1897 getLocationOfByte(ignoredFlag.getPosition()),
1898 /*IsStringLocation*/true,
1899 getSpecifierRange(startSpecifier, specifierLen),
1900 FixItHint::CreateRemoval(
1901 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00001902}
1903
Ted Kremeneke0e53132010-01-28 23:39:18 +00001904bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001905CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001906 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001907 const char *startSpecifier,
1908 unsigned specifierLen) {
1909
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001910 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001911 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001912 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001913
Ted Kremenekbaa40062010-07-19 22:01:06 +00001914 if (FS.consumesDataArgument()) {
1915 if (atFirstArg) {
1916 atFirstArg = false;
1917 usesPositionalArgs = FS.usesPositionalArg();
1918 }
1919 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00001920 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
1921 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00001922 return false;
1923 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001924 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001925
Ted Kremenekefaff192010-02-27 01:41:03 +00001926 // First check if the field width, precision, and conversion specifier
1927 // have matching data arguments.
1928 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1929 startSpecifier, specifierLen)) {
1930 return false;
1931 }
1932
1933 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1934 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001935 return false;
1936 }
1937
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001938 if (!CS.consumesDataArgument()) {
1939 // FIXME: Technically specifying a precision or field width here
1940 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001941 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001942 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001943
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001944 // Consume the argument.
1945 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001946 if (argIndex < NumDataArgs) {
1947 // The check to see if the argIndex is valid will come later.
1948 // We set the bit here because we may exit early from this
1949 // function if we encounter some other error.
1950 CoveredArgs.set(argIndex);
1951 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001952
1953 // Check for using an Objective-C specific conversion specifier
1954 // in a non-ObjC literal.
1955 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001956 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1957 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001958 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001959
Tom Caree4ee9662010-06-17 19:00:27 +00001960 // Check for invalid use of field width
1961 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001962 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001963 startSpecifier, specifierLen);
1964 }
1965
1966 // Check for invalid use of precision
1967 if (!FS.hasValidPrecision()) {
1968 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1969 startSpecifier, specifierLen);
1970 }
1971
1972 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001973 if (!FS.hasValidThousandsGroupingPrefix())
1974 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001975 if (!FS.hasValidLeadingZeros())
1976 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1977 if (!FS.hasValidPlusPrefix())
1978 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001979 if (!FS.hasValidSpacePrefix())
1980 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001981 if (!FS.hasValidAlternativeForm())
1982 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1983 if (!FS.hasValidLeftJustified())
1984 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1985
1986 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001987 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1988 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1989 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001990 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1991 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1992 startSpecifier, specifierLen);
1993
1994 // Check the length modifier is valid with the given conversion specifier.
1995 const LengthModifier &LM = FS.getLengthModifier();
1996 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00001997 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
1998 << LM.toString() << CS.toString(),
1999 getLocationOfByte(LM.getStart()),
2000 /*IsStringLocation*/true,
2001 getSpecifierRange(startSpecifier, specifierLen),
2002 FixItHint::CreateRemoval(
2003 getSpecifierRange(LM.getStart(),
2004 LM.getLength())));
Tom Caree4ee9662010-06-17 19:00:27 +00002005
2006 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002007 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002008 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002009 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2010 getLocationOfByte(CS.getStart()),
2011 /*IsStringLocation*/true,
2012 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002013 // Continue checking the other format specifiers.
2014 return true;
2015 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002016
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002017 // The remaining checks depend on the data arguments.
2018 if (HasVAListArg)
2019 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002020
Ted Kremenek666a1972010-07-26 19:45:42 +00002021 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002022 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002023
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002024 // Now type check the data expression that matches the
2025 // format specifier.
2026 const Expr *Ex = getDataArg(argIndex);
2027 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
2028 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2029 // Check if we didn't match because of an implicit cast from a 'char'
2030 // or 'short' to an 'int'. This is done because printf is a varargs
2031 // function.
2032 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002033 if (ICE->getType() == S.Context.IntTy) {
2034 // All further checking is done on the subexpression.
2035 Ex = ICE->getSubExpr();
2036 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002037 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002038 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002039
2040 // We may be able to offer a FixItHint if it is a supported type.
2041 PrintfSpecifier fixedFS = FS;
Hans Wennborga7da2152011-10-18 08:10:06 +00002042 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002043
2044 if (success) {
2045 // Get the fix string from the fixed format specifier
2046 llvm::SmallString<128> buf;
2047 llvm::raw_svector_ostream os(buf);
2048 fixedFS.toString(os);
2049
Ted Kremenek9325eaf2010-08-24 22:24:51 +00002050 // FIXME: getRepresentativeType() perhaps should return a string
2051 // instead of a QualType to better handle when the representative
2052 // type is 'wint_t' (which is defined in the system headers).
Richard Trieu55733de2011-10-28 00:41:25 +00002053 EmitFormatDiagnostic(
2054 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2055 << ATR.getRepresentativeType(S.Context) << Ex->getType()
2056 << Ex->getSourceRange(),
2057 getLocationOfByte(CS.getStart()),
2058 /*IsStringLocation*/true,
2059 getSpecifierRange(startSpecifier, specifierLen),
2060 FixItHint::CreateReplacement(
2061 getSpecifierRange(startSpecifier, specifierLen),
2062 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002063 }
2064 else {
2065 S.Diag(getLocationOfByte(CS.getStart()),
2066 diag::warn_printf_conversion_argument_type_mismatch)
2067 << ATR.getRepresentativeType(S.Context) << Ex->getType()
2068 << getSpecifierRange(startSpecifier, specifierLen)
2069 << Ex->getSourceRange();
2070 }
2071 }
2072
Ted Kremeneke0e53132010-01-28 23:39:18 +00002073 return true;
2074}
2075
Ted Kremenek826a3452010-07-16 02:11:22 +00002076//===--- CHECK: Scanf format string checking ------------------------------===//
2077
2078namespace {
2079class CheckScanfHandler : public CheckFormatHandler {
2080public:
2081 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2082 const Expr *origFormatExpr, unsigned firstDataArg,
2083 unsigned numDataArgs, bool isObjCLiteral,
2084 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002085 const CallExpr *theCall, unsigned formatIdx,
2086 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002087 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2088 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002089 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002090
2091 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2092 const char *startSpecifier,
2093 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002094
2095 bool HandleInvalidScanfConversionSpecifier(
2096 const analyze_scanf::ScanfSpecifier &FS,
2097 const char *startSpecifier,
2098 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002099
2100 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002101};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002102}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002103
Ted Kremenekb7c21012010-07-16 18:28:03 +00002104void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2105 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002106 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2107 getLocationOfByte(end), /*IsStringLocation*/true,
2108 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002109}
2110
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002111bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2112 const analyze_scanf::ScanfSpecifier &FS,
2113 const char *startSpecifier,
2114 unsigned specifierLen) {
2115
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002116 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002117 FS.getConversionSpecifier();
2118
2119 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2120 getLocationOfByte(CS.getStart()),
2121 startSpecifier, specifierLen,
2122 CS.getStart(), CS.getLength());
2123}
2124
Ted Kremenek826a3452010-07-16 02:11:22 +00002125bool CheckScanfHandler::HandleScanfSpecifier(
2126 const analyze_scanf::ScanfSpecifier &FS,
2127 const char *startSpecifier,
2128 unsigned specifierLen) {
2129
2130 using namespace analyze_scanf;
2131 using namespace analyze_format_string;
2132
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002133 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002134
Ted Kremenekbaa40062010-07-19 22:01:06 +00002135 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2136 // be used to decide if we are using positional arguments consistently.
2137 if (FS.consumesDataArgument()) {
2138 if (atFirstArg) {
2139 atFirstArg = false;
2140 usesPositionalArgs = FS.usesPositionalArg();
2141 }
2142 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002143 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2144 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002145 return false;
2146 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002147 }
2148
2149 // Check if the field with is non-zero.
2150 const OptionalAmount &Amt = FS.getFieldWidth();
2151 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2152 if (Amt.getConstantAmount() == 0) {
2153 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2154 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002155 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2156 getLocationOfByte(Amt.getStart()),
2157 /*IsStringLocation*/true, R,
2158 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002159 }
2160 }
2161
2162 if (!FS.consumesDataArgument()) {
2163 // FIXME: Technically specifying a precision or field width here
2164 // makes no sense. Worth issuing a warning at some point.
2165 return true;
2166 }
2167
2168 // Consume the argument.
2169 unsigned argIndex = FS.getArgIndex();
2170 if (argIndex < NumDataArgs) {
2171 // The check to see if the argIndex is valid will come later.
2172 // We set the bit here because we may exit early from this
2173 // function if we encounter some other error.
2174 CoveredArgs.set(argIndex);
2175 }
2176
Ted Kremenek1e51c202010-07-20 20:04:47 +00002177 // Check the length modifier is valid with the given conversion specifier.
2178 const LengthModifier &LM = FS.getLengthModifier();
2179 if (!FS.hasValidLengthModifier()) {
2180 S.Diag(getLocationOfByte(LM.getStart()),
2181 diag::warn_format_nonsensical_length)
2182 << LM.toString() << CS.toString()
2183 << getSpecifierRange(startSpecifier, specifierLen)
2184 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2185 LM.getLength()));
2186 }
2187
Ted Kremenek826a3452010-07-16 02:11:22 +00002188 // The remaining checks depend on the data arguments.
2189 if (HasVAListArg)
2190 return true;
2191
Ted Kremenek666a1972010-07-26 19:45:42 +00002192 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002193 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002194
2195 // FIXME: Check that the argument type matches the format specifier.
2196
2197 return true;
2198}
2199
2200void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002201 const Expr *OrigFormatExpr,
2202 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00002203 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002204 bool isPrintf, bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002205
Ted Kremeneke0e53132010-01-28 23:39:18 +00002206 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002207 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002208 CheckFormatHandler::EmitFormatDiagnostic(
2209 *this, inFunctionCall, TheCall->getArg(format_idx),
2210 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2211 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002212 return;
2213 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002214
Ted Kremeneke0e53132010-01-28 23:39:18 +00002215 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002216 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002217 const char *Str = StrRef.data();
2218 unsigned StrLen = StrRef.size();
Ted Kremenek4cd57912011-09-29 05:52:16 +00002219 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002220
Ted Kremeneke0e53132010-01-28 23:39:18 +00002221 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002222 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002223 CheckFormatHandler::EmitFormatDiagnostic(
2224 *this, inFunctionCall, TheCall->getArg(format_idx),
2225 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2226 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002227 return;
2228 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002229
2230 if (isPrintf) {
2231 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002232 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002233 Str, HasVAListArg, TheCall, format_idx,
2234 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002235
2236 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2237 H.DoneProcessing();
2238 }
2239 else {
2240 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002241 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002242 Str, HasVAListArg, TheCall, format_idx,
2243 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002244
2245 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2246 H.DoneProcessing();
2247 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002248}
2249
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002250//===--- CHECK: Standard memory functions ---------------------------------===//
2251
Douglas Gregor2a053a32011-05-03 20:05:22 +00002252/// \brief Determine whether the given type is a dynamic class type (e.g.,
2253/// whether it has a vtable).
2254static bool isDynamicClassType(QualType T) {
2255 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2256 if (CXXRecordDecl *Definition = Record->getDefinition())
2257 if (Definition->isDynamicClass())
2258 return true;
2259
2260 return false;
2261}
2262
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002263/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002264/// otherwise returns NULL.
2265static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002266 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002267 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2268 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2269 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002270
Chandler Carruth000d4282011-06-16 09:09:40 +00002271 return 0;
2272}
2273
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002274/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002275static QualType getSizeOfArgType(const Expr* E) {
2276 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2277 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2278 if (SizeOf->getKind() == clang::UETT_SizeOf)
2279 return SizeOf->getTypeOfArgument();
2280
2281 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002282}
2283
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002284/// \brief Check for dangerous or invalid arguments to memset().
2285///
Chandler Carruth929f0132011-06-03 06:23:57 +00002286/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002287/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2288/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002289///
2290/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002291void Sema::CheckMemaccessArguments(const CallExpr *Call,
2292 CheckedMemoryFunction CMF,
2293 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002294 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002295 // we have enough arguments, and if not, abort further checking.
Nico Webercda57822011-10-13 22:30:23 +00002296 unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2297 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002298 return;
2299
Nico Webercda57822011-10-13 22:30:23 +00002300 unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2301 unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2302 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002303
2304 // We have special checking when the length is a sizeof expression.
2305 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2306 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2307 llvm::FoldingSetNodeID SizeOfArgID;
2308
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002309 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2310 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002311 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002312
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002313 QualType DestTy = Dest->getType();
2314 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2315 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002316
Chandler Carruth000d4282011-06-16 09:09:40 +00002317 // Never warn about void type pointers. This can be used to suppress
2318 // false positives.
2319 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002320 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002321
Chandler Carruth000d4282011-06-16 09:09:40 +00002322 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2323 // actually comparing the expressions for equality. Because computing the
2324 // expression IDs can be expensive, we only do this if the diagnostic is
2325 // enabled.
2326 if (SizeOfArg &&
2327 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2328 SizeOfArg->getExprLoc())) {
2329 // We only compute IDs for expressions if the warning is enabled, and
2330 // cache the sizeof arg's ID.
2331 if (SizeOfArgID == llvm::FoldingSetNodeID())
2332 SizeOfArg->Profile(SizeOfArgID, Context, true);
2333 llvm::FoldingSetNodeID DestID;
2334 Dest->Profile(DestID, Context, true);
2335 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002336 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2337 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002338 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2339 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2340 if (UnaryOp->getOpcode() == UO_AddrOf)
2341 ActionIdx = 1; // If its an address-of operator, just remove it.
2342 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2343 ActionIdx = 2; // If the pointee's size is sizeof(char),
2344 // suggest an explicit length.
Nico Webercda57822011-10-13 22:30:23 +00002345 unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002346 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2347 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002348 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002349 << Dest->getSourceRange()
2350 << SizeOfArg->getSourceRange());
2351 break;
2352 }
2353 }
2354
2355 // Also check for cases where the sizeof argument is the exact same
2356 // type as the memory argument, and where it points to a user-defined
2357 // record type.
2358 if (SizeOfArgTy != QualType()) {
2359 if (PointeeTy->isRecordType() &&
2360 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2361 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2362 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2363 << FnName << SizeOfArgTy << ArgIdx
2364 << PointeeTy << Dest->getSourceRange()
2365 << LenExpr->getSourceRange());
2366 break;
2367 }
Nico Webere4a1c642011-06-14 16:14:58 +00002368 }
2369
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002370 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00002371 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002372 DiagRuntimeBehavior(
2373 Dest->getExprLoc(), Dest,
2374 PDiag(diag::warn_dyn_class_memaccess)
2375 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2376 // "overwritten" if we're warning about the destination for any call
2377 // but memcmp; otherwise a verb appropriate to the call.
2378 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2379 << Call->getCallee()->getSourceRange());
Douglas Gregor707a23e2011-06-16 17:56:04 +00002380 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002381 DiagRuntimeBehavior(
2382 Dest->getExprLoc(), Dest,
2383 PDiag(diag::warn_arc_object_memaccess)
2384 << ArgIdx << FnName << PointeeTy
2385 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002386 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002387 continue;
John McCallf85e1932011-06-15 23:02:42 +00002388
2389 DiagRuntimeBehavior(
2390 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002391 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002392 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2393 break;
2394 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002395 }
2396}
2397
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002398// A little helper routine: ignore addition and subtraction of integer literals.
2399// This intentionally does not ignore all integer constant expressions because
2400// we don't want to remove sizeof().
2401static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2402 Ex = Ex->IgnoreParenCasts();
2403
2404 for (;;) {
2405 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2406 if (!BO || !BO->isAdditiveOp())
2407 break;
2408
2409 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2410 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2411
2412 if (isa<IntegerLiteral>(RHS))
2413 Ex = LHS;
2414 else if (isa<IntegerLiteral>(LHS))
2415 Ex = RHS;
2416 else
2417 break;
2418 }
2419
2420 return Ex;
2421}
2422
2423// Warn if the user has made the 'size' argument to strlcpy or strlcat
2424// be the size of the source, instead of the destination.
2425void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2426 IdentifierInfo *FnName) {
2427
2428 // Don't crash if the user has the wrong number of arguments
2429 if (Call->getNumArgs() != 3)
2430 return;
2431
2432 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2433 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2434 const Expr *CompareWithSrc = NULL;
2435
2436 // Look for 'strlcpy(dst, x, sizeof(x))'
2437 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2438 CompareWithSrc = Ex;
2439 else {
2440 // Look for 'strlcpy(dst, x, strlen(x))'
2441 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002442 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002443 && SizeCall->getNumArgs() == 1)
2444 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2445 }
2446 }
2447
2448 if (!CompareWithSrc)
2449 return;
2450
2451 // Determine if the argument to sizeof/strlen is equal to the source
2452 // argument. In principle there's all kinds of things you could do
2453 // here, for instance creating an == expression and evaluating it with
2454 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2455 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2456 if (!SrcArgDRE)
2457 return;
2458
2459 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2460 if (!CompareWithSrcDRE ||
2461 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2462 return;
2463
2464 const Expr *OriginalSizeArg = Call->getArg(2);
2465 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2466 << OriginalSizeArg->getSourceRange() << FnName;
2467
2468 // Output a FIXIT hint if the destination is an array (rather than a
2469 // pointer to an array). This could be enhanced to handle some
2470 // pointers if we know the actual size, like if DstArg is 'array+2'
2471 // we could say 'sizeof(array)-2'.
2472 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002473 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002474
Ted Kremenek8f746222011-08-18 22:48:41 +00002475 // Only handle constant-sized or VLAs, but not flexible members.
2476 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2477 // Only issue the FIXIT for arrays of size > 1.
2478 if (CAT->getSize().getSExtValue() <= 1)
2479 return;
2480 } else if (!DstArgTy->isVariableArrayType()) {
2481 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002482 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002483
2484 llvm::SmallString<128> sizeString;
2485 llvm::raw_svector_ostream OS(sizeString);
2486 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002487 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002488 OS << ")";
2489
2490 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2491 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2492 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002493}
2494
Ted Kremenek06de2762007-08-17 16:46:58 +00002495//===--- CHECK: Return Address of Stack Variable --------------------------===//
2496
Chris Lattner5f9e2722011-07-23 10:55:15 +00002497static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2498static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002499
2500/// CheckReturnStackAddr - Check if a return statement returns the address
2501/// of a stack variable.
2502void
2503Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2504 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002505
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002506 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002507 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002508
2509 // Perform checking for returned stack addresses, local blocks,
2510 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002511 if (lhsType->isPointerType() ||
2512 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002513 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002514 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002515 stackE = EvalVal(RetValExp, refVars);
2516 }
2517
2518 if (stackE == 0)
2519 return; // Nothing suspicious was found.
2520
2521 SourceLocation diagLoc;
2522 SourceRange diagRange;
2523 if (refVars.empty()) {
2524 diagLoc = stackE->getLocStart();
2525 diagRange = stackE->getSourceRange();
2526 } else {
2527 // We followed through a reference variable. 'stackE' contains the
2528 // problematic expression but we will warn at the return statement pointing
2529 // at the reference variable. We will later display the "trail" of
2530 // reference variables using notes.
2531 diagLoc = refVars[0]->getLocStart();
2532 diagRange = refVars[0]->getSourceRange();
2533 }
2534
2535 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2536 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2537 : diag::warn_ret_stack_addr)
2538 << DR->getDecl()->getDeclName() << diagRange;
2539 } else if (isa<BlockExpr>(stackE)) { // local block.
2540 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2541 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2542 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2543 } else { // local temporary.
2544 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2545 : diag::warn_ret_local_temp_addr)
2546 << diagRange;
2547 }
2548
2549 // Display the "trail" of reference variables that we followed until we
2550 // found the problematic expression using notes.
2551 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2552 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2553 // If this var binds to another reference var, show the range of the next
2554 // var, otherwise the var binds to the problematic expression, in which case
2555 // show the range of the expression.
2556 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2557 : stackE->getSourceRange();
2558 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2559 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002560 }
2561}
2562
2563/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2564/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002565/// to a location on the stack, a local block, an address of a label, or a
2566/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002567/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002568/// encounter a subexpression that (1) clearly does not lead to one of the
2569/// above problematic expressions (2) is something we cannot determine leads to
2570/// a problematic expression based on such local checking.
2571///
2572/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2573/// the expression that they point to. Such variables are added to the
2574/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002575///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002576/// EvalAddr processes expressions that are pointers that are used as
2577/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002578/// At the base case of the recursion is a check for the above problematic
2579/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002580///
2581/// This implementation handles:
2582///
2583/// * pointer-to-pointer casts
2584/// * implicit conversions from array references to pointers
2585/// * taking the address of fields
2586/// * arbitrary interplay between "&" and "*" operators
2587/// * pointer arithmetic from an address of a stack variable
2588/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002589static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002590 if (E->isTypeDependent())
2591 return NULL;
2592
Ted Kremenek06de2762007-08-17 16:46:58 +00002593 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002594 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002595 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002596 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002597 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Peter Collingbournef111d932011-04-15 00:35:48 +00002599 E = E->IgnoreParens();
2600
Ted Kremenek06de2762007-08-17 16:46:58 +00002601 // Our "symbolic interpreter" is just a dispatch off the currently
2602 // viewed AST node. We then recursively traverse the AST by calling
2603 // EvalAddr and EvalVal appropriately.
2604 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002605 case Stmt::DeclRefExprClass: {
2606 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2607
2608 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2609 // If this is a reference variable, follow through to the expression that
2610 // it points to.
2611 if (V->hasLocalStorage() &&
2612 V->getType()->isReferenceType() && V->hasInit()) {
2613 // Add the reference variable to the "trail".
2614 refVars.push_back(DR);
2615 return EvalAddr(V->getInit(), refVars);
2616 }
2617
2618 return NULL;
2619 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002620
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002621 case Stmt::UnaryOperatorClass: {
2622 // The only unary operator that make sense to handle here
2623 // is AddrOf. All others don't make sense as pointers.
2624 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002625
John McCall2de56d12010-08-25 11:45:40 +00002626 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002627 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002628 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002629 return NULL;
2630 }
Mike Stump1eb44332009-09-09 15:08:12 +00002631
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002632 case Stmt::BinaryOperatorClass: {
2633 // Handle pointer arithmetic. All other binary operators are not valid
2634 // in this context.
2635 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002636 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002637
John McCall2de56d12010-08-25 11:45:40 +00002638 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002639 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002641 Expr *Base = B->getLHS();
2642
2643 // Determine which argument is the real pointer base. It could be
2644 // the RHS argument instead of the LHS.
2645 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002647 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002648 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002649 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002650
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002651 // For conditional operators we need to see if either the LHS or RHS are
2652 // valid DeclRefExpr*s. If one of them is valid, we return it.
2653 case Stmt::ConditionalOperatorClass: {
2654 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002655
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002656 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002657 if (Expr *lhsExpr = C->getLHS()) {
2658 // In C++, we can have a throw-expression, which has 'void' type.
2659 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002660 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002661 return LHS;
2662 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002663
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002664 // In C++, we can have a throw-expression, which has 'void' type.
2665 if (C->getRHS()->getType()->isVoidType())
2666 return NULL;
2667
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002668 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002669 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002670
2671 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002672 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002673 return E; // local block.
2674 return NULL;
2675
2676 case Stmt::AddrLabelExprClass:
2677 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002678
John McCall80ee6e82011-11-10 05:35:25 +00002679 case Stmt::ExprWithCleanupsClass:
2680 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2681
Ted Kremenek54b52742008-08-07 00:49:01 +00002682 // For casts, we need to handle conversions from arrays to
2683 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002684 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002685 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002686 case Stmt::CXXFunctionalCastExprClass:
2687 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002688 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002689 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Steve Naroffdd972f22008-09-05 22:11:13 +00002691 if (SubExpr->getType()->isPointerType() ||
2692 SubExpr->getType()->isBlockPointerType() ||
2693 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002694 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002695 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002696 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002697 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002698 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002699 }
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002701 // C++ casts. For dynamic casts, static casts, and const casts, we
2702 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002703 // through the cast. In the case the dynamic cast doesn't fail (and
2704 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002705 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002706 // FIXME: The comment about is wrong; we're not always converting
2707 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002708 // handle references to objects.
2709 case Stmt::CXXStaticCastExprClass:
2710 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002711 case Stmt::CXXConstCastExprClass:
2712 case Stmt::CXXReinterpretCastExprClass: {
2713 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002714 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002715 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002716 else
2717 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002718 }
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Douglas Gregor03e80032011-06-21 17:03:29 +00002720 case Stmt::MaterializeTemporaryExprClass:
2721 if (Expr *Result = EvalAddr(
2722 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2723 refVars))
2724 return Result;
2725
2726 return E;
2727
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002728 // Everything else: we simply don't reason about them.
2729 default:
2730 return NULL;
2731 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002732}
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Ted Kremenek06de2762007-08-17 16:46:58 +00002734
2735/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2736/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002737static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002738do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002739 // We should only be called for evaluating non-pointer expressions, or
2740 // expressions with a pointer type that are not used as references but instead
2741 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002742
Ted Kremenek06de2762007-08-17 16:46:58 +00002743 // Our "symbolic interpreter" is just a dispatch off the currently
2744 // viewed AST node. We then recursively traverse the AST by calling
2745 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002746
2747 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002748 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002749 case Stmt::ImplicitCastExprClass: {
2750 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002751 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002752 E = IE->getSubExpr();
2753 continue;
2754 }
2755 return NULL;
2756 }
2757
John McCall80ee6e82011-11-10 05:35:25 +00002758 case Stmt::ExprWithCleanupsClass:
2759 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2760
Douglas Gregora2813ce2009-10-23 18:54:35 +00002761 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002762 // When we hit a DeclRefExpr we are looking at code that refers to a
2763 // variable's name. If it's not a reference variable we check if it has
2764 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002765 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002766
Ted Kremenek06de2762007-08-17 16:46:58 +00002767 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002768 if (V->hasLocalStorage()) {
2769 if (!V->getType()->isReferenceType())
2770 return DR;
2771
2772 // Reference variable, follow through to the expression that
2773 // it points to.
2774 if (V->hasInit()) {
2775 // Add the reference variable to the "trail".
2776 refVars.push_back(DR);
2777 return EvalVal(V->getInit(), refVars);
2778 }
2779 }
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Ted Kremenek06de2762007-08-17 16:46:58 +00002781 return NULL;
2782 }
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Ted Kremenek06de2762007-08-17 16:46:58 +00002784 case Stmt::UnaryOperatorClass: {
2785 // The only unary operator that make sense to handle here
2786 // is Deref. All others don't resolve to a "name." This includes
2787 // handling all sorts of rvalues passed to a unary operator.
2788 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002789
John McCall2de56d12010-08-25 11:45:40 +00002790 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002791 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002792
2793 return NULL;
2794 }
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Ted Kremenek06de2762007-08-17 16:46:58 +00002796 case Stmt::ArraySubscriptExprClass: {
2797 // Array subscripts are potential references to data on the stack. We
2798 // retrieve the DeclRefExpr* for the array variable if it indeed
2799 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002800 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002801 }
Mike Stump1eb44332009-09-09 15:08:12 +00002802
Ted Kremenek06de2762007-08-17 16:46:58 +00002803 case Stmt::ConditionalOperatorClass: {
2804 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002805 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002806 ConditionalOperator *C = cast<ConditionalOperator>(E);
2807
Anders Carlsson39073232007-11-30 19:04:31 +00002808 // Handle the GNU extension for missing LHS.
2809 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002810 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002811 return LHS;
2812
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002813 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002814 }
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Ted Kremenek06de2762007-08-17 16:46:58 +00002816 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002817 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002818 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002819
Ted Kremenek06de2762007-08-17 16:46:58 +00002820 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002821 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002822 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002823
2824 // Check whether the member type is itself a reference, in which case
2825 // we're not going to refer to the member, but to what the member refers to.
2826 if (M->getMemberDecl()->getType()->isReferenceType())
2827 return NULL;
2828
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002829 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002830 }
Mike Stump1eb44332009-09-09 15:08:12 +00002831
Douglas Gregor03e80032011-06-21 17:03:29 +00002832 case Stmt::MaterializeTemporaryExprClass:
2833 if (Expr *Result = EvalVal(
2834 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2835 refVars))
2836 return Result;
2837
2838 return E;
2839
Ted Kremenek06de2762007-08-17 16:46:58 +00002840 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002841 // Check that we don't return or take the address of a reference to a
2842 // temporary. This is only useful in C++.
2843 if (!E->isTypeDependent() && E->isRValue())
2844 return E;
2845
2846 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002847 return NULL;
2848 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002849} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002850}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002851
2852//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2853
2854/// Check for comparisons of floating point operands using != and ==.
2855/// Issue a warning if these are no self-comparisons, as they are not likely
2856/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00002857void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002858 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002859
Richard Trieudd225092011-09-15 21:56:47 +00002860 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2861 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002862
2863 // Special case: check for x == x (which is OK).
2864 // Do not emit warnings for such cases.
2865 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2866 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2867 if (DRL->getDecl() == DRR->getDecl())
2868 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002869
2870
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002871 // Special case: check for comparisons against literals that can be exactly
2872 // represented by APFloat. In such cases, do not emit a warning. This
2873 // is a heuristic: often comparison against such literals are used to
2874 // detect if a value in a variable has not changed. This clearly can
2875 // lead to false negatives.
2876 if (EmitWarning) {
2877 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2878 if (FLL->isExact())
2879 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002880 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002881 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2882 if (FLR->isExact())
2883 EmitWarning = false;
2884 }
2885 }
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002887 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002888 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002889 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00002890 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002891 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002892
Sebastian Redl0eb23302009-01-19 00:08:26 +00002893 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002894 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00002895 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002896 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002898 // Emit the diagnostic.
2899 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00002900 Diag(Loc, diag::warn_floatingpoint_eq)
2901 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002902}
John McCallba26e582010-01-04 23:21:16 +00002903
John McCallf2370c92010-01-06 05:24:50 +00002904//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2905//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002906
John McCallf2370c92010-01-06 05:24:50 +00002907namespace {
John McCallba26e582010-01-04 23:21:16 +00002908
John McCallf2370c92010-01-06 05:24:50 +00002909/// Structure recording the 'active' range of an integer-valued
2910/// expression.
2911struct IntRange {
2912 /// The number of bits active in the int.
2913 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002914
John McCallf2370c92010-01-06 05:24:50 +00002915 /// True if the int is known not to have negative values.
2916 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002917
John McCallf2370c92010-01-06 05:24:50 +00002918 IntRange(unsigned Width, bool NonNegative)
2919 : Width(Width), NonNegative(NonNegative)
2920 {}
John McCallba26e582010-01-04 23:21:16 +00002921
John McCall1844a6e2010-11-10 23:38:19 +00002922 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002923 static IntRange forBoolType() {
2924 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002925 }
2926
John McCall1844a6e2010-11-10 23:38:19 +00002927 /// Returns the range of an opaque value of the given integral type.
2928 static IntRange forValueOfType(ASTContext &C, QualType T) {
2929 return forValueOfCanonicalType(C,
2930 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002931 }
2932
John McCall1844a6e2010-11-10 23:38:19 +00002933 /// Returns the range of an opaque value of a canonical integral type.
2934 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002935 assert(T->isCanonicalUnqualified());
2936
2937 if (const VectorType *VT = dyn_cast<VectorType>(T))
2938 T = VT->getElementType().getTypePtr();
2939 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2940 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002941
John McCall091f23f2010-11-09 22:22:12 +00002942 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002943 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2944 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00002945 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00002946 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2947
John McCall323ed742010-05-06 08:58:33 +00002948 unsigned NumPositive = Enum->getNumPositiveBits();
2949 unsigned NumNegative = Enum->getNumNegativeBits();
2950
2951 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2952 }
John McCallf2370c92010-01-06 05:24:50 +00002953
2954 const BuiltinType *BT = cast<BuiltinType>(T);
2955 assert(BT->isInteger());
2956
2957 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2958 }
2959
John McCall1844a6e2010-11-10 23:38:19 +00002960 /// Returns the "target" range of a canonical integral type, i.e.
2961 /// the range of values expressible in the type.
2962 ///
2963 /// This matches forValueOfCanonicalType except that enums have the
2964 /// full range of their type, not the range of their enumerators.
2965 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2966 assert(T->isCanonicalUnqualified());
2967
2968 if (const VectorType *VT = dyn_cast<VectorType>(T))
2969 T = VT->getElementType().getTypePtr();
2970 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2971 T = CT->getElementType().getTypePtr();
2972 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00002973 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00002974
2975 const BuiltinType *BT = cast<BuiltinType>(T);
2976 assert(BT->isInteger());
2977
2978 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2979 }
2980
2981 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002982 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002983 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002984 L.NonNegative && R.NonNegative);
2985 }
2986
John McCall1844a6e2010-11-10 23:38:19 +00002987 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002988 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002989 return IntRange(std::min(L.Width, R.Width),
2990 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002991 }
2992};
2993
2994IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2995 if (value.isSigned() && value.isNegative())
2996 return IntRange(value.getMinSignedBits(), false);
2997
2998 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002999 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003000
3001 // isNonNegative() just checks the sign bit without considering
3002 // signedness.
3003 return IntRange(value.getActiveBits(), true);
3004}
3005
John McCall0acc3112010-01-06 22:57:21 +00003006IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00003007 unsigned MaxWidth) {
3008 if (result.isInt())
3009 return GetValueRange(C, result.getInt(), MaxWidth);
3010
3011 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003012 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3013 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3014 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3015 R = IntRange::join(R, El);
3016 }
John McCallf2370c92010-01-06 05:24:50 +00003017 return R;
3018 }
3019
3020 if (result.isComplexInt()) {
3021 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3022 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3023 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003024 }
3025
3026 // This can happen with lossless casts to intptr_t of "based" lvalues.
3027 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003028 // FIXME: The only reason we need to pass the type in here is to get
3029 // the sign right on this one case. It would be nice if APValue
3030 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00003031 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003032 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003033}
John McCallf2370c92010-01-06 05:24:50 +00003034
3035/// Pseudo-evaluate the given integer expression, estimating the
3036/// range of values it might take.
3037///
3038/// \param MaxWidth - the width to which the value will be truncated
3039IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3040 E = E->IgnoreParens();
3041
3042 // Try a full evaluation first.
3043 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003044 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003045 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003046
3047 // I think we only want to look through implicit casts here; if the
3048 // user has an explicit widening cast, we should treat the value as
3049 // being of the new, wider type.
3050 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00003051 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00003052 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3053
John McCall1844a6e2010-11-10 23:38:19 +00003054 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003055
John McCall2de56d12010-08-25 11:45:40 +00003056 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003057
John McCallf2370c92010-01-06 05:24:50 +00003058 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003059 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003060 return OutputTypeRange;
3061
3062 IntRange SubRange
3063 = GetExprRange(C, CE->getSubExpr(),
3064 std::min(MaxWidth, OutputTypeRange.Width));
3065
3066 // Bail out if the subexpr's range is as wide as the cast type.
3067 if (SubRange.Width >= OutputTypeRange.Width)
3068 return OutputTypeRange;
3069
3070 // Otherwise, we take the smaller width, and we're non-negative if
3071 // either the output type or the subexpr is.
3072 return IntRange(SubRange.Width,
3073 SubRange.NonNegative || OutputTypeRange.NonNegative);
3074 }
3075
3076 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3077 // If we can fold the condition, just take that operand.
3078 bool CondResult;
3079 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3080 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3081 : CO->getFalseExpr(),
3082 MaxWidth);
3083
3084 // Otherwise, conservatively merge.
3085 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3086 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3087 return IntRange::join(L, R);
3088 }
3089
3090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3091 switch (BO->getOpcode()) {
3092
3093 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003094 case BO_LAnd:
3095 case BO_LOr:
3096 case BO_LT:
3097 case BO_GT:
3098 case BO_LE:
3099 case BO_GE:
3100 case BO_EQ:
3101 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003102 return IntRange::forBoolType();
3103
John McCall862ff872011-07-13 06:35:24 +00003104 // The type of the assignments is the type of the LHS, so the RHS
3105 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003106 case BO_MulAssign:
3107 case BO_DivAssign:
3108 case BO_RemAssign:
3109 case BO_AddAssign:
3110 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003111 case BO_XorAssign:
3112 case BO_OrAssign:
3113 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003114 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003115
John McCall862ff872011-07-13 06:35:24 +00003116 // Simple assignments just pass through the RHS, which will have
3117 // been coerced to the LHS type.
3118 case BO_Assign:
3119 // TODO: bitfields?
3120 return GetExprRange(C, BO->getRHS(), MaxWidth);
3121
John McCallf2370c92010-01-06 05:24:50 +00003122 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003123 case BO_PtrMemD:
3124 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003125 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003126
John McCall60fad452010-01-06 22:07:33 +00003127 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003128 case BO_And:
3129 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003130 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3131 GetExprRange(C, BO->getRHS(), MaxWidth));
3132
John McCallf2370c92010-01-06 05:24:50 +00003133 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003134 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003135 // ...except that we want to treat '1 << (blah)' as logically
3136 // positive. It's an important idiom.
3137 if (IntegerLiteral *I
3138 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3139 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003140 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003141 return IntRange(R.Width, /*NonNegative*/ true);
3142 }
3143 }
3144 // fallthrough
3145
John McCall2de56d12010-08-25 11:45:40 +00003146 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003147 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003148
John McCall60fad452010-01-06 22:07:33 +00003149 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003150 case BO_Shr:
3151 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003152 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3153
3154 // If the shift amount is a positive constant, drop the width by
3155 // that much.
3156 llvm::APSInt shift;
3157 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3158 shift.isNonNegative()) {
3159 unsigned zext = shift.getZExtValue();
3160 if (zext >= L.Width)
3161 L.Width = (L.NonNegative ? 0 : 1);
3162 else
3163 L.Width -= zext;
3164 }
3165
3166 return L;
3167 }
3168
3169 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003170 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003171 return GetExprRange(C, BO->getRHS(), MaxWidth);
3172
John McCall60fad452010-01-06 22:07:33 +00003173 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003174 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003175 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003176 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003177 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003178
John McCall00fe7612011-07-14 22:39:48 +00003179 // The width of a division result is mostly determined by the size
3180 // of the LHS.
3181 case BO_Div: {
3182 // Don't 'pre-truncate' the operands.
3183 unsigned opWidth = C.getIntWidth(E->getType());
3184 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3185
3186 // If the divisor is constant, use that.
3187 llvm::APSInt divisor;
3188 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3189 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3190 if (log2 >= L.Width)
3191 L.Width = (L.NonNegative ? 0 : 1);
3192 else
3193 L.Width = std::min(L.Width - log2, MaxWidth);
3194 return L;
3195 }
3196
3197 // Otherwise, just use the LHS's width.
3198 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3199 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3200 }
3201
3202 // The result of a remainder can't be larger than the result of
3203 // either side.
3204 case BO_Rem: {
3205 // Don't 'pre-truncate' the operands.
3206 unsigned opWidth = C.getIntWidth(E->getType());
3207 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3208 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3209
3210 IntRange meet = IntRange::meet(L, R);
3211 meet.Width = std::min(meet.Width, MaxWidth);
3212 return meet;
3213 }
3214
3215 // The default behavior is okay for these.
3216 case BO_Mul:
3217 case BO_Add:
3218 case BO_Xor:
3219 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003220 break;
3221 }
3222
John McCall00fe7612011-07-14 22:39:48 +00003223 // The default case is to treat the operation as if it were closed
3224 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003225 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3226 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3227 return IntRange::join(L, R);
3228 }
3229
3230 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3231 switch (UO->getOpcode()) {
3232 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003233 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003234 return IntRange::forBoolType();
3235
3236 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003237 case UO_Deref:
3238 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003239 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003240
3241 default:
3242 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3243 }
3244 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003245
3246 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003247 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003248 }
John McCallf2370c92010-01-06 05:24:50 +00003249
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003250 if (FieldDecl *BitField = E->getBitField())
3251 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003252 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003253
John McCall1844a6e2010-11-10 23:38:19 +00003254 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003255}
John McCall51313c32010-01-04 23:31:57 +00003256
John McCall323ed742010-05-06 08:58:33 +00003257IntRange GetExprRange(ASTContext &C, Expr *E) {
3258 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3259}
3260
John McCall51313c32010-01-04 23:31:57 +00003261/// Checks whether the given value, which currently has the given
3262/// source semantics, has the same value when coerced through the
3263/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003264bool IsSameFloatAfterCast(const llvm::APFloat &value,
3265 const llvm::fltSemantics &Src,
3266 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003267 llvm::APFloat truncated = value;
3268
3269 bool ignored;
3270 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3271 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3272
3273 return truncated.bitwiseIsEqual(value);
3274}
3275
3276/// Checks whether the given value, which currently has the given
3277/// source semantics, has the same value when coerced through the
3278/// target semantics.
3279///
3280/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003281bool IsSameFloatAfterCast(const APValue &value,
3282 const llvm::fltSemantics &Src,
3283 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003284 if (value.isFloat())
3285 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3286
3287 if (value.isVector()) {
3288 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3289 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3290 return false;
3291 return true;
3292 }
3293
3294 assert(value.isComplexFloat());
3295 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3296 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3297}
3298
John McCallb4eb64d2010-10-08 02:01:28 +00003299void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003300
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003301static bool IsZero(Sema &S, Expr *E) {
3302 // Suppress cases where we are comparing against an enum constant.
3303 if (const DeclRefExpr *DR =
3304 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3305 if (isa<EnumConstantDecl>(DR->getDecl()))
3306 return false;
3307
3308 // Suppress cases where the '0' value is expanded from a macro.
3309 if (E->getLocStart().isMacroID())
3310 return false;
3311
John McCall323ed742010-05-06 08:58:33 +00003312 llvm::APSInt Value;
3313 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3314}
3315
John McCall372e1032010-10-06 00:25:24 +00003316static bool HasEnumType(Expr *E) {
3317 // Strip off implicit integral promotions.
3318 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003319 if (ICE->getCastKind() != CK_IntegralCast &&
3320 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003321 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003322 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003323 }
3324
3325 return E->getType()->isEnumeralType();
3326}
3327
John McCall323ed742010-05-06 08:58:33 +00003328void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003329 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003330 if (E->isValueDependent())
3331 return;
3332
John McCall2de56d12010-08-25 11:45:40 +00003333 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003334 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003335 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003336 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003337 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003338 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003339 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003340 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003341 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003342 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003343 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003344 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003345 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003346 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003347 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003348 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3349 }
3350}
3351
3352/// Analyze the operands of the given comparison. Implements the
3353/// fallback case from AnalyzeComparison.
3354void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003355 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3356 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003357}
John McCall51313c32010-01-04 23:31:57 +00003358
John McCallba26e582010-01-04 23:21:16 +00003359/// \brief Implements -Wsign-compare.
3360///
Richard Trieudd225092011-09-15 21:56:47 +00003361/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003362void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3363 // The type the comparison is being performed in.
3364 QualType T = E->getLHS()->getType();
3365 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3366 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003367
John McCall323ed742010-05-06 08:58:33 +00003368 // We don't do anything special if this isn't an unsigned integral
3369 // comparison: we're only interested in integral comparisons, and
3370 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003371 //
3372 // We also don't care about value-dependent expressions or expressions
3373 // whose result is a constant.
3374 if (!T->hasUnsignedIntegerRepresentation()
3375 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003376 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003377
Richard Trieudd225092011-09-15 21:56:47 +00003378 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3379 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003380
John McCall323ed742010-05-06 08:58:33 +00003381 // Check to see if one of the (unmodified) operands is of different
3382 // signedness.
3383 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003384 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3385 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003386 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003387 signedOperand = LHS;
3388 unsignedOperand = RHS;
3389 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3390 signedOperand = RHS;
3391 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003392 } else {
John McCall323ed742010-05-06 08:58:33 +00003393 CheckTrivialUnsignedComparison(S, E);
3394 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003395 }
3396
John McCall323ed742010-05-06 08:58:33 +00003397 // Otherwise, calculate the effective range of the signed operand.
3398 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003399
John McCall323ed742010-05-06 08:58:33 +00003400 // Go ahead and analyze implicit conversions in the operands. Note
3401 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003402 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3403 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003404
John McCall323ed742010-05-06 08:58:33 +00003405 // If the signed range is non-negative, -Wsign-compare won't fire,
3406 // but we should still check for comparisons which are always true
3407 // or false.
3408 if (signedRange.NonNegative)
3409 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003410
3411 // For (in)equality comparisons, if the unsigned operand is a
3412 // constant which cannot collide with a overflowed signed operand,
3413 // then reinterpreting the signed operand as unsigned will not
3414 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003415 if (E->isEqualityOp()) {
3416 unsigned comparisonWidth = S.Context.getIntWidth(T);
3417 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003418
John McCall323ed742010-05-06 08:58:33 +00003419 // We should never be unable to prove that the unsigned operand is
3420 // non-negative.
3421 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3422
3423 if (unsignedRange.Width < comparisonWidth)
3424 return;
3425 }
3426
3427 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003428 << LHS->getType() << RHS->getType()
3429 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003430}
3431
John McCall15d7d122010-11-11 03:21:53 +00003432/// Analyzes an attempt to assign the given value to a bitfield.
3433///
3434/// Returns true if there was something fishy about the attempt.
3435bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3436 SourceLocation InitLoc) {
3437 assert(Bitfield->isBitField());
3438 if (Bitfield->isInvalidDecl())
3439 return false;
3440
John McCall91b60142010-11-11 05:33:51 +00003441 // White-list bool bitfields.
3442 if (Bitfield->getType()->isBooleanType())
3443 return false;
3444
Douglas Gregor46ff3032011-02-04 13:09:01 +00003445 // Ignore value- or type-dependent expressions.
3446 if (Bitfield->getBitWidth()->isValueDependent() ||
3447 Bitfield->getBitWidth()->isTypeDependent() ||
3448 Init->isValueDependent() ||
3449 Init->isTypeDependent())
3450 return false;
3451
John McCall15d7d122010-11-11 03:21:53 +00003452 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3453
John McCall15d7d122010-11-11 03:21:53 +00003454 Expr::EvalResult InitValue;
Richard Smith51f47082011-10-29 00:50:52 +00003455 if (!OriginalInit->EvaluateAsRValue(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00003456 !InitValue.Val.isInt())
3457 return false;
3458
3459 const llvm::APSInt &Value = InitValue.Val.getInt();
3460 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003461 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003462
3463 if (OriginalWidth <= FieldWidth)
3464 return false;
3465
Jay Foad9f71a8f2010-12-07 08:25:34 +00003466 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003467
3468 // It's fairly common to write values into signed bitfields
3469 // that, if sign-extended, would end up becoming a different
3470 // value. We don't want to warn about that.
3471 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003472 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003473 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003474 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003475
3476 if (Value == TruncatedValue)
3477 return false;
3478
3479 std::string PrettyValue = Value.toString(10);
3480 std::string PrettyTrunc = TruncatedValue.toString(10);
3481
3482 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3483 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3484 << Init->getSourceRange();
3485
3486 return true;
3487}
3488
John McCallbeb22aa2010-11-09 23:24:47 +00003489/// Analyze the given simple or compound assignment for warning-worthy
3490/// operations.
3491void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3492 // Just recurse on the LHS.
3493 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3494
3495 // We want to recurse on the RHS as normal unless we're assigning to
3496 // a bitfield.
3497 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003498 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3499 E->getOperatorLoc())) {
3500 // Recurse, ignoring any implicit conversions on the RHS.
3501 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3502 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003503 }
3504 }
3505
3506 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3507}
3508
John McCall51313c32010-01-04 23:31:57 +00003509/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003510void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3511 SourceLocation CContext, unsigned diag) {
3512 S.Diag(E->getExprLoc(), diag)
3513 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3514}
3515
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003516/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3517void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3518 unsigned diag) {
3519 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3520}
3521
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003522/// Diagnose an implicit cast from a literal expression. Does not warn when the
3523/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003524void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3525 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003526 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003527 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003528 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003529 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3530 T->hasUnsignedIntegerRepresentation());
3531 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003532 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003533 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003534 return;
3535
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003536 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3537 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003538}
3539
John McCall091f23f2010-11-09 22:22:12 +00003540std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3541 if (!Range.Width) return "0";
3542
3543 llvm::APSInt ValueInRange = Value;
3544 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003545 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003546 return ValueInRange.toString(10);
3547}
3548
Ted Kremenekef9ff882011-03-10 20:03:42 +00003549static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3550 SourceManager &smgr = S.Context.getSourceManager();
3551 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3552}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003553
John McCall323ed742010-05-06 08:58:33 +00003554void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003555 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003556 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003557
John McCall323ed742010-05-06 08:58:33 +00003558 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3559 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3560 if (Source == Target) return;
3561 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003562
Chandler Carruth108f7562011-07-26 05:40:03 +00003563 // If the conversion context location is invalid don't complain. We also
3564 // don't want to emit a warning if the issue occurs from the expansion of
3565 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3566 // delay this check as long as possible. Once we detect we are in that
3567 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003568 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003569 return;
3570
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003571 // Diagnose implicit casts to bool.
3572 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3573 if (isa<StringLiteral>(E))
3574 // Warn on string literal to bool. Checks for string literals in logical
3575 // expressions, for instances, assert(0 && "error here"), is prevented
3576 // by a check in AnalyzeImplicitConversions().
3577 return DiagnoseImpCast(S, E, T, CC,
3578 diag::warn_impcast_string_literal_to_bool);
David Blaikiee37cdc42011-09-29 04:06:47 +00003579 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003580 }
John McCall51313c32010-01-04 23:31:57 +00003581
3582 // Strip vector types.
3583 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003584 if (!isa<VectorType>(Target)) {
3585 if (isFromSystemMacro(S, CC))
3586 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003587 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003588 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003589
3590 // If the vector cast is cast between two vectors of the same size, it is
3591 // a bitcast, not a conversion.
3592 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3593 return;
John McCall51313c32010-01-04 23:31:57 +00003594
3595 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3596 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3597 }
3598
3599 // Strip complex types.
3600 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003601 if (!isa<ComplexType>(Target)) {
3602 if (isFromSystemMacro(S, CC))
3603 return;
3604
John McCallb4eb64d2010-10-08 02:01:28 +00003605 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003606 }
John McCall51313c32010-01-04 23:31:57 +00003607
3608 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3609 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3610 }
3611
3612 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3613 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3614
3615 // If the source is floating point...
3616 if (SourceBT && SourceBT->isFloatingPoint()) {
3617 // ...and the target is floating point...
3618 if (TargetBT && TargetBT->isFloatingPoint()) {
3619 // ...then warn if we're dropping FP rank.
3620
3621 // Builtin FP kinds are ordered by increasing FP rank.
3622 if (SourceBT->getKind() > TargetBT->getKind()) {
3623 // Don't warn about float constants that are precisely
3624 // representable in the target type.
3625 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003626 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003627 // Value might be a float, a float vector, or a float complex.
3628 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003629 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3630 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003631 return;
3632 }
3633
Ted Kremenekef9ff882011-03-10 20:03:42 +00003634 if (isFromSystemMacro(S, CC))
3635 return;
3636
John McCallb4eb64d2010-10-08 02:01:28 +00003637 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003638 }
3639 return;
3640 }
3641
Ted Kremenekef9ff882011-03-10 20:03:42 +00003642 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003643 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003644 if (isFromSystemMacro(S, CC))
3645 return;
3646
Chandler Carrutha5b93322011-02-17 11:05:49 +00003647 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003648 // We also want to warn on, e.g., "int i = -1.234"
3649 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3650 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3651 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3652
Chandler Carruthf65076e2011-04-10 08:36:24 +00003653 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3654 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003655 } else {
3656 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3657 }
3658 }
John McCall51313c32010-01-04 23:31:57 +00003659
3660 return;
3661 }
3662
John McCallf2370c92010-01-06 05:24:50 +00003663 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003664 return;
3665
Richard Trieu1838ca52011-05-29 19:59:02 +00003666 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3667 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3668 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3669 << E->getSourceRange() << clang::SourceRange(CC);
3670 return;
3671 }
3672
John McCall323ed742010-05-06 08:58:33 +00003673 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003674 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003675
3676 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003677 // If the source is a constant, use a default-on diagnostic.
3678 // TODO: this should happen for bitfield stores, too.
3679 llvm::APSInt Value(32);
3680 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003681 if (isFromSystemMacro(S, CC))
3682 return;
3683
John McCall091f23f2010-11-09 22:22:12 +00003684 std::string PrettySourceValue = Value.toString(10);
3685 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3686
Ted Kremenek5e745da2011-10-22 02:37:33 +00003687 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3688 S.PDiag(diag::warn_impcast_integer_precision_constant)
3689 << PrettySourceValue << PrettyTargetValue
3690 << E->getType() << T << E->getSourceRange()
3691 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00003692 return;
3693 }
3694
Chris Lattnerb792b302011-06-14 04:51:15 +00003695 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003696 if (isFromSystemMacro(S, CC))
3697 return;
3698
John McCallf2370c92010-01-06 05:24:50 +00003699 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003700 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3701 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003702 }
3703
3704 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3705 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3706 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003707
3708 if (isFromSystemMacro(S, CC))
3709 return;
3710
John McCall323ed742010-05-06 08:58:33 +00003711 unsigned DiagID = diag::warn_impcast_integer_sign;
3712
3713 // Traditionally, gcc has warned about this under -Wsign-compare.
3714 // We also want to warn about it in -Wconversion.
3715 // So if -Wconversion is off, use a completely identical diagnostic
3716 // in the sign-compare group.
3717 // The conditional-checking code will
3718 if (ICContext) {
3719 DiagID = diag::warn_impcast_integer_sign_conditional;
3720 *ICContext = true;
3721 }
3722
John McCallb4eb64d2010-10-08 02:01:28 +00003723 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003724 }
3725
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003726 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003727 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3728 // type, to give us better diagnostics.
3729 QualType SourceType = E->getType();
3730 if (!S.getLangOptions().CPlusPlus) {
3731 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3732 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3733 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3734 SourceType = S.Context.getTypeDeclType(Enum);
3735 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3736 }
3737 }
3738
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003739 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3740 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3741 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003742 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003743 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003744 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003745 SourceEnum != TargetEnum) {
3746 if (isFromSystemMacro(S, CC))
3747 return;
3748
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003749 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003750 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003751 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003752
John McCall51313c32010-01-04 23:31:57 +00003753 return;
3754}
3755
John McCall323ed742010-05-06 08:58:33 +00003756void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3757
3758void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003759 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003760 E = E->IgnoreParenImpCasts();
3761
3762 if (isa<ConditionalOperator>(E))
3763 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3764
John McCallb4eb64d2010-10-08 02:01:28 +00003765 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003766 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003767 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003768 return;
3769}
3770
3771void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003772 SourceLocation CC = E->getQuestionLoc();
3773
3774 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003775
3776 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003777 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3778 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003779
3780 // If -Wconversion would have warned about either of the candidates
3781 // for a signedness conversion to the context type...
3782 if (!Suspicious) return;
3783
3784 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003785 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3786 CC))
John McCall323ed742010-05-06 08:58:33 +00003787 return;
3788
John McCall323ed742010-05-06 08:58:33 +00003789 // ...then check whether it would have warned about either of the
3790 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003791 if (E->getType() == T) return;
3792
3793 Suspicious = false;
3794 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3795 E->getType(), CC, &Suspicious);
3796 if (!Suspicious)
3797 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003798 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003799}
3800
3801/// AnalyzeImplicitConversions - Find and report any interesting
3802/// implicit conversions in the given expression. There are a couple
3803/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003804void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003805 QualType T = OrigE->getType();
3806 Expr *E = OrigE->IgnoreParenImpCasts();
3807
Douglas Gregorf8b6e152011-10-10 17:38:18 +00003808 if (E->isTypeDependent() || E->isValueDependent())
3809 return;
3810
John McCall323ed742010-05-06 08:58:33 +00003811 // For conditional operators, we analyze the arguments as if they
3812 // were being fed directly into the output.
3813 if (isa<ConditionalOperator>(E)) {
3814 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3815 CheckConditionalOperator(S, CO, T);
3816 return;
3817 }
3818
3819 // Go ahead and check any implicit conversions we might have skipped.
3820 // The non-canonical typecheck is just an optimization;
3821 // CheckImplicitConversion will filter out dead implicit conversions.
3822 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003823 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003824
3825 // Now continue drilling into this expression.
3826
3827 // Skip past explicit casts.
3828 if (isa<ExplicitCastExpr>(E)) {
3829 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003830 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003831 }
3832
John McCallbeb22aa2010-11-09 23:24:47 +00003833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3834 // Do a somewhat different check with comparison operators.
3835 if (BO->isComparisonOp())
3836 return AnalyzeComparison(S, BO);
3837
3838 // And with assignments and compound assignments.
3839 if (BO->isAssignmentOp())
3840 return AnalyzeAssignment(S, BO);
3841 }
John McCall323ed742010-05-06 08:58:33 +00003842
3843 // These break the otherwise-useful invariant below. Fortunately,
3844 // we don't really need to recurse into them, because any internal
3845 // expressions should have been analyzed already when they were
3846 // built into statements.
3847 if (isa<StmtExpr>(E)) return;
3848
3849 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003850 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003851
3852 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003853 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003854 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3855 bool IsLogicalOperator = BO && BO->isLogicalOp();
3856 for (Stmt::child_range I = E->children(); I; ++I) {
3857 Expr *ChildExpr = cast<Expr>(*I);
3858 if (IsLogicalOperator &&
3859 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3860 // Ignore checking string literals that are in logical operators.
3861 continue;
3862 AnalyzeImplicitConversions(S, ChildExpr, CC);
3863 }
John McCall323ed742010-05-06 08:58:33 +00003864}
3865
3866} // end anonymous namespace
3867
3868/// Diagnoses "dangerous" implicit conversions within the given
3869/// expression (which is a full expression). Implements -Wconversion
3870/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003871///
3872/// \param CC the "context" location of the implicit conversion, i.e.
3873/// the most location of the syntactic entity requiring the implicit
3874/// conversion
3875void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003876 // Don't diagnose in unevaluated contexts.
3877 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3878 return;
3879
3880 // Don't diagnose for value- or type-dependent expressions.
3881 if (E->isTypeDependent() || E->isValueDependent())
3882 return;
3883
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003884 // Check for array bounds violations in cases where the check isn't triggered
3885 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3886 // ArraySubscriptExpr is on the RHS of a variable initialization.
3887 CheckArrayAccess(E);
3888
John McCallb4eb64d2010-10-08 02:01:28 +00003889 // This is not the right CC for (e.g.) a variable initialization.
3890 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003891}
3892
John McCall15d7d122010-11-11 03:21:53 +00003893void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3894 FieldDecl *BitField,
3895 Expr *Init) {
3896 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3897}
3898
Mike Stumpf8c49212010-01-21 03:59:47 +00003899/// CheckParmsForFunctionDef - Check that the parameters of the given
3900/// function are appropriate for the definition of a function. This
3901/// takes care of any checks that cannot be performed on the
3902/// declaration itself, e.g., that the types of each of the function
3903/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003904bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3905 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003906 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003907 for (; P != PEnd; ++P) {
3908 ParmVarDecl *Param = *P;
3909
Mike Stumpf8c49212010-01-21 03:59:47 +00003910 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3911 // function declarator that is part of a function definition of
3912 // that function shall not have incomplete type.
3913 //
3914 // This is also C++ [dcl.fct]p6.
3915 if (!Param->isInvalidDecl() &&
3916 RequireCompleteType(Param->getLocation(), Param->getType(),
3917 diag::err_typecheck_decl_incomplete_type)) {
3918 Param->setInvalidDecl();
3919 HasInvalidParm = true;
3920 }
3921
3922 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3923 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003924 if (CheckParameterNames &&
3925 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003926 !Param->isImplicit() &&
3927 !getLangOptions().CPlusPlus)
3928 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003929
3930 // C99 6.7.5.3p12:
3931 // If the function declarator is not part of a definition of that
3932 // function, parameters may have incomplete type and may use the [*]
3933 // notation in their sequences of declarator specifiers to specify
3934 // variable length array types.
3935 QualType PType = Param->getOriginalType();
3936 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3937 if (AT->getSizeModifier() == ArrayType::Star) {
3938 // FIXME: This diagnosic should point the the '[*]' if source-location
3939 // information is added for it.
3940 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3941 }
3942 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003943 }
3944
3945 return HasInvalidParm;
3946}
John McCallb7f4ffe2010-08-12 21:44:57 +00003947
3948/// CheckCastAlign - Implements -Wcast-align, which warns when a
3949/// pointer cast increases the alignment requirements.
3950void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3951 // This is actually a lot of work to potentially be doing on every
3952 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003953 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3954 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00003955 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00003956 return;
3957
3958 // Ignore dependent types.
3959 if (T->isDependentType() || Op->getType()->isDependentType())
3960 return;
3961
3962 // Require that the destination be a pointer type.
3963 const PointerType *DestPtr = T->getAs<PointerType>();
3964 if (!DestPtr) return;
3965
3966 // If the destination has alignment 1, we're done.
3967 QualType DestPointee = DestPtr->getPointeeType();
3968 if (DestPointee->isIncompleteType()) return;
3969 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3970 if (DestAlign.isOne()) return;
3971
3972 // Require that the source be a pointer type.
3973 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3974 if (!SrcPtr) return;
3975 QualType SrcPointee = SrcPtr->getPointeeType();
3976
3977 // Whitelist casts from cv void*. We already implicitly
3978 // whitelisted casts to cv void*, since they have alignment 1.
3979 // Also whitelist casts involving incomplete types, which implicitly
3980 // includes 'void'.
3981 if (SrcPointee->isIncompleteType()) return;
3982
3983 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3984 if (SrcAlign >= DestAlign) return;
3985
3986 Diag(TRange.getBegin(), diag::warn_cast_align)
3987 << Op->getType() << T
3988 << static_cast<unsigned>(SrcAlign.getQuantity())
3989 << static_cast<unsigned>(DestAlign.getQuantity())
3990 << TRange << Op->getSourceRange();
3991}
3992
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003993static const Type* getElementType(const Expr *BaseExpr) {
3994 const Type* EltType = BaseExpr->getType().getTypePtr();
3995 if (EltType->isAnyPointerType())
3996 return EltType->getPointeeType().getTypePtr();
3997 else if (EltType->isArrayType())
3998 return EltType->getBaseElementTypeUnsafe();
3999 return EltType;
4000}
4001
Chandler Carruthc2684342011-08-05 09:10:50 +00004002/// \brief Check whether this array fits the idiom of a size-one tail padded
4003/// array member of a struct.
4004///
4005/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4006/// commonly used to emulate flexible arrays in C89 code.
4007static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4008 const NamedDecl *ND) {
4009 if (Size != 1 || !ND) return false;
4010
4011 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4012 if (!FD) return false;
4013
4014 // Don't consider sizes resulting from macro expansions or template argument
4015 // substitution to form C89 tail-padded arrays.
4016 ConstantArrayTypeLoc TL =
4017 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4018 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4019 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4020 return false;
4021
4022 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
4023 if (!RD || !RD->isStruct())
4024 return false;
4025
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004026 // See if this is the last field decl in the record.
4027 const Decl *D = FD;
4028 while ((D = D->getNextDeclInContext()))
4029 if (isa<FieldDecl>(D))
4030 return false;
4031 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004032}
4033
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004034void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
4035 bool isSubscript, bool AllowOnePastEnd) {
4036 const Type* EffectiveType = getElementType(BaseExpr);
4037 BaseExpr = BaseExpr->IgnoreParenCasts();
4038 IndexExpr = IndexExpr->IgnoreParenCasts();
4039
Chandler Carruth34064582011-02-17 20:55:08 +00004040 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004041 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004042 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004043 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004044
Chandler Carruth34064582011-02-17 20:55:08 +00004045 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00004046 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004047 llvm::APSInt index;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004048 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004049 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004050
Chandler Carruthba447122011-08-05 08:07:29 +00004051 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004052 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4053 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004054 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004055 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004056
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004057 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004058 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004059 if (!size.isStrictlyPositive())
4060 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004061
4062 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004063 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004064 // Make sure we're comparing apples to apples when comparing index to size
4065 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4066 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004067 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004068 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004069 if (ptrarith_typesize != array_typesize) {
4070 // There's a cast to a different size type involved
4071 uint64_t ratio = array_typesize / ptrarith_typesize;
4072 // TODO: Be smarter about handling cases where array_typesize is not a
4073 // multiple of ptrarith_typesize
4074 if (ptrarith_typesize * ratio == array_typesize)
4075 size *= llvm::APInt(size.getBitWidth(), ratio);
4076 }
4077 }
4078
Chandler Carruth34064582011-02-17 20:55:08 +00004079 if (size.getBitWidth() > index.getBitWidth())
4080 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004081 else if (size.getBitWidth() < index.getBitWidth())
4082 size = size.sext(index.getBitWidth());
4083
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004084 // For array subscripting the index must be less than size, but for pointer
4085 // arithmetic also allow the index (offset) to be equal to size since
4086 // computing the next address after the end of the array is legal and
4087 // commonly done e.g. in C++ iterators and range-based for loops.
4088 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004089 return;
4090
4091 // Also don't warn for arrays of size 1 which are members of some
4092 // structure. These are often used to approximate flexible arrays in C89
4093 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004094 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004095 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004096
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004097 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
4098 if (isSubscript)
4099 DiagID = diag::warn_array_index_exceeds_bounds;
4100
4101 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4102 PDiag(DiagID) << index.toString(10, true)
4103 << size.toString(10, true)
4104 << (unsigned)size.getLimitedValue(~0U)
4105 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004106 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004107 unsigned DiagID = diag::warn_array_index_precedes_bounds;
4108 if (!isSubscript) {
4109 DiagID = diag::warn_ptr_arith_precedes_bounds;
4110 if (index.isNegative()) index = -index;
4111 }
4112
4113 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4114 PDiag(DiagID) << index.toString(10, true)
4115 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004116 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004117
Chandler Carruth35001ca2011-02-17 21:10:52 +00004118 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004119 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4120 PDiag(diag::note_array_index_out_of_bounds)
4121 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004122}
4123
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004124void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004125 int AllowOnePastEnd = 0;
4126 while (expr) {
4127 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004128 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004129 case Stmt::ArraySubscriptExprClass: {
4130 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4131 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
4132 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004133 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004134 }
4135 case Stmt::UnaryOperatorClass: {
4136 // Only unwrap the * and & unary operators
4137 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4138 expr = UO->getSubExpr();
4139 switch (UO->getOpcode()) {
4140 case UO_AddrOf:
4141 AllowOnePastEnd++;
4142 break;
4143 case UO_Deref:
4144 AllowOnePastEnd--;
4145 break;
4146 default:
4147 return;
4148 }
4149 break;
4150 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004151 case Stmt::ConditionalOperatorClass: {
4152 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4153 if (const Expr *lhs = cond->getLHS())
4154 CheckArrayAccess(lhs);
4155 if (const Expr *rhs = cond->getRHS())
4156 CheckArrayAccess(rhs);
4157 return;
4158 }
4159 default:
4160 return;
4161 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004162 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004163}
John McCallf85e1932011-06-15 23:02:42 +00004164
4165//===--- CHECK: Objective-C retain cycles ----------------------------------//
4166
4167namespace {
4168 struct RetainCycleOwner {
4169 RetainCycleOwner() : Variable(0), Indirect(false) {}
4170 VarDecl *Variable;
4171 SourceRange Range;
4172 SourceLocation Loc;
4173 bool Indirect;
4174
4175 void setLocsFrom(Expr *e) {
4176 Loc = e->getExprLoc();
4177 Range = e->getSourceRange();
4178 }
4179 };
4180}
4181
4182/// Consider whether capturing the given variable can possibly lead to
4183/// a retain cycle.
4184static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4185 // In ARC, it's captured strongly iff the variable has __strong
4186 // lifetime. In MRR, it's captured strongly if the variable is
4187 // __block and has an appropriate type.
4188 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4189 return false;
4190
4191 owner.Variable = var;
4192 owner.setLocsFrom(ref);
4193 return true;
4194}
4195
4196static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4197 while (true) {
4198 e = e->IgnoreParens();
4199 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4200 switch (cast->getCastKind()) {
4201 case CK_BitCast:
4202 case CK_LValueBitCast:
4203 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004204 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004205 e = cast->getSubExpr();
4206 continue;
4207
John McCallf85e1932011-06-15 23:02:42 +00004208 default:
4209 return false;
4210 }
4211 }
4212
4213 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4214 ObjCIvarDecl *ivar = ref->getDecl();
4215 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4216 return false;
4217
4218 // Try to find a retain cycle in the base.
4219 if (!findRetainCycleOwner(ref->getBase(), owner))
4220 return false;
4221
4222 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4223 owner.Indirect = true;
4224 return true;
4225 }
4226
4227 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4228 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4229 if (!var) return false;
4230 return considerVariable(var, ref, owner);
4231 }
4232
4233 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4234 owner.Variable = ref->getDecl();
4235 owner.setLocsFrom(ref);
4236 return true;
4237 }
4238
4239 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4240 if (member->isArrow()) return false;
4241
4242 // Don't count this as an indirect ownership.
4243 e = member->getBase();
4244 continue;
4245 }
4246
John McCall4b9c2d22011-11-06 09:01:30 +00004247 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4248 // Only pay attention to pseudo-objects on property references.
4249 ObjCPropertyRefExpr *pre
4250 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4251 ->IgnoreParens());
4252 if (!pre) return false;
4253 if (pre->isImplicitProperty()) return false;
4254 ObjCPropertyDecl *property = pre->getExplicitProperty();
4255 if (!property->isRetaining() &&
4256 !(property->getPropertyIvarDecl() &&
4257 property->getPropertyIvarDecl()->getType()
4258 .getObjCLifetime() == Qualifiers::OCL_Strong))
4259 return false;
4260
4261 owner.Indirect = true;
4262 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4263 ->getSourceExpr());
4264 continue;
4265 }
4266
John McCallf85e1932011-06-15 23:02:42 +00004267 // Array ivars?
4268
4269 return false;
4270 }
4271}
4272
4273namespace {
4274 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4275 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4276 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4277 Variable(variable), Capturer(0) {}
4278
4279 VarDecl *Variable;
4280 Expr *Capturer;
4281
4282 void VisitDeclRefExpr(DeclRefExpr *ref) {
4283 if (ref->getDecl() == Variable && !Capturer)
4284 Capturer = ref;
4285 }
4286
4287 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4288 if (ref->getDecl() == Variable && !Capturer)
4289 Capturer = ref;
4290 }
4291
4292 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4293 if (Capturer) return;
4294 Visit(ref->getBase());
4295 if (Capturer && ref->isFreeIvar())
4296 Capturer = ref;
4297 }
4298
4299 void VisitBlockExpr(BlockExpr *block) {
4300 // Look inside nested blocks
4301 if (block->getBlockDecl()->capturesVariable(Variable))
4302 Visit(block->getBlockDecl()->getBody());
4303 }
4304 };
4305}
4306
4307/// Check whether the given argument is a block which captures a
4308/// variable.
4309static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4310 assert(owner.Variable && owner.Loc.isValid());
4311
4312 e = e->IgnoreParenCasts();
4313 BlockExpr *block = dyn_cast<BlockExpr>(e);
4314 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4315 return 0;
4316
4317 FindCaptureVisitor visitor(S.Context, owner.Variable);
4318 visitor.Visit(block->getBlockDecl()->getBody());
4319 return visitor.Capturer;
4320}
4321
4322static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4323 RetainCycleOwner &owner) {
4324 assert(capturer);
4325 assert(owner.Variable && owner.Loc.isValid());
4326
4327 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4328 << owner.Variable << capturer->getSourceRange();
4329 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4330 << owner.Indirect << owner.Range;
4331}
4332
4333/// Check for a keyword selector that starts with the word 'add' or
4334/// 'set'.
4335static bool isSetterLikeSelector(Selector sel) {
4336 if (sel.isUnarySelector()) return false;
4337
Chris Lattner5f9e2722011-07-23 10:55:15 +00004338 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004339 while (!str.empty() && str.front() == '_') str = str.substr(1);
4340 if (str.startswith("set") || str.startswith("add"))
4341 str = str.substr(3);
4342 else
4343 return false;
4344
4345 if (str.empty()) return true;
4346 return !islower(str.front());
4347}
4348
4349/// Check a message send to see if it's likely to cause a retain cycle.
4350void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4351 // Only check instance methods whose selector looks like a setter.
4352 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4353 return;
4354
4355 // Try to find a variable that the receiver is strongly owned by.
4356 RetainCycleOwner owner;
4357 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4358 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4359 return;
4360 } else {
4361 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4362 owner.Variable = getCurMethodDecl()->getSelfDecl();
4363 owner.Loc = msg->getSuperLoc();
4364 owner.Range = msg->getSuperLoc();
4365 }
4366
4367 // Check whether the receiver is captured by any of the arguments.
4368 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4369 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4370 return diagnoseRetainCycle(*this, capturer, owner);
4371}
4372
4373/// Check a property assign to see if it's likely to cause a retain cycle.
4374void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4375 RetainCycleOwner owner;
4376 if (!findRetainCycleOwner(receiver, owner))
4377 return;
4378
4379 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4380 diagnoseRetainCycle(*this, capturer, owner);
4381}
4382
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004383bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004384 QualType LHS, Expr *RHS) {
4385 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4386 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004387 return false;
4388 // strip off any implicit cast added to get to the one arc-specific
4389 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004390 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004391 Diag(Loc, diag::warn_arc_retained_assign)
4392 << (LT == Qualifiers::OCL_ExplicitNone)
4393 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004394 return true;
4395 }
4396 RHS = cast->getSubExpr();
4397 }
4398 return false;
John McCallf85e1932011-06-15 23:02:42 +00004399}
4400
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004401void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4402 Expr *LHS, Expr *RHS) {
4403 QualType LHSType = LHS->getType();
4404 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4405 return;
4406 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4407 // FIXME. Check for other life times.
4408 if (LT != Qualifiers::OCL_None)
4409 return;
4410
John McCall3c3b7f92011-10-25 17:37:35 +00004411 if (ObjCPropertyRefExpr *PRE
4412 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004413 if (PRE->isImplicitProperty())
4414 return;
4415 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4416 if (!PD)
4417 return;
4418
4419 unsigned Attributes = PD->getPropertyAttributes();
4420 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4421 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004422 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004423 Diag(Loc, diag::warn_arc_retained_property_assign)
4424 << RHS->getSourceRange();
4425 return;
4426 }
4427 RHS = cast->getSubExpr();
4428 }
4429 }
4430}