blob: d6aa4ce88527296353a82c494e1c30df11cdb413 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Sema.h"
John McCall83024632010-08-25 22:03:47 +000016#include "clang/Sema/SemaInternal.h"
John McCallaab3e412010-08-25 08:40:02 +000017#include "clang/Sema/ScopeInfo.h"
Ted Kremenek02087932010-07-16 02:11:22 +000018#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000019#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000020#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000021#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000023#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000024#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/DeclObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000028#include "clang/Lex/Preprocessor.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000029#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/STLExtras.h"
Tom Careb7042702010-06-09 04:11:11 +000031#include "llvm/Support/raw_ostream.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000032#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000033#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian56603ef2010-09-07 19:38:13 +000034#include "clang/Basic/ConvertUTF.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000035#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000036using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000037using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000038
Chris Lattnera26fb342009-02-18 17:49:48 +000039SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
40 unsigned ByteNo) const {
Chris Lattnere925d612010-11-17 07:37:15 +000041 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
42 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000043}
Chris Lattnere925d612010-11-17 07:37:15 +000044
Chris Lattnera26fb342009-02-18 17:49:48 +000045
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +000046/// CheckablePrintfAttr - does a function call have a "printf" attribute
47/// and arguments that merit checking?
48bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
49 if (Format->getType() == "printf") return true;
50 if (Format->getType() == "printf0") {
51 // printf0 allows null "format" string; if so don't check format/args
52 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl6eedcc12009-11-17 18:02:24 +000053 // Does the index refer to the implicit object argument?
54 if (isa<CXXMemberCallExpr>(TheCall)) {
55 if (format_idx == 0)
56 return false;
57 --format_idx;
58 }
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +000059 if (format_idx < TheCall->getNumArgs()) {
60 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekd1668192010-02-27 01:41:03 +000061 if (!Format->isNullPointerConstant(Context,
62 Expr::NPC_ValueDependentIsNull))
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +000063 return true;
64 }
65 }
66 return false;
67}
Chris Lattnera26fb342009-02-18 17:49:48 +000068
John McCalldadc5752010-08-24 06:29:42 +000069ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +000070Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +000071 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +000072
Chris Lattner3be167f2010-10-01 23:23:24 +000073 // Find out if any arguments are required to be integer constant expressions.
74 unsigned ICEArguments = 0;
75 ASTContext::GetBuiltinTypeError Error;
76 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
77 if (Error != ASTContext::GE_None)
78 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
79
80 // If any arguments are required to be ICE's, check and diagnose.
81 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
82 // Skip arguments not required to be ICE's.
83 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
84
85 llvm::APSInt Result;
86 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
87 return true;
88 ICEArguments &= ~(1 << ArgNo);
89 }
90
Anders Carlssonbc4c1072009-08-16 01:56:34 +000091 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +000092 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +000093 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +000094 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +000095 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +000096 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +000097 break;
Ted Kremeneka174c522008-07-09 17:58:53 +000098 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +000099 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000100 if (SemaBuiltinVAStart(TheCall))
101 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000102 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000103 case Builtin::BI__builtin_isgreater:
104 case Builtin::BI__builtin_isgreaterequal:
105 case Builtin::BI__builtin_isless:
106 case Builtin::BI__builtin_islessequal:
107 case Builtin::BI__builtin_islessgreater:
108 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000109 if (SemaBuiltinUnorderedCompare(TheCall))
110 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000111 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000112 case Builtin::BI__builtin_fpclassify:
113 if (SemaBuiltinFPClassification(TheCall, 6))
114 return ExprError();
115 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000116 case Builtin::BI__builtin_isfinite:
117 case Builtin::BI__builtin_isinf:
118 case Builtin::BI__builtin_isinf_sign:
119 case Builtin::BI__builtin_isnan:
120 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000121 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000122 return ExprError();
123 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000124 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000125 return SemaBuiltinShuffleVector(TheCall);
126 // TheCall will be freed by the smart pointer here, but that's fine, since
127 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000128 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000129 if (SemaBuiltinPrefetch(TheCall))
130 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000131 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000132 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000133 if (SemaBuiltinObjectSize(TheCall))
134 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000135 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000136 case Builtin::BI__builtin_longjmp:
137 if (SemaBuiltinLongjmp(TheCall))
138 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000139 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000140 case Builtin::BI__builtin_constant_p:
141 if (TheCall->getNumArgs() == 0)
142 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
143 << 0 /*function call*/ << 1 << 0 << TheCall->getSourceRange();
144 if (TheCall->getNumArgs() > 1)
145 return Diag(TheCall->getArg(1)->getLocStart(),
146 diag::err_typecheck_call_too_many_args)
147 << 0 /*function call*/ << 1 << TheCall->getNumArgs()
148 << TheCall->getArg(1)->getSourceRange();
149 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000150 case Builtin::BI__sync_fetch_and_add:
151 case Builtin::BI__sync_fetch_and_sub:
152 case Builtin::BI__sync_fetch_and_or:
153 case Builtin::BI__sync_fetch_and_and:
154 case Builtin::BI__sync_fetch_and_xor:
155 case Builtin::BI__sync_add_and_fetch:
156 case Builtin::BI__sync_sub_and_fetch:
157 case Builtin::BI__sync_and_and_fetch:
158 case Builtin::BI__sync_or_and_fetch:
159 case Builtin::BI__sync_xor_and_fetch:
160 case Builtin::BI__sync_val_compare_and_swap:
161 case Builtin::BI__sync_bool_compare_and_swap:
162 case Builtin::BI__sync_lock_test_and_set:
163 case Builtin::BI__sync_lock_release:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000164 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman4904e322010-06-08 02:47:44 +0000165 }
166
167 // Since the target specific builtins for each arch overlap, only check those
168 // of the arch we are compiling for.
169 if (BuiltinID >= Builtin::FirstTSBuiltin) {
170 switch (Context.Target.getTriple().getArch()) {
171 case llvm::Triple::arm:
172 case llvm::Triple::thumb:
173 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
174 return ExprError();
175 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000176 default:
177 break;
178 }
179 }
180
181 return move(TheCallResult);
182}
183
Nate Begeman91e1fea2010-06-14 05:21:25 +0000184// Get the valid immediate range for the specified NEON type code.
185static unsigned RFT(unsigned t, bool shift = false) {
186 bool quad = t & 0x10;
187
188 switch (t & 0x7) {
189 case 0: // i8
Nate Begemandbafec12010-06-17 02:26:59 +0000190 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000191 case 1: // i16
Nate Begemandbafec12010-06-17 02:26:59 +0000192 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000193 case 2: // i32
Nate Begemandbafec12010-06-17 02:26:59 +0000194 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000195 case 3: // i64
Nate Begemandbafec12010-06-17 02:26:59 +0000196 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000197 case 4: // f32
198 assert(!shift && "cannot shift float types!");
Nate Begemandbafec12010-06-17 02:26:59 +0000199 return (2 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000200 case 5: // poly8
201 assert(!shift && "cannot shift polynomial types!");
Nate Begemandbafec12010-06-17 02:26:59 +0000202 return (8 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000203 case 6: // poly16
204 assert(!shift && "cannot shift polynomial types!");
Nate Begemandbafec12010-06-17 02:26:59 +0000205 return (4 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000206 case 7: // float16
207 assert(!shift && "cannot shift float types!");
Nate Begemandbafec12010-06-17 02:26:59 +0000208 return (4 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000209 }
210 return 0;
211}
212
Nate Begeman4904e322010-06-08 02:47:44 +0000213bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000214 llvm::APSInt Result;
215
Nate Begemand773fe62010-06-13 04:47:52 +0000216 unsigned mask = 0;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000217 unsigned TV = 0;
Nate Begeman55483092010-06-09 01:10:23 +0000218 switch (BuiltinID) {
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000219#define GET_NEON_OVERLOAD_CHECK
220#include "clang/Basic/arm_neon.inc"
221#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman55483092010-06-09 01:10:23 +0000222 }
223
Nate Begemand773fe62010-06-13 04:47:52 +0000224 // For NEON intrinsics which are overloaded on vector element type, validate
225 // the immediate which specifies which variant to emit.
226 if (mask) {
227 unsigned ArgNo = TheCall->getNumArgs()-1;
228 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
229 return true;
230
Nate Begeman91e1fea2010-06-14 05:21:25 +0000231 TV = Result.getLimitedValue(32);
232 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begemand773fe62010-06-13 04:47:52 +0000233 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
234 << TheCall->getArg(ArgNo)->getSourceRange();
235 }
Nate Begeman55483092010-06-09 01:10:23 +0000236
Nate Begemand773fe62010-06-13 04:47:52 +0000237 // For NEON intrinsics which take an immediate value as part of the
238 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000239 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000240 switch (BuiltinID) {
241 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000242 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
243 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000244 case ARM::BI__builtin_arm_vcvtr_f:
245 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000246#define GET_NEON_IMMEDIATE_CHECK
247#include "clang/Basic/arm_neon.inc"
248#undef GET_NEON_IMMEDIATE_CHECK
Nate Begemand773fe62010-06-13 04:47:52 +0000249 };
250
Nate Begeman91e1fea2010-06-14 05:21:25 +0000251 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000252 if (SemaBuiltinConstantArg(TheCall, i, Result))
253 return true;
254
Nate Begeman91e1fea2010-06-14 05:21:25 +0000255 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000256 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000257 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000258 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000259 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000260
Nate Begemanf568b072010-08-03 21:32:34 +0000261 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000262 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000263}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000264
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000265/// CheckFunctionCall - Check a direct function call for various correctness
266/// and safety properties not strictly enforced by the C type system.
267bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
268 // Get the IdentifierInfo* for the called function.
269 IdentifierInfo *FnInfo = FDecl->getIdentifier();
270
271 // None of the checks below are needed for functions that don't have
272 // simple names (e.g., C++ conversion functions).
273 if (!FnInfo)
274 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000275
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000276 // FIXME: This mechanism should be abstracted to be less fragile and
277 // more efficient. For example, just map function ids to custom
278 // handlers.
279
Ted Kremenekb8176da2010-09-09 04:33:05 +0000280 // Printf and scanf checking.
281 for (specific_attr_iterator<FormatAttr>
282 i = FDecl->specific_attr_begin<FormatAttr>(),
283 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
284
285 const FormatAttr *Format = *i;
Ted Kremenek02087932010-07-16 02:11:22 +0000286 const bool b = Format->getType() == "scanf";
287 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek9723bcf2009-02-27 17:58:43 +0000288 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek02087932010-07-16 02:11:22 +0000289 CheckPrintfScanfArguments(TheCall, HasVAListArg,
290 Format->getFormatIdx() - 1,
291 HasVAListArg ? 0 : Format->getFirstArg() - 1,
292 !b);
Douglas Gregore711f702009-02-14 18:57:46 +0000293 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000294 }
Mike Stump11289f42009-09-09 15:08:12 +0000295
Ted Kremenekb8176da2010-09-09 04:33:05 +0000296 for (specific_attr_iterator<NonNullAttr>
297 i = FDecl->specific_attr_begin<NonNullAttr>(),
298 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000299 CheckNonNullArguments(*i, TheCall);
Ted Kremenekb8176da2010-09-09 04:33:05 +0000300 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000301
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000302 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000303}
304
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000305bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000306 // Printf checking.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000307 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000308 if (!Format)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000309 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000310
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000311 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
312 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000313 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000314
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000315 QualType Ty = V->getType();
316 if (!Ty->isBlockPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000317 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000318
Ted Kremenek02087932010-07-16 02:11:22 +0000319 const bool b = Format->getType() == "scanf";
320 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000321 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000322
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000323 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek02087932010-07-16 02:11:22 +0000324 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
325 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000326
327 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000328}
329
Chris Lattnerdc046542009-05-08 06:58:22 +0000330/// SemaBuiltinAtomicOverloaded - We have a call to a function like
331/// __sync_fetch_and_add, which is an overloaded function based on the pointer
332/// type of its first argument. The main ActOnCallExpr routines have already
333/// promoted the types of arguments because all of these calls are prototyped as
334/// void(...).
335///
336/// This function goes through and does final semantic checking for these
337/// builtins,
John McCalldadc5752010-08-24 06:29:42 +0000338ExprResult
339Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000340 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +0000341 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
342 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
343
344 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000345 if (TheCall->getNumArgs() < 1) {
346 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
347 << 0 << 1 << TheCall->getNumArgs()
348 << TheCall->getCallee()->getSourceRange();
349 return ExprError();
350 }
Mike Stump11289f42009-09-09 15:08:12 +0000351
Chris Lattnerdc046542009-05-08 06:58:22 +0000352 // Inspect the first argument of the atomic builtin. This should always be
353 // a pointer type, whose element is an integral scalar or pointer type.
354 // Because it is a pointer type, we don't have to worry about any implicit
355 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000356 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +0000357 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000358 if (!FirstArg->getType()->isPointerType()) {
359 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
360 << FirstArg->getType() << FirstArg->getSourceRange();
361 return ExprError();
362 }
Mike Stump11289f42009-09-09 15:08:12 +0000363
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000364 QualType ValType =
365 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +0000366 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000367 !ValType->isBlockPointerType()) {
368 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
369 << FirstArg->getType() << FirstArg->getSourceRange();
370 return ExprError();
371 }
Chris Lattnerdc046542009-05-08 06:58:22 +0000372
Chandler Carruth3973af72010-07-18 20:54:12 +0000373 // The majority of builtins return a value, but a few have special return
374 // types, so allow them to override appropriately below.
375 QualType ResultType = ValType;
376
Chris Lattnerdc046542009-05-08 06:58:22 +0000377 // We need to figure out which concrete builtin this maps onto. For example,
378 // __sync_fetch_and_add with a 2 byte object turns into
379 // __sync_fetch_and_add_2.
380#define BUILTIN_ROW(x) \
381 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
382 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +0000383
Chris Lattnerdc046542009-05-08 06:58:22 +0000384 static const unsigned BuiltinIndices[][5] = {
385 BUILTIN_ROW(__sync_fetch_and_add),
386 BUILTIN_ROW(__sync_fetch_and_sub),
387 BUILTIN_ROW(__sync_fetch_and_or),
388 BUILTIN_ROW(__sync_fetch_and_and),
389 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +0000390
Chris Lattnerdc046542009-05-08 06:58:22 +0000391 BUILTIN_ROW(__sync_add_and_fetch),
392 BUILTIN_ROW(__sync_sub_and_fetch),
393 BUILTIN_ROW(__sync_and_and_fetch),
394 BUILTIN_ROW(__sync_or_and_fetch),
395 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +0000396
Chris Lattnerdc046542009-05-08 06:58:22 +0000397 BUILTIN_ROW(__sync_val_compare_and_swap),
398 BUILTIN_ROW(__sync_bool_compare_and_swap),
399 BUILTIN_ROW(__sync_lock_test_and_set),
400 BUILTIN_ROW(__sync_lock_release)
401 };
Mike Stump11289f42009-09-09 15:08:12 +0000402#undef BUILTIN_ROW
403
Chris Lattnerdc046542009-05-08 06:58:22 +0000404 // Determine the index of the size.
405 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +0000406 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000407 case 1: SizeIndex = 0; break;
408 case 2: SizeIndex = 1; break;
409 case 4: SizeIndex = 2; break;
410 case 8: SizeIndex = 3; break;
411 case 16: SizeIndex = 4; break;
412 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000413 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
414 << FirstArg->getType() << FirstArg->getSourceRange();
415 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +0000416 }
Mike Stump11289f42009-09-09 15:08:12 +0000417
Chris Lattnerdc046542009-05-08 06:58:22 +0000418 // Each of these builtins has one pointer argument, followed by some number of
419 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
420 // that we ignore. Find out which row of BuiltinIndices to read from as well
421 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +0000422 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +0000423 unsigned BuiltinIndex, NumFixed = 1;
424 switch (BuiltinID) {
425 default: assert(0 && "Unknown overloaded atomic builtin!");
426 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
427 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
428 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
429 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
430 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump11289f42009-09-09 15:08:12 +0000431
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000432 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
433 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
434 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
435 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
436 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump11289f42009-09-09 15:08:12 +0000437
Chris Lattnerdc046542009-05-08 06:58:22 +0000438 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000439 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +0000440 NumFixed = 2;
441 break;
442 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000443 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +0000444 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +0000445 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000446 break;
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000447 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000448 case Builtin::BI__sync_lock_release:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000449 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +0000450 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +0000451 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000452 break;
453 }
Mike Stump11289f42009-09-09 15:08:12 +0000454
Chris Lattnerdc046542009-05-08 06:58:22 +0000455 // Now that we know how many fixed arguments we expect, first check that we
456 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000457 if (TheCall->getNumArgs() < 1+NumFixed) {
458 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
459 << 0 << 1+NumFixed << TheCall->getNumArgs()
460 << TheCall->getCallee()->getSourceRange();
461 return ExprError();
462 }
Mike Stump11289f42009-09-09 15:08:12 +0000463
Chris Lattner5b9241b2009-05-08 15:36:58 +0000464 // Get the decl for the concrete builtin from this, we can tell what the
465 // concrete integer type we should convert to is.
466 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
467 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
468 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump11289f42009-09-09 15:08:12 +0000469 FunctionDecl *NewBuiltinDecl =
Chris Lattner5b9241b2009-05-08 15:36:58 +0000470 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
471 TUScope, false, DRE->getLocStart()));
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000472
John McCallcf142162010-08-07 06:22:56 +0000473 // The first argument --- the pointer --- has a fixed type; we
474 // deduce the types of the rest of the arguments accordingly. Walk
475 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +0000476 for (unsigned i = 0; i != NumFixed; ++i) {
477 Expr *Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +0000478
Chris Lattnerdc046542009-05-08 06:58:22 +0000479 // If the argument is an implicit cast, then there was a promotion due to
480 // "...", just remove it now.
481 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
482 Arg = ICE->getSubExpr();
483 ICE->setSubExpr(0);
Chris Lattnerdc046542009-05-08 06:58:22 +0000484 TheCall->setArg(i+1, Arg);
485 }
Mike Stump11289f42009-09-09 15:08:12 +0000486
Chris Lattnerdc046542009-05-08 06:58:22 +0000487 // GCC does an implicit conversion to the pointer or integer ValType. This
488 // can fail in some cases (1i -> int**), check for this error case now.
John McCall8cb679e2010-11-15 09:13:47 +0000489 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +0000490 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +0000491 CXXCastPath BasePath;
John McCall7decc9e2010-11-18 06:31:45 +0000492 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, VK, BasePath))
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000493 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000494
Chris Lattnerdc046542009-05-08 06:58:22 +0000495 // Okay, we have something that *can* be converted to the right type. Check
496 // to see if there is a potentially weird extension going on here. This can
497 // happen when you do an atomic operation on something like an char* and
498 // pass in 42. The 42 gets converted to char. This is even more strange
499 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +0000500 // FIXME: Do this check.
John McCall7decc9e2010-11-18 06:31:45 +0000501 ImpCastExprToType(Arg, ValType, Kind, VK, &BasePath);
Chris Lattnerdc046542009-05-08 06:58:22 +0000502 TheCall->setArg(i+1, Arg);
503 }
Mike Stump11289f42009-09-09 15:08:12 +0000504
Chris Lattnerdc046542009-05-08 06:58:22 +0000505 // Switch the DeclRefExpr to refer to the new decl.
506 DRE->setDecl(NewBuiltinDecl);
507 DRE->setType(NewBuiltinDecl->getType());
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattnerdc046542009-05-08 06:58:22 +0000509 // Set the callee in the CallExpr.
510 // FIXME: This leaks the original parens and implicit casts.
511 Expr *PromotedCall = DRE;
512 UsualUnaryConversions(PromotedCall);
513 TheCall->setCallee(PromotedCall);
Mike Stump11289f42009-09-09 15:08:12 +0000514
Chandler Carruthbc8cab12010-07-18 07:23:17 +0000515 // Change the result type of the call to match the original value type. This
516 // is arbitrary, but the codegen for these builtins ins design to handle it
517 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +0000518 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000519
520 return move(TheCallResult);
Chris Lattnerdc046542009-05-08 06:58:22 +0000521}
522
523
Chris Lattner6436fb62009-02-18 06:01:06 +0000524/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +0000525/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +0000526/// Note: It might also make sense to do the UTF-16 conversion here (would
527/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +0000528bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +0000529 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +0000530 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
531
532 if (!Literal || Literal->isWide()) {
Chris Lattner3b054132008-11-19 05:08:23 +0000533 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
534 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +0000535 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +0000536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Benjamin Kramer35b077e2010-08-17 12:54:38 +0000538 size_t NulPos = Literal->getString().find('\0');
539 if (NulPos != llvm::StringRef::npos) {
540 Diag(getLocationOfStringLiteralByte(Literal, NulPos),
541 diag::warn_cfstring_literal_contains_nul_character)
542 << Arg->getSourceRange();
Daniel Dunbarb879c3c2009-09-22 10:03:52 +0000543 }
Fariborz Jahanian56603ef2010-09-07 19:38:13 +0000544 if (Literal->containsNonAsciiOrNull()) {
545 llvm::StringRef String = Literal->getString();
546 unsigned NumBytes = String.size();
547 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
548 const UTF8 *FromPtr = (UTF8 *)String.data();
549 UTF16 *ToPtr = &ToBuf[0];
550
551 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
552 &ToPtr, ToPtr + NumBytes,
553 strictConversion);
554 // Check for conversion failure.
555 if (Result != conversionOK)
556 Diag(Arg->getLocStart(),
557 diag::warn_cfstring_truncated) << Arg->getSourceRange();
558 }
Anders Carlssona3a9c432007-08-17 15:44:17 +0000559 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000560}
561
Chris Lattnere202e6a2007-12-20 00:05:45 +0000562/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
563/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +0000564bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
565 Expr *Fn = TheCall->getCallee();
566 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +0000567 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000568 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000569 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
570 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +0000571 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000572 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +0000573 return true;
574 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000575
576 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +0000577 return Diag(TheCall->getLocEnd(),
578 diag::err_typecheck_call_too_few_args_at_least)
579 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000580 }
581
Chris Lattnere202e6a2007-12-20 00:05:45 +0000582 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000583 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +0000584 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +0000585 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +0000586 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +0000587 else if (FunctionDecl *FD = getCurFunctionDecl())
588 isVariadic = FD->isVariadic();
589 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000590 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +0000591
Chris Lattnere202e6a2007-12-20 00:05:45 +0000592 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000593 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
594 return true;
595 }
Mike Stump11289f42009-09-09 15:08:12 +0000596
Chris Lattner43be2e62007-12-19 23:59:04 +0000597 // Verify that the second argument to the builtin is the last argument of the
598 // current function or method.
599 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +0000600 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +0000601
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000602 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
603 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000604 // FIXME: This isn't correct for methods (results in bogus warning).
605 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000606 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +0000607 if (CurBlock)
608 LastArg = *(CurBlock->TheDecl->param_end()-1);
609 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +0000610 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000611 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000612 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000613 SecondArgIsLastNamedArgument = PV == LastArg;
614 }
615 }
Mike Stump11289f42009-09-09 15:08:12 +0000616
Chris Lattner43be2e62007-12-19 23:59:04 +0000617 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000618 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +0000619 diag::warn_second_parameter_of_va_start_not_last_named_argument);
620 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +0000621}
Chris Lattner43be2e62007-12-19 23:59:04 +0000622
Chris Lattner2da14fb2007-12-20 00:26:33 +0000623/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
624/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +0000625bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
626 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +0000627 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +0000628 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +0000629 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +0000630 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000631 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000632 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +0000633 << SourceRange(TheCall->getArg(2)->getLocStart(),
634 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000635
Chris Lattner08464942007-12-28 05:29:59 +0000636 Expr *OrigArg0 = TheCall->getArg(0);
637 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000638
Chris Lattner2da14fb2007-12-20 00:26:33 +0000639 // Do standard promotions between the two arguments, returning their common
640 // type.
Chris Lattner08464942007-12-28 05:29:59 +0000641 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar96f86772009-02-19 19:28:43 +0000642
643 // Make sure any conversions are pushed back into the call; this is
644 // type safe since unordered compare builtins are declared as "_Bool
645 // foo(...)".
646 TheCall->setArg(0, OrigArg0);
647 TheCall->setArg(1, OrigArg1);
Mike Stump11289f42009-09-09 15:08:12 +0000648
Douglas Gregorc25f7662009-05-19 22:10:17 +0000649 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
650 return false;
651
Chris Lattner2da14fb2007-12-20 00:26:33 +0000652 // If the common type isn't a real floating type, then the arguments were
653 // invalid for this operation.
654 if (!Res->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +0000655 return Diag(OrigArg0->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000656 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000657 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattner3b054132008-11-19 05:08:23 +0000658 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000659
Chris Lattner2da14fb2007-12-20 00:26:33 +0000660 return false;
661}
662
Benjamin Kramer634fc102010-02-15 22:42:31 +0000663/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
664/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +0000665/// to check everything. We expect the last argument to be a floating point
666/// value.
667bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
668 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +0000669 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +0000670 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +0000671 if (TheCall->getNumArgs() > NumArgs)
672 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000673 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000674 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +0000675 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000676 (*(TheCall->arg_end()-1))->getLocEnd());
677
Benjamin Kramer64aae502010-02-16 10:07:31 +0000678 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +0000679
Eli Friedman7e4faac2009-08-31 20:06:00 +0000680 if (OrigArg->isTypeDependent())
681 return false;
682
Chris Lattner68784ef2010-05-06 05:50:07 +0000683 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +0000684 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +0000685 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000686 diag::err_typecheck_call_invalid_unary_fp)
687 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000688
Chris Lattner68784ef2010-05-06 05:50:07 +0000689 // If this is an implicit conversion from float -> double, remove it.
690 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
691 Expr *CastArg = Cast->getSubExpr();
692 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
693 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
694 "promotion from float to double is the only expected cast here");
695 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +0000696 TheCall->setArg(NumArgs-1, CastArg);
697 OrigArg = CastArg;
698 }
699 }
700
Eli Friedman7e4faac2009-08-31 20:06:00 +0000701 return false;
702}
703
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000704/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
705// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +0000706ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +0000707 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000708 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +0000709 diag::err_typecheck_call_too_few_args_at_least)
Nate Begemana0110022010-06-08 00:16:34 +0000710 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherabf1e182010-04-16 04:48:22 +0000711 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000712
Nate Begemana0110022010-06-08 00:16:34 +0000713 // Determine which of the following types of shufflevector we're checking:
714 // 1) unary, vector mask: (lhs, mask)
715 // 2) binary, vector mask: (lhs, rhs, mask)
716 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
717 QualType resType = TheCall->getArg(0)->getType();
718 unsigned numElements = 0;
719
Douglas Gregorc25f7662009-05-19 22:10:17 +0000720 if (!TheCall->getArg(0)->isTypeDependent() &&
721 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +0000722 QualType LHSType = TheCall->getArg(0)->getType();
723 QualType RHSType = TheCall->getArg(1)->getType();
724
725 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000726 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump11289f42009-09-09 15:08:12 +0000727 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +0000728 TheCall->getArg(1)->getLocEnd());
729 return ExprError();
730 }
Nate Begemana0110022010-06-08 00:16:34 +0000731
732 numElements = LHSType->getAs<VectorType>()->getNumElements();
733 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +0000734
Nate Begemana0110022010-06-08 00:16:34 +0000735 // Check to see if we have a call with 2 vector arguments, the unary shuffle
736 // with mask. If so, verify that RHS is an integer vector type with the
737 // same number of elts as lhs.
738 if (TheCall->getNumArgs() == 2) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +0000739 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +0000740 RHSType->getAs<VectorType>()->getNumElements() != numElements)
741 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
742 << SourceRange(TheCall->getArg(1)->getLocStart(),
743 TheCall->getArg(1)->getLocEnd());
744 numResElements = numElements;
745 }
746 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000747 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump11289f42009-09-09 15:08:12 +0000748 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +0000749 TheCall->getArg(1)->getLocEnd());
750 return ExprError();
Nate Begemana0110022010-06-08 00:16:34 +0000751 } else if (numElements != numResElements) {
752 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +0000753 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000754 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000755 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000756 }
757
758 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000759 if (TheCall->getArg(i)->isTypeDependent() ||
760 TheCall->getArg(i)->isValueDependent())
761 continue;
762
Nate Begemana0110022010-06-08 00:16:34 +0000763 llvm::APSInt Result(32);
764 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
765 return ExprError(Diag(TheCall->getLocStart(),
766 diag::err_shufflevector_nonconstant_argument)
767 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000768
Chris Lattner7ab824e2008-08-10 02:05:13 +0000769 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000770 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000771 diag::err_shufflevector_argument_too_large)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000772 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000773 }
774
775 llvm::SmallVector<Expr*, 32> exprs;
776
Chris Lattner7ab824e2008-08-10 02:05:13 +0000777 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000778 exprs.push_back(TheCall->getArg(i));
779 TheCall->setArg(i, 0);
780 }
781
Nate Begemanf485fb52009-08-12 02:10:25 +0000782 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begemana0110022010-06-08 00:16:34 +0000783 exprs.size(), resType,
Ted Kremenek5a201952009-02-07 01:47:29 +0000784 TheCall->getCallee()->getLocStart(),
785 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000786}
Chris Lattner43be2e62007-12-19 23:59:04 +0000787
Daniel Dunbarb7257262008-07-21 22:59:13 +0000788/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
789// This is declared to take (const void*, ...) and can take two
790// optional constant int args.
791bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +0000792 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000793
Chris Lattner3b054132008-11-19 05:08:23 +0000794 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000795 return Diag(TheCall->getLocEnd(),
796 diag::err_typecheck_call_too_many_args_at_most)
797 << 0 /*function call*/ << 3 << NumArgs
798 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000799
800 // Argument 0 is checked for us and the remaining arguments must be
801 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +0000802 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +0000803 Expr *Arg = TheCall->getArg(i);
Eric Christopher8d0c6212010-04-17 02:26:23 +0000804
Eli Friedman5efba262009-12-04 00:30:06 +0000805 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +0000806 if (SemaBuiltinConstantArg(TheCall, i, Result))
807 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000808
Daniel Dunbarb7257262008-07-21 22:59:13 +0000809 // FIXME: gcc issues a warning and rewrites these to 0. These
810 // seems especially odd for the third argument since the default
811 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +0000812 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +0000813 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +0000814 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +0000815 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000816 } else {
Eli Friedman5efba262009-12-04 00:30:06 +0000817 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +0000818 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +0000819 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000820 }
821 }
822
Chris Lattner3b054132008-11-19 05:08:23 +0000823 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +0000824}
825
Eric Christopher8d0c6212010-04-17 02:26:23 +0000826/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
827/// TheCall is a constant expression.
828bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
829 llvm::APSInt &Result) {
830 Expr *Arg = TheCall->getArg(ArgNum);
831 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
832 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
833
834 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
835
836 if (!Arg->isIntegerConstantExpr(Result, Context))
837 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +0000838 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +0000839
Chris Lattnerd545ad12009-09-23 06:06:36 +0000840 return false;
841}
842
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000843/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
844/// int type). This simply type checks that type is one of the defined
845/// constants (0-3).
Eric Christopherc8791562009-12-23 03:49:37 +0000846// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000847bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +0000848 llvm::APSInt Result;
849
850 // Check constant-ness first.
851 if (SemaBuiltinConstantArg(TheCall, 1, Result))
852 return true;
853
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000854 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000855 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +0000856 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
857 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000858 }
859
860 return false;
861}
862
Eli Friedmanc97d0142009-05-03 06:04:26 +0000863/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000864/// This checks that val is a constant 1.
865bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
866 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +0000867 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +0000868
Eric Christopher8d0c6212010-04-17 02:26:23 +0000869 // TODO: This is less than ideal. Overload this to take a value.
870 if (SemaBuiltinConstantArg(TheCall, 1, Result))
871 return true;
872
873 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000874 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
875 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
876
877 return false;
878}
879
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000880// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000881bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
882 bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +0000883 unsigned format_idx, unsigned firstDataArg,
884 bool isPrintf) {
Ted Kremenek808829352010-09-09 03:51:39 +0000885 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +0000886 if (E->isTypeDependent() || E->isValueDependent())
887 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000888
889 switch (E->getStmtClass()) {
890 case Stmt::ConditionalOperatorClass: {
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000891 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenek02087932010-07-16 02:11:22 +0000892 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
893 format_idx, firstDataArg, isPrintf)
894 && SemaCheckStringLiteral(C->getRHS(), TheCall, HasVAListArg,
895 format_idx, firstDataArg, isPrintf);
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000896 }
897
Ted Kremenek1520dae2010-09-09 03:51:42 +0000898 case Stmt::IntegerLiteralClass:
899 // Technically -Wformat-nonliteral does not warn about this case.
900 // The behavior of printf and friends in this case is implementation
901 // dependent. Ideally if the format string cannot be null then
902 // it should have a 'nonnull' attribute in the function prototype.
903 return true;
904
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000905 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +0000906 E = cast<ImplicitCastExpr>(E)->getSubExpr();
907 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000908 }
909
910 case Stmt::ParenExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +0000911 E = cast<ParenExpr>(E)->getSubExpr();
912 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000913 }
Mike Stump11289f42009-09-09 15:08:12 +0000914
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000915 case Stmt::DeclRefExprClass: {
916 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +0000917
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000918 // As an exception, do not flag errors for variables binding to
919 // const string literals.
920 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
921 bool isConstant = false;
922 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000923
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000924 if (const ArrayType *AT = Context.getAsArrayType(T)) {
925 isConstant = AT->getElementType().isConstant(Context);
Mike Stump12b8ce12009-08-04 21:02:39 +0000926 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000927 isConstant = T.isConstant(Context) &&
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000928 PT->getPointeeType().isConstant(Context);
929 }
Mike Stump11289f42009-09-09 15:08:12 +0000930
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000931 if (isConstant) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000932 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000933 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek02087932010-07-16 02:11:22 +0000934 HasVAListArg, format_idx, firstDataArg,
935 isPrintf);
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000936 }
Mike Stump11289f42009-09-09 15:08:12 +0000937
Anders Carlssonb012ca92009-06-28 19:55:58 +0000938 // For vprintf* functions (i.e., HasVAListArg==true), we add a
939 // special check to see if the format string is a function parameter
940 // of the function calling the printf function. If the function
941 // has an attribute indicating it is a printf-like function, then we
942 // should suppress warnings concerning non-literals being used in a call
943 // to a vprintf function. For example:
944 //
945 // void
946 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
947 // va_list ap;
948 // va_start(ap, fmt);
949 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
950 // ...
951 //
952 //
953 // FIXME: We don't have full attribute support yet, so just check to see
954 // if the argument is a DeclRefExpr that references a parameter. We'll
955 // add proper support for checking the attribute later.
956 if (HasVAListArg)
957 if (isa<ParmVarDecl>(VD))
958 return true;
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000959 }
Mike Stump11289f42009-09-09 15:08:12 +0000960
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000961 return false;
962 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000963
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000964 case Stmt::CallExprClass: {
965 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +0000966 if (const ImplicitCastExpr *ICE
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000967 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
968 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
969 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000970 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000971 unsigned ArgIndex = FA->getFormatIdx();
972 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +0000973
974 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +0000975 format_idx, firstDataArg, isPrintf);
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000976 }
977 }
978 }
979 }
Mike Stump11289f42009-09-09 15:08:12 +0000980
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000981 return false;
982 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000983 case Stmt::ObjCStringLiteralClass:
984 case Stmt::StringLiteralClass: {
985 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +0000986
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000987 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000988 StrE = ObjCFExpr->getString();
989 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000990 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000992 if (StrE) {
Ted Kremenek02087932010-07-16 02:11:22 +0000993 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
994 firstDataArg, isPrintf);
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000995 return true;
996 }
Mike Stump11289f42009-09-09 15:08:12 +0000997
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000998 return false;
999 }
Mike Stump11289f42009-09-09 15:08:12 +00001000
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001001 default:
1002 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001003 }
1004}
1005
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001006void
Mike Stump11289f42009-09-09 15:08:12 +00001007Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1008 const CallExpr *TheCall) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001009 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1010 e = NonNull->args_end();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001011 i != e; ++i) {
Chris Lattner23464b82009-05-25 18:23:36 +00001012 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001013 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00001014 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner23464b82009-05-25 18:23:36 +00001015 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1016 << ArgExpr->getSourceRange();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001017 }
1018}
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001019
Ted Kremenek02087932010-07-16 02:11:22 +00001020/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1021/// functions) for correct use of format strings.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001022void
Ted Kremenek02087932010-07-16 02:11:22 +00001023Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1024 unsigned format_idx, unsigned firstDataArg,
1025 bool isPrintf) {
1026
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001027 const Expr *Fn = TheCall->getCallee();
Chris Lattner08464942007-12-28 05:29:59 +00001028
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001029 // The way the format attribute works in GCC, the implicit this argument
1030 // of member functions is counted. However, it doesn't appear in our own
1031 // lists, so decrement format_idx in that case.
1032 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth1c8383d2010-11-16 08:49:43 +00001033 const CXXMethodDecl *method_decl =
1034 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1035 if (method_decl && method_decl->isInstance()) {
1036 // Catch a format attribute mistakenly referring to the object argument.
1037 if (format_idx == 0)
1038 return;
1039 --format_idx;
1040 if(firstDataArg != 0)
1041 --firstDataArg;
1042 }
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001043 }
1044
Ted Kremenek02087932010-07-16 02:11:22 +00001045 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner08464942007-12-28 05:29:59 +00001046 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek02087932010-07-16 02:11:22 +00001047 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerf490e152008-11-19 05:27:50 +00001048 << Fn->getSourceRange();
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001049 return;
1050 }
Mike Stump11289f42009-09-09 15:08:12 +00001051
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001052 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001053
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001054 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001055 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001056 // Dynamically generated format strings are difficult to
1057 // automatically vet at compile time. Requiring that format strings
1058 // are string literals: (1) permits the checking of format strings by
1059 // the compiler and thereby (2) can practically remove the source of
1060 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00001061
Mike Stump11289f42009-09-09 15:08:12 +00001062 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00001063 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00001064 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00001065 // the same format string checking logic for both ObjC and C strings.
Chris Lattnere009a882009-04-29 04:49:34 +00001066 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek02087932010-07-16 02:11:22 +00001067 firstDataArg, isPrintf))
Chris Lattnere009a882009-04-29 04:49:34 +00001068 return; // Literal format string found, check done!
Ted Kremenek34f664d2008-06-16 18:00:42 +00001069
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001070 // If there are no arguments specified, warn with -Wformat-security, otherwise
1071 // warn only with -Wformat-nonliteral.
1072 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump11289f42009-09-09 15:08:12 +00001073 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001074 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001075 << OrigFormatExpr->getSourceRange();
1076 else
Mike Stump11289f42009-09-09 15:08:12 +00001077 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001078 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001079 << OrigFormatExpr->getSourceRange();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001080}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001081
Ted Kremenekab278de2010-01-28 23:39:18 +00001082namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00001083class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1084protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00001085 Sema &S;
1086 const StringLiteral *FExpr;
1087 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001088 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00001089 const unsigned NumDataArgs;
1090 const bool IsObjCLiteral;
1091 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00001092 const bool HasVAListArg;
1093 const CallExpr *TheCall;
1094 unsigned FormatIdx;
Ted Kremenek4a49d982010-02-26 19:18:41 +00001095 llvm::BitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00001096 bool usesPositionalArgs;
1097 bool atFirstArg;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001098public:
Ted Kremenek02087932010-07-16 02:11:22 +00001099 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001100 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremenekab278de2010-01-28 23:39:18 +00001101 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek5739de72010-01-29 01:06:55 +00001102 const char *beg, bool hasVAListArg,
1103 const CallExpr *theCall, unsigned formatIdx)
Ted Kremenekab278de2010-01-28 23:39:18 +00001104 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001105 FirstDataArg(firstDataArg),
Ted Kremenek4a49d982010-02-26 19:18:41 +00001106 NumDataArgs(numDataArgs),
Ted Kremenek5739de72010-01-29 01:06:55 +00001107 IsObjCLiteral(isObjCLiteral), Beg(beg),
1108 HasVAListArg(hasVAListArg),
Ted Kremenekd1668192010-02-27 01:41:03 +00001109 TheCall(theCall), FormatIdx(formatIdx),
1110 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001111 CoveredArgs.resize(numDataArgs);
1112 CoveredArgs.reset();
1113 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001114
Ted Kremenek019d2242010-01-29 01:50:07 +00001115 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001116
Ted Kremenek02087932010-07-16 02:11:22 +00001117 void HandleIncompleteSpecifier(const char *startSpecifier,
1118 unsigned specifierLen);
1119
Ted Kremenekd1668192010-02-27 01:41:03 +00001120 virtual void HandleInvalidPosition(const char *startSpecifier,
1121 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00001122 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00001123
1124 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1125
Ted Kremenekab278de2010-01-28 23:39:18 +00001126 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001127
Ted Kremenek02087932010-07-16 02:11:22 +00001128protected:
Ted Kremenekce815422010-07-19 21:25:57 +00001129 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1130 const char *startSpec,
1131 unsigned specifierLen,
1132 const char *csStart, unsigned csLen);
1133
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001134 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00001135 CharSourceRange getSpecifierRange(const char *startSpecifier,
1136 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00001137 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001138
Ted Kremenek5739de72010-01-29 01:06:55 +00001139 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001140
1141 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1142 const analyze_format_string::ConversionSpecifier &CS,
1143 const char *startSpecifier, unsigned specifierLen,
1144 unsigned argIndex);
Ted Kremenekab278de2010-01-28 23:39:18 +00001145};
1146}
1147
Ted Kremenek02087932010-07-16 02:11:22 +00001148SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00001149 return OrigFormatExpr->getSourceRange();
1150}
1151
Ted Kremenek02087932010-07-16 02:11:22 +00001152CharSourceRange CheckFormatHandler::
1153getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00001154 SourceLocation Start = getLocationOfByte(startSpecifier);
1155 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1156
1157 // Advance the end SourceLocation by one due to half-open ranges.
1158 End = End.getFileLocWithOffset(1);
1159
1160 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001161}
1162
Ted Kremenek02087932010-07-16 02:11:22 +00001163SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001164 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00001165}
1166
Ted Kremenek02087932010-07-16 02:11:22 +00001167void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1168 unsigned specifierLen){
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001169 SourceLocation Loc = getLocationOfByte(startSpecifier);
1170 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek02087932010-07-16 02:11:22 +00001171 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001172}
1173
Ted Kremenekd1668192010-02-27 01:41:03 +00001174void
Ted Kremenek02087932010-07-16 02:11:22 +00001175CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1176 analyze_format_string::PositionContext p) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001177 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek02087932010-07-16 02:11:22 +00001178 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1179 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekd1668192010-02-27 01:41:03 +00001180}
1181
Ted Kremenek02087932010-07-16 02:11:22 +00001182void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00001183 unsigned posLen) {
1184 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek02087932010-07-16 02:11:22 +00001185 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1186 << getSpecifierRange(startPos, posLen);
Ted Kremenekd1668192010-02-27 01:41:03 +00001187}
1188
Ted Kremenek02087932010-07-16 02:11:22 +00001189void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1190 // The presence of a null character is likely an error.
1191 S.Diag(getLocationOfByte(nullCharacter),
1192 diag::warn_printf_format_string_contains_null_char)
1193 << getFormatStringRange();
1194}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001195
Ted Kremenek02087932010-07-16 02:11:22 +00001196const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1197 return TheCall->getArg(FirstDataArg + i);
1198}
1199
1200void CheckFormatHandler::DoneProcessing() {
1201 // Does the number of data arguments exceed the number of
1202 // format conversions in the format string?
1203 if (!HasVAListArg) {
1204 // Find any arguments that weren't covered.
1205 CoveredArgs.flip();
1206 signed notCoveredArg = CoveredArgs.find_first();
1207 if (notCoveredArg >= 0) {
1208 assert((unsigned)notCoveredArg < NumDataArgs);
1209 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1210 diag::warn_printf_data_arg_not_used)
1211 << getFormatStringRange();
1212 }
1213 }
1214}
1215
Ted Kremenekce815422010-07-19 21:25:57 +00001216bool
1217CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1218 SourceLocation Loc,
1219 const char *startSpec,
1220 unsigned specifierLen,
1221 const char *csStart,
1222 unsigned csLen) {
1223
1224 bool keepGoing = true;
1225 if (argIndex < NumDataArgs) {
1226 // Consider the argument coverered, even though the specifier doesn't
1227 // make sense.
1228 CoveredArgs.set(argIndex);
1229 }
1230 else {
1231 // If argIndex exceeds the number of data arguments we
1232 // don't issue a warning because that is just a cascade of warnings (and
1233 // they may have intended '%%' anyway). We don't want to continue processing
1234 // the format string after this point, however, as we will like just get
1235 // gibberish when trying to match arguments.
1236 keepGoing = false;
1237 }
1238
1239 S.Diag(Loc, diag::warn_format_invalid_conversion)
1240 << llvm::StringRef(csStart, csLen)
1241 << getSpecifierRange(startSpec, specifierLen);
1242
1243 return keepGoing;
1244}
1245
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001246bool
1247CheckFormatHandler::CheckNumArgs(
1248 const analyze_format_string::FormatSpecifier &FS,
1249 const analyze_format_string::ConversionSpecifier &CS,
1250 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1251
1252 if (argIndex >= NumDataArgs) {
1253 if (FS.usesPositionalArg()) {
1254 S.Diag(getLocationOfByte(CS.getStart()),
1255 diag::warn_printf_positional_arg_exceeds_data_args)
1256 << (argIndex+1) << NumDataArgs
1257 << getSpecifierRange(startSpecifier, specifierLen);
1258 }
1259 else {
1260 S.Diag(getLocationOfByte(CS.getStart()),
1261 diag::warn_printf_insufficient_data_args)
1262 << getSpecifierRange(startSpecifier, specifierLen);
1263 }
1264
1265 return false;
1266 }
1267 return true;
1268}
1269
Ted Kremenek02087932010-07-16 02:11:22 +00001270//===--- CHECK: Printf format string checking ------------------------------===//
1271
1272namespace {
1273class CheckPrintfHandler : public CheckFormatHandler {
1274public:
1275 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1276 const Expr *origFormatExpr, unsigned firstDataArg,
1277 unsigned numDataArgs, bool isObjCLiteral,
1278 const char *beg, bool hasVAListArg,
1279 const CallExpr *theCall, unsigned formatIdx)
1280 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1281 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1282 theCall, formatIdx) {}
1283
1284
1285 bool HandleInvalidPrintfConversionSpecifier(
1286 const analyze_printf::PrintfSpecifier &FS,
1287 const char *startSpecifier,
1288 unsigned specifierLen);
1289
1290 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1291 const char *startSpecifier,
1292 unsigned specifierLen);
1293
1294 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1295 const char *startSpecifier, unsigned specifierLen);
1296 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1297 const analyze_printf::OptionalAmount &Amt,
1298 unsigned type,
1299 const char *startSpecifier, unsigned specifierLen);
1300 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1301 const analyze_printf::OptionalFlag &flag,
1302 const char *startSpecifier, unsigned specifierLen);
1303 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1304 const analyze_printf::OptionalFlag &ignoredFlag,
1305 const analyze_printf::OptionalFlag &flag,
1306 const char *startSpecifier, unsigned specifierLen);
1307};
1308}
1309
1310bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1311 const analyze_printf::PrintfSpecifier &FS,
1312 const char *startSpecifier,
1313 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001314 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00001315 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00001316
Ted Kremenekce815422010-07-19 21:25:57 +00001317 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1318 getLocationOfByte(CS.getStart()),
1319 startSpecifier, specifierLen,
1320 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00001321}
1322
Ted Kremenek02087932010-07-16 02:11:22 +00001323bool CheckPrintfHandler::HandleAmount(
1324 const analyze_format_string::OptionalAmount &Amt,
1325 unsigned k, const char *startSpecifier,
1326 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001327
1328 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001329 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001330 unsigned argIndex = Amt.getArgIndex();
1331 if (argIndex >= NumDataArgs) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001332 S.Diag(getLocationOfByte(Amt.getStart()),
1333 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek02087932010-07-16 02:11:22 +00001334 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek5739de72010-01-29 01:06:55 +00001335 // Don't do any more checking. We will just emit
1336 // spurious errors.
1337 return false;
1338 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001339
Ted Kremenek5739de72010-01-29 01:06:55 +00001340 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00001341 // Although not in conformance with C99, we also allow the argument to be
1342 // an 'unsigned int' as that is a reasonably safe case. GCC also
1343 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00001344 CoveredArgs.set(argIndex);
1345 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek5739de72010-01-29 01:06:55 +00001346 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001347
1348 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1349 assert(ATR.isValid());
1350
1351 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001352 S.Diag(getLocationOfByte(Amt.getStart()),
1353 diag::warn_printf_asterisk_wrong_type)
1354 << k
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001355 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek02087932010-07-16 02:11:22 +00001356 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001357 << Arg->getSourceRange();
Ted Kremenek5739de72010-01-29 01:06:55 +00001358 // Don't do any more checking. We will just emit
1359 // spurious errors.
1360 return false;
1361 }
1362 }
1363 }
1364 return true;
1365}
Ted Kremenek5739de72010-01-29 01:06:55 +00001366
Tom Careb49ec692010-06-17 19:00:27 +00001367void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00001368 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001369 const analyze_printf::OptionalAmount &Amt,
1370 unsigned type,
1371 const char *startSpecifier,
1372 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001373 const analyze_printf::PrintfConversionSpecifier &CS =
1374 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001375 switch (Amt.getHowSpecified()) {
1376 case analyze_printf::OptionalAmount::Constant:
1377 S.Diag(getLocationOfByte(Amt.getStart()),
1378 diag::warn_printf_nonsensical_optional_amount)
1379 << type
1380 << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001381 << getSpecifierRange(startSpecifier, specifierLen)
1382 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Careb49ec692010-06-17 19:00:27 +00001383 Amt.getConstantLength()));
1384 break;
1385
1386 default:
1387 S.Diag(getLocationOfByte(Amt.getStart()),
1388 diag::warn_printf_nonsensical_optional_amount)
1389 << type
1390 << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001391 << getSpecifierRange(startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001392 break;
1393 }
1394}
1395
Ted Kremenek02087932010-07-16 02:11:22 +00001396void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001397 const analyze_printf::OptionalFlag &flag,
1398 const char *startSpecifier,
1399 unsigned specifierLen) {
1400 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001401 const analyze_printf::PrintfConversionSpecifier &CS =
1402 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001403 S.Diag(getLocationOfByte(flag.getPosition()),
1404 diag::warn_printf_nonsensical_flag)
1405 << flag.toString() << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001406 << getSpecifierRange(startSpecifier, specifierLen)
1407 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Careb49ec692010-06-17 19:00:27 +00001408}
1409
1410void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00001411 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001412 const analyze_printf::OptionalFlag &ignoredFlag,
1413 const analyze_printf::OptionalFlag &flag,
1414 const char *startSpecifier,
1415 unsigned specifierLen) {
1416 // Warn about ignored flag with a fixit removal.
1417 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1418 diag::warn_printf_ignored_flag)
1419 << ignoredFlag.toString() << flag.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001420 << getSpecifierRange(startSpecifier, specifierLen)
1421 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Careb49ec692010-06-17 19:00:27 +00001422 ignoredFlag.getPosition(), 1));
1423}
1424
Ted Kremenekab278de2010-01-28 23:39:18 +00001425bool
Ted Kremenek02087932010-07-16 02:11:22 +00001426CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00001427 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00001428 const char *startSpecifier,
1429 unsigned specifierLen) {
1430
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001431 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00001432 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001433 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00001434
Ted Kremenek6cd69422010-07-19 22:01:06 +00001435 if (FS.consumesDataArgument()) {
1436 if (atFirstArg) {
1437 atFirstArg = false;
1438 usesPositionalArgs = FS.usesPositionalArg();
1439 }
1440 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1441 // Cannot mix-and-match positional and non-positional arguments.
1442 S.Diag(getLocationOfByte(CS.getStart()),
1443 diag::warn_format_mix_positional_nonpositional_args)
1444 << getSpecifierRange(startSpecifier, specifierLen);
1445 return false;
1446 }
Ted Kremenek5739de72010-01-29 01:06:55 +00001447 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001448
Ted Kremenekd1668192010-02-27 01:41:03 +00001449 // First check if the field width, precision, and conversion specifier
1450 // have matching data arguments.
1451 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1452 startSpecifier, specifierLen)) {
1453 return false;
1454 }
1455
1456 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1457 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001458 return false;
1459 }
1460
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001461 if (!CS.consumesDataArgument()) {
1462 // FIXME: Technically specifying a precision or field width here
1463 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00001464 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001465 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001466
Ted Kremenek4a49d982010-02-26 19:18:41 +00001467 // Consume the argument.
1468 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00001469 if (argIndex < NumDataArgs) {
1470 // The check to see if the argIndex is valid will come later.
1471 // We set the bit here because we may exit early from this
1472 // function if we encounter some other error.
1473 CoveredArgs.set(argIndex);
1474 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00001475
1476 // Check for using an Objective-C specific conversion specifier
1477 // in a non-ObjC literal.
1478 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00001479 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1480 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00001481 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001482
Tom Careb49ec692010-06-17 19:00:27 +00001483 // Check for invalid use of field width
1484 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00001485 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00001486 startSpecifier, specifierLen);
1487 }
1488
1489 // Check for invalid use of precision
1490 if (!FS.hasValidPrecision()) {
1491 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1492 startSpecifier, specifierLen);
1493 }
1494
1495 // Check each flag does not conflict with any other component.
1496 if (!FS.hasValidLeadingZeros())
1497 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1498 if (!FS.hasValidPlusPrefix())
1499 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00001500 if (!FS.hasValidSpacePrefix())
1501 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001502 if (!FS.hasValidAlternativeForm())
1503 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1504 if (!FS.hasValidLeftJustified())
1505 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1506
1507 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00001508 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1509 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1510 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001511 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1512 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1513 startSpecifier, specifierLen);
1514
1515 // Check the length modifier is valid with the given conversion specifier.
1516 const LengthModifier &LM = FS.getLengthModifier();
1517 if (!FS.hasValidLengthModifier())
1518 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenekb65a9d52010-07-20 20:03:43 +00001519 diag::warn_format_nonsensical_length)
Tom Careb49ec692010-06-17 19:00:27 +00001520 << LM.toString() << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001521 << getSpecifierRange(startSpecifier, specifierLen)
1522 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Careb49ec692010-06-17 19:00:27 +00001523 LM.getLength()));
1524
1525 // Are we using '%n'?
Ted Kremenek516ef222010-07-20 20:04:10 +00001526 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Careb49ec692010-06-17 19:00:27 +00001527 // Issue a warning about this being a possible security issue.
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001528 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek02087932010-07-16 02:11:22 +00001529 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001530 // Continue checking the other format specifiers.
1531 return true;
1532 }
Ted Kremenekd31b2632010-02-11 09:27:41 +00001533
Ted Kremenek9fcd8302010-01-29 01:43:31 +00001534 // The remaining checks depend on the data arguments.
1535 if (HasVAListArg)
1536 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001537
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001538 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00001539 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001540
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001541 // Now type check the data expression that matches the
1542 // format specifier.
1543 const Expr *Ex = getDataArg(argIndex);
1544 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1545 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1546 // Check if we didn't match because of an implicit cast from a 'char'
1547 // or 'short' to an 'int'. This is done because printf is a varargs
1548 // function.
1549 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek12a37de2010-10-21 04:00:58 +00001550 if (ICE->getType() == S.Context.IntTy) {
1551 // All further checking is done on the subexpression.
1552 Ex = ICE->getSubExpr();
1553 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001554 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00001555 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001556
1557 // We may be able to offer a FixItHint if it is a supported type.
1558 PrintfSpecifier fixedFS = FS;
1559 bool success = fixedFS.fixType(Ex->getType());
1560
1561 if (success) {
1562 // Get the fix string from the fixed format specifier
1563 llvm::SmallString<128> buf;
1564 llvm::raw_svector_ostream os(buf);
1565 fixedFS.toString(os);
1566
Ted Kremenek5f0c0662010-08-24 22:24:51 +00001567 // FIXME: getRepresentativeType() perhaps should return a string
1568 // instead of a QualType to better handle when the representative
1569 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001570 S.Diag(getLocationOfByte(CS.getStart()),
1571 diag::warn_printf_conversion_argument_type_mismatch)
1572 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1573 << getSpecifierRange(startSpecifier, specifierLen)
1574 << Ex->getSourceRange()
1575 << FixItHint::CreateReplacement(
1576 getSpecifierRange(startSpecifier, specifierLen),
1577 os.str());
1578 }
1579 else {
1580 S.Diag(getLocationOfByte(CS.getStart()),
1581 diag::warn_printf_conversion_argument_type_mismatch)
1582 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1583 << getSpecifierRange(startSpecifier, specifierLen)
1584 << Ex->getSourceRange();
1585 }
1586 }
1587
Ted Kremenekab278de2010-01-28 23:39:18 +00001588 return true;
1589}
1590
Ted Kremenek02087932010-07-16 02:11:22 +00001591//===--- CHECK: Scanf format string checking ------------------------------===//
1592
1593namespace {
1594class CheckScanfHandler : public CheckFormatHandler {
1595public:
1596 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1597 const Expr *origFormatExpr, unsigned firstDataArg,
1598 unsigned numDataArgs, bool isObjCLiteral,
1599 const char *beg, bool hasVAListArg,
1600 const CallExpr *theCall, unsigned formatIdx)
1601 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1602 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1603 theCall, formatIdx) {}
1604
1605 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1606 const char *startSpecifier,
1607 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00001608
1609 bool HandleInvalidScanfConversionSpecifier(
1610 const analyze_scanf::ScanfSpecifier &FS,
1611 const char *startSpecifier,
1612 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00001613
1614 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00001615};
Ted Kremenek019d2242010-01-29 01:50:07 +00001616}
Ted Kremenekab278de2010-01-28 23:39:18 +00001617
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00001618void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1619 const char *end) {
1620 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1621 << getSpecifierRange(start, end - start);
1622}
1623
Ted Kremenekce815422010-07-19 21:25:57 +00001624bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1625 const analyze_scanf::ScanfSpecifier &FS,
1626 const char *startSpecifier,
1627 unsigned specifierLen) {
1628
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001629 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00001630 FS.getConversionSpecifier();
1631
1632 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1633 getLocationOfByte(CS.getStart()),
1634 startSpecifier, specifierLen,
1635 CS.getStart(), CS.getLength());
1636}
1637
Ted Kremenek02087932010-07-16 02:11:22 +00001638bool CheckScanfHandler::HandleScanfSpecifier(
1639 const analyze_scanf::ScanfSpecifier &FS,
1640 const char *startSpecifier,
1641 unsigned specifierLen) {
1642
1643 using namespace analyze_scanf;
1644 using namespace analyze_format_string;
1645
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001646 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00001647
Ted Kremenek6cd69422010-07-19 22:01:06 +00001648 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1649 // be used to decide if we are using positional arguments consistently.
1650 if (FS.consumesDataArgument()) {
1651 if (atFirstArg) {
1652 atFirstArg = false;
1653 usesPositionalArgs = FS.usesPositionalArg();
1654 }
1655 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1656 // Cannot mix-and-match positional and non-positional arguments.
1657 S.Diag(getLocationOfByte(CS.getStart()),
1658 diag::warn_format_mix_positional_nonpositional_args)
1659 << getSpecifierRange(startSpecifier, specifierLen);
1660 return false;
1661 }
Ted Kremenek02087932010-07-16 02:11:22 +00001662 }
1663
1664 // Check if the field with is non-zero.
1665 const OptionalAmount &Amt = FS.getFieldWidth();
1666 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1667 if (Amt.getConstantAmount() == 0) {
1668 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1669 Amt.getConstantLength());
1670 S.Diag(getLocationOfByte(Amt.getStart()),
1671 diag::warn_scanf_nonzero_width)
1672 << R << FixItHint::CreateRemoval(R);
1673 }
1674 }
1675
1676 if (!FS.consumesDataArgument()) {
1677 // FIXME: Technically specifying a precision or field width here
1678 // makes no sense. Worth issuing a warning at some point.
1679 return true;
1680 }
1681
1682 // Consume the argument.
1683 unsigned argIndex = FS.getArgIndex();
1684 if (argIndex < NumDataArgs) {
1685 // The check to see if the argIndex is valid will come later.
1686 // We set the bit here because we may exit early from this
1687 // function if we encounter some other error.
1688 CoveredArgs.set(argIndex);
1689 }
1690
Ted Kremenek4407ea42010-07-20 20:04:47 +00001691 // Check the length modifier is valid with the given conversion specifier.
1692 const LengthModifier &LM = FS.getLengthModifier();
1693 if (!FS.hasValidLengthModifier()) {
1694 S.Diag(getLocationOfByte(LM.getStart()),
1695 diag::warn_format_nonsensical_length)
1696 << LM.toString() << CS.toString()
1697 << getSpecifierRange(startSpecifier, specifierLen)
1698 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1699 LM.getLength()));
1700 }
1701
Ted Kremenek02087932010-07-16 02:11:22 +00001702 // The remaining checks depend on the data arguments.
1703 if (HasVAListArg)
1704 return true;
1705
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001706 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00001707 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00001708
1709 // FIXME: Check that the argument type matches the format specifier.
1710
1711 return true;
1712}
1713
1714void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00001715 const Expr *OrigFormatExpr,
1716 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001717 unsigned format_idx, unsigned firstDataArg,
1718 bool isPrintf) {
1719
Ted Kremenekab278de2010-01-28 23:39:18 +00001720 // CHECK: is the format string a wide literal?
1721 if (FExpr->isWide()) {
1722 Diag(FExpr->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001723 diag::warn_format_string_is_wide_literal)
Ted Kremenekab278de2010-01-28 23:39:18 +00001724 << OrigFormatExpr->getSourceRange();
1725 return;
1726 }
Ted Kremenek02087932010-07-16 02:11:22 +00001727
Ted Kremenekab278de2010-01-28 23:39:18 +00001728 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001729 llvm::StringRef StrRef = FExpr->getString();
1730 const char *Str = StrRef.data();
1731 unsigned StrLen = StrRef.size();
Ted Kremenek02087932010-07-16 02:11:22 +00001732
Ted Kremenekab278de2010-01-28 23:39:18 +00001733 // CHECK: empty format string?
Ted Kremenekab278de2010-01-28 23:39:18 +00001734 if (StrLen == 0) {
Ted Kremenek02087932010-07-16 02:11:22 +00001735 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremenekab278de2010-01-28 23:39:18 +00001736 << OrigFormatExpr->getSourceRange();
1737 return;
1738 }
Ted Kremenek02087932010-07-16 02:11:22 +00001739
1740 if (isPrintf) {
1741 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1742 TheCall->getNumArgs() - firstDataArg,
1743 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1744 HasVAListArg, TheCall, format_idx);
1745
1746 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1747 H.DoneProcessing();
1748 }
1749 else {
1750 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1751 TheCall->getNumArgs() - firstDataArg,
1752 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1753 HasVAListArg, TheCall, format_idx);
1754
1755 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1756 H.DoneProcessing();
1757 }
Ted Kremenekc70ee862010-01-28 01:18:22 +00001758}
1759
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001760//===--- CHECK: Return Address of Stack Variable --------------------------===//
1761
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001762static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1763static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001764
1765/// CheckReturnStackAddr - Check if a return statement returns the address
1766/// of a stack variable.
1767void
1768Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1769 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001770
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001771 Expr *stackE = 0;
1772 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1773
1774 // Perform checking for returned stack addresses, local blocks,
1775 // label addresses or references to temporaries.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001776 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001777 stackE = EvalAddr(RetValExp, refVars);
Mike Stump12b8ce12009-08-04 21:02:39 +00001778 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001779 stackE = EvalVal(RetValExp, refVars);
1780 }
1781
1782 if (stackE == 0)
1783 return; // Nothing suspicious was found.
1784
1785 SourceLocation diagLoc;
1786 SourceRange diagRange;
1787 if (refVars.empty()) {
1788 diagLoc = stackE->getLocStart();
1789 diagRange = stackE->getSourceRange();
1790 } else {
1791 // We followed through a reference variable. 'stackE' contains the
1792 // problematic expression but we will warn at the return statement pointing
1793 // at the reference variable. We will later display the "trail" of
1794 // reference variables using notes.
1795 diagLoc = refVars[0]->getLocStart();
1796 diagRange = refVars[0]->getSourceRange();
1797 }
1798
1799 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1800 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1801 : diag::warn_ret_stack_addr)
1802 << DR->getDecl()->getDeclName() << diagRange;
1803 } else if (isa<BlockExpr>(stackE)) { // local block.
1804 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1805 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1806 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1807 } else { // local temporary.
1808 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1809 : diag::warn_ret_local_temp_addr)
1810 << diagRange;
1811 }
1812
1813 // Display the "trail" of reference variables that we followed until we
1814 // found the problematic expression using notes.
1815 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1816 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1817 // If this var binds to another reference var, show the range of the next
1818 // var, otherwise the var binds to the problematic expression, in which case
1819 // show the range of the expression.
1820 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1821 : stackE->getSourceRange();
1822 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1823 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001824 }
1825}
1826
1827/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1828/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001829/// to a location on the stack, a local block, an address of a label, or a
1830/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001831/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001832/// encounter a subexpression that (1) clearly does not lead to one of the
1833/// above problematic expressions (2) is something we cannot determine leads to
1834/// a problematic expression based on such local checking.
1835///
1836/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1837/// the expression that they point to. Such variables are added to the
1838/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001839///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00001840/// EvalAddr processes expressions that are pointers that are used as
1841/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001842/// At the base case of the recursion is a check for the above problematic
1843/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001844///
1845/// This implementation handles:
1846///
1847/// * pointer-to-pointer casts
1848/// * implicit conversions from array references to pointers
1849/// * taking the address of fields
1850/// * arbitrary interplay between "&" and "*" operators
1851/// * pointer arithmetic from an address of a stack variable
1852/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001853static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1854 if (E->isTypeDependent())
1855 return NULL;
1856
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001857 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00001858 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001859 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001860 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00001861 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00001862
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001863 // Our "symbolic interpreter" is just a dispatch off the currently
1864 // viewed AST node. We then recursively traverse the AST by calling
1865 // EvalAddr and EvalVal appropriately.
1866 switch (E->getStmtClass()) {
Chris Lattner934edb22007-12-28 05:31:15 +00001867 case Stmt::ParenExprClass:
1868 // Ignore parentheses.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001869 return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1870
1871 case Stmt::DeclRefExprClass: {
1872 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1873
1874 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1875 // If this is a reference variable, follow through to the expression that
1876 // it points to.
1877 if (V->hasLocalStorage() &&
1878 V->getType()->isReferenceType() && V->hasInit()) {
1879 // Add the reference variable to the "trail".
1880 refVars.push_back(DR);
1881 return EvalAddr(V->getInit(), refVars);
1882 }
1883
1884 return NULL;
1885 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001886
Chris Lattner934edb22007-12-28 05:31:15 +00001887 case Stmt::UnaryOperatorClass: {
1888 // The only unary operator that make sense to handle here
1889 // is AddrOf. All others don't make sense as pointers.
1890 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001891
John McCalle3027922010-08-25 11:45:40 +00001892 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001893 return EvalVal(U->getSubExpr(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001894 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001895 return NULL;
1896 }
Mike Stump11289f42009-09-09 15:08:12 +00001897
Chris Lattner934edb22007-12-28 05:31:15 +00001898 case Stmt::BinaryOperatorClass: {
1899 // Handle pointer arithmetic. All other binary operators are not valid
1900 // in this context.
1901 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00001902 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00001903
John McCalle3027922010-08-25 11:45:40 +00001904 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00001905 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001906
Chris Lattner934edb22007-12-28 05:31:15 +00001907 Expr *Base = B->getLHS();
1908
1909 // Determine which argument is the real pointer base. It could be
1910 // the RHS argument instead of the LHS.
1911 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00001912
Chris Lattner934edb22007-12-28 05:31:15 +00001913 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001914 return EvalAddr(Base, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001915 }
Steve Naroff2752a172008-09-10 19:17:48 +00001916
Chris Lattner934edb22007-12-28 05:31:15 +00001917 // For conditional operators we need to see if either the LHS or RHS are
1918 // valid DeclRefExpr*s. If one of them is valid, we return it.
1919 case Stmt::ConditionalOperatorClass: {
1920 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001921
Chris Lattner934edb22007-12-28 05:31:15 +00001922 // Handle the GNU extension for missing LHS.
Douglas Gregor270b2ef2010-10-21 16:21:08 +00001923 if (Expr *lhsExpr = C->getLHS()) {
1924 // In C++, we can have a throw-expression, which has 'void' type.
1925 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001926 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00001927 return LHS;
1928 }
Chris Lattner934edb22007-12-28 05:31:15 +00001929
Douglas Gregor270b2ef2010-10-21 16:21:08 +00001930 // In C++, we can have a throw-expression, which has 'void' type.
1931 if (C->getRHS()->getType()->isVoidType())
1932 return NULL;
1933
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001934 return EvalAddr(C->getRHS(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001935 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001936
1937 case Stmt::BlockExprClass:
1938 if (cast<BlockExpr>(E)->hasBlockDeclRefExprs())
1939 return E; // local block.
1940 return NULL;
1941
1942 case Stmt::AddrLabelExprClass:
1943 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00001944
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001945 // For casts, we need to handle conversions from arrays to
1946 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00001947 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00001948 case Stmt::CStyleCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00001949 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00001950 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001951 QualType T = SubExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001952
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001953 if (SubExpr->getType()->isPointerType() ||
1954 SubExpr->getType()->isBlockPointerType() ||
1955 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001956 return EvalAddr(SubExpr, refVars);
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001957 else if (T->isArrayType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001958 return EvalVal(SubExpr, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001959 else
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001960 return 0;
Chris Lattner934edb22007-12-28 05:31:15 +00001961 }
Mike Stump11289f42009-09-09 15:08:12 +00001962
Chris Lattner934edb22007-12-28 05:31:15 +00001963 // C++ casts. For dynamic casts, static casts, and const casts, we
1964 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregore200adc2008-10-27 19:41:14 +00001965 // through the cast. In the case the dynamic cast doesn't fail (and
1966 // return NULL), we take the conservative route and report cases
Chris Lattner934edb22007-12-28 05:31:15 +00001967 // where we return the address of a stack variable. For Reinterpre
Douglas Gregore200adc2008-10-27 19:41:14 +00001968 // FIXME: The comment about is wrong; we're not always converting
1969 // from pointer to pointer. I'm guessing that this code should also
Mike Stump11289f42009-09-09 15:08:12 +00001970 // handle references to objects.
1971 case Stmt::CXXStaticCastExprClass:
1972 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00001973 case Stmt::CXXConstCastExprClass:
1974 case Stmt::CXXReinterpretCastExprClass: {
1975 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001976 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001977 return EvalAddr(S, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001978 else
1979 return NULL;
Chris Lattner934edb22007-12-28 05:31:15 +00001980 }
Mike Stump11289f42009-09-09 15:08:12 +00001981
Chris Lattner934edb22007-12-28 05:31:15 +00001982 // Everything else: we simply don't reason about them.
1983 default:
1984 return NULL;
1985 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001986}
Mike Stump11289f42009-09-09 15:08:12 +00001987
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001988
1989/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1990/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001991static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenekb7861562010-08-04 20:01:07 +00001992do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00001993 // We should only be called for evaluating non-pointer expressions, or
1994 // expressions with a pointer type that are not used as references but instead
1995 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00001996
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001997 // Our "symbolic interpreter" is just a dispatch off the currently
1998 // viewed AST node. We then recursively traverse the AST by calling
1999 // EvalAddr and EvalVal appropriately.
2000 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002001 case Stmt::ImplicitCastExprClass: {
2002 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00002003 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002004 E = IE->getSubExpr();
2005 continue;
2006 }
2007 return NULL;
2008 }
2009
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002010 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002011 // When we hit a DeclRefExpr we are looking at code that refers to a
2012 // variable's name. If it's not a reference variable we check if it has
2013 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002014 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002015
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002016 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002017 if (V->hasLocalStorage()) {
2018 if (!V->getType()->isReferenceType())
2019 return DR;
2020
2021 // Reference variable, follow through to the expression that
2022 // it points to.
2023 if (V->hasInit()) {
2024 // Add the reference variable to the "trail".
2025 refVars.push_back(DR);
2026 return EvalVal(V->getInit(), refVars);
2027 }
2028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002030 return NULL;
2031 }
Mike Stump11289f42009-09-09 15:08:12 +00002032
Ted Kremenekb7861562010-08-04 20:01:07 +00002033 case Stmt::ParenExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002034 // Ignore parentheses.
Ted Kremenekb7861562010-08-04 20:01:07 +00002035 E = cast<ParenExpr>(E)->getSubExpr();
2036 continue;
2037 }
Mike Stump11289f42009-09-09 15:08:12 +00002038
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002039 case Stmt::UnaryOperatorClass: {
2040 // The only unary operator that make sense to handle here
2041 // is Deref. All others don't resolve to a "name." This includes
2042 // handling all sorts of rvalues passed to a unary operator.
2043 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002044
John McCalle3027922010-08-25 11:45:40 +00002045 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002046 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002047
2048 return NULL;
2049 }
Mike Stump11289f42009-09-09 15:08:12 +00002050
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002051 case Stmt::ArraySubscriptExprClass: {
2052 // Array subscripts are potential references to data on the stack. We
2053 // retrieve the DeclRefExpr* for the array variable if it indeed
2054 // has local storage.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002055 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002056 }
Mike Stump11289f42009-09-09 15:08:12 +00002057
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002058 case Stmt::ConditionalOperatorClass: {
2059 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002060 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002061 ConditionalOperator *C = cast<ConditionalOperator>(E);
2062
Anders Carlsson801c5c72007-11-30 19:04:31 +00002063 // Handle the GNU extension for missing LHS.
2064 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002065 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson801c5c72007-11-30 19:04:31 +00002066 return LHS;
2067
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002068 return EvalVal(C->getRHS(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002069 }
Mike Stump11289f42009-09-09 15:08:12 +00002070
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002071 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002072 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002073 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002074
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002075 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00002076 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002077 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00002078
2079 // Check whether the member type is itself a reference, in which case
2080 // we're not going to refer to the member, but to what the member refers to.
2081 if (M->getMemberDecl()->getType()->isReferenceType())
2082 return NULL;
2083
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002084 return EvalVal(M->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002085 }
Mike Stump11289f42009-09-09 15:08:12 +00002086
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002087 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002088 // Check that we don't return or take the address of a reference to a
2089 // temporary. This is only useful in C++.
2090 if (!E->isTypeDependent() && E->isRValue())
2091 return E;
2092
2093 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002094 return NULL;
2095 }
Ted Kremenekb7861562010-08-04 20:01:07 +00002096} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002097}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002098
2099//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2100
2101/// Check for comparisons of floating point operands using != and ==.
2102/// Issue a warning if these are no self-comparisons, as they are not likely
2103/// to do what the programmer intended.
2104void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2105 bool EmitWarning = true;
Mike Stump11289f42009-09-09 15:08:12 +00002106
John McCall34376a62010-12-04 03:47:34 +00002107 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2108 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002109
2110 // Special case: check for x == x (which is OK).
2111 // Do not emit warnings for such cases.
2112 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2113 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2114 if (DRL->getDecl() == DRR->getDecl())
2115 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002116
2117
Ted Kremenekeda40e22007-11-29 00:59:04 +00002118 // Special case: check for comparisons against literals that can be exactly
2119 // represented by APFloat. In such cases, do not emit a warning. This
2120 // is a heuristic: often comparison against such literals are used to
2121 // detect if a value in a variable has not changed. This clearly can
2122 // lead to false negatives.
2123 if (EmitWarning) {
2124 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2125 if (FLL->isExact())
2126 EmitWarning = false;
Mike Stump12b8ce12009-08-04 21:02:39 +00002127 } else
Ted Kremenekeda40e22007-11-29 00:59:04 +00002128 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2129 if (FLR->isExact())
2130 EmitWarning = false;
2131 }
2132 }
Mike Stump11289f42009-09-09 15:08:12 +00002133
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002134 // Check for comparisons with builtin types.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002135 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002136 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00002137 if (CL->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002138 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002139
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002140 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002141 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00002142 if (CR->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002143 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002144
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002145 // Emit the diagnostic.
2146 if (EmitWarning)
Chris Lattner3b054132008-11-19 05:08:23 +00002147 Diag(loc, diag::warn_floatingpoint_eq)
2148 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002149}
John McCallca01b222010-01-04 23:21:16 +00002150
John McCall70aa5392010-01-06 05:24:50 +00002151//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2152//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00002153
John McCall70aa5392010-01-06 05:24:50 +00002154namespace {
John McCallca01b222010-01-04 23:21:16 +00002155
John McCall70aa5392010-01-06 05:24:50 +00002156/// Structure recording the 'active' range of an integer-valued
2157/// expression.
2158struct IntRange {
2159 /// The number of bits active in the int.
2160 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00002161
John McCall70aa5392010-01-06 05:24:50 +00002162 /// True if the int is known not to have negative values.
2163 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00002164
John McCall70aa5392010-01-06 05:24:50 +00002165 IntRange(unsigned Width, bool NonNegative)
2166 : Width(Width), NonNegative(NonNegative)
2167 {}
John McCallca01b222010-01-04 23:21:16 +00002168
John McCall817d4af2010-11-10 23:38:19 +00002169 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00002170 static IntRange forBoolType() {
2171 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00002172 }
2173
John McCall817d4af2010-11-10 23:38:19 +00002174 /// Returns the range of an opaque value of the given integral type.
2175 static IntRange forValueOfType(ASTContext &C, QualType T) {
2176 return forValueOfCanonicalType(C,
2177 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00002178 }
2179
John McCall817d4af2010-11-10 23:38:19 +00002180 /// Returns the range of an opaque value of a canonical integral type.
2181 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00002182 assert(T->isCanonicalUnqualified());
2183
2184 if (const VectorType *VT = dyn_cast<VectorType>(T))
2185 T = VT->getElementType().getTypePtr();
2186 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2187 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00002188
John McCall18a2c2c2010-11-09 22:22:12 +00002189 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00002190 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2191 EnumDecl *Enum = ET->getDecl();
John McCall18a2c2c2010-11-09 22:22:12 +00002192 if (!Enum->isDefinition())
2193 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2194
John McCallcc7e5bf2010-05-06 08:58:33 +00002195 unsigned NumPositive = Enum->getNumPositiveBits();
2196 unsigned NumNegative = Enum->getNumNegativeBits();
2197
2198 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2199 }
John McCall70aa5392010-01-06 05:24:50 +00002200
2201 const BuiltinType *BT = cast<BuiltinType>(T);
2202 assert(BT->isInteger());
2203
2204 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2205 }
2206
John McCall817d4af2010-11-10 23:38:19 +00002207 /// Returns the "target" range of a canonical integral type, i.e.
2208 /// the range of values expressible in the type.
2209 ///
2210 /// This matches forValueOfCanonicalType except that enums have the
2211 /// full range of their type, not the range of their enumerators.
2212 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2213 assert(T->isCanonicalUnqualified());
2214
2215 if (const VectorType *VT = dyn_cast<VectorType>(T))
2216 T = VT->getElementType().getTypePtr();
2217 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2218 T = CT->getElementType().getTypePtr();
2219 if (const EnumType *ET = dyn_cast<EnumType>(T))
2220 T = ET->getDecl()->getIntegerType().getTypePtr();
2221
2222 const BuiltinType *BT = cast<BuiltinType>(T);
2223 assert(BT->isInteger());
2224
2225 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2226 }
2227
2228 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00002229 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00002230 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00002231 L.NonNegative && R.NonNegative);
2232 }
2233
John McCall817d4af2010-11-10 23:38:19 +00002234 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00002235 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00002236 return IntRange(std::min(L.Width, R.Width),
2237 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00002238 }
2239};
2240
2241IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2242 if (value.isSigned() && value.isNegative())
2243 return IntRange(value.getMinSignedBits(), false);
2244
2245 if (value.getBitWidth() > MaxWidth)
2246 value.trunc(MaxWidth);
2247
2248 // isNonNegative() just checks the sign bit without considering
2249 // signedness.
2250 return IntRange(value.getActiveBits(), true);
2251}
2252
John McCall74430522010-01-06 22:57:21 +00002253IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCall70aa5392010-01-06 05:24:50 +00002254 unsigned MaxWidth) {
2255 if (result.isInt())
2256 return GetValueRange(C, result.getInt(), MaxWidth);
2257
2258 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00002259 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2260 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2261 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2262 R = IntRange::join(R, El);
2263 }
John McCall70aa5392010-01-06 05:24:50 +00002264 return R;
2265 }
2266
2267 if (result.isComplexInt()) {
2268 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2269 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2270 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00002271 }
2272
2273 // This can happen with lossless casts to intptr_t of "based" lvalues.
2274 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00002275 // FIXME: The only reason we need to pass the type in here is to get
2276 // the sign right on this one case. It would be nice if APValue
2277 // preserved this.
John McCall70aa5392010-01-06 05:24:50 +00002278 assert(result.isLValue());
John McCall74430522010-01-06 22:57:21 +00002279 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall263a48b2010-01-04 23:31:57 +00002280}
John McCall70aa5392010-01-06 05:24:50 +00002281
2282/// Pseudo-evaluate the given integer expression, estimating the
2283/// range of values it might take.
2284///
2285/// \param MaxWidth - the width to which the value will be truncated
2286IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2287 E = E->IgnoreParens();
2288
2289 // Try a full evaluation first.
2290 Expr::EvalResult result;
2291 if (E->Evaluate(result, C))
John McCall74430522010-01-06 22:57:21 +00002292 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00002293
2294 // I think we only want to look through implicit casts here; if the
2295 // user has an explicit widening cast, we should treat the value as
2296 // being of the new, wider type.
2297 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002298 if (CE->getCastKind() == CK_NoOp)
John McCall70aa5392010-01-06 05:24:50 +00002299 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2300
John McCall817d4af2010-11-10 23:38:19 +00002301 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCall70aa5392010-01-06 05:24:50 +00002302
John McCalle3027922010-08-25 11:45:40 +00002303 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00002304
John McCall70aa5392010-01-06 05:24:50 +00002305 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00002306 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00002307 return OutputTypeRange;
2308
2309 IntRange SubRange
2310 = GetExprRange(C, CE->getSubExpr(),
2311 std::min(MaxWidth, OutputTypeRange.Width));
2312
2313 // Bail out if the subexpr's range is as wide as the cast type.
2314 if (SubRange.Width >= OutputTypeRange.Width)
2315 return OutputTypeRange;
2316
2317 // Otherwise, we take the smaller width, and we're non-negative if
2318 // either the output type or the subexpr is.
2319 return IntRange(SubRange.Width,
2320 SubRange.NonNegative || OutputTypeRange.NonNegative);
2321 }
2322
2323 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2324 // If we can fold the condition, just take that operand.
2325 bool CondResult;
2326 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2327 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2328 : CO->getFalseExpr(),
2329 MaxWidth);
2330
2331 // Otherwise, conservatively merge.
2332 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2333 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2334 return IntRange::join(L, R);
2335 }
2336
2337 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2338 switch (BO->getOpcode()) {
2339
2340 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00002341 case BO_LAnd:
2342 case BO_LOr:
2343 case BO_LT:
2344 case BO_GT:
2345 case BO_LE:
2346 case BO_GE:
2347 case BO_EQ:
2348 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00002349 return IntRange::forBoolType();
2350
John McCallff96ccd2010-02-23 19:22:29 +00002351 // The type of these compound assignments is the type of the LHS,
2352 // so the RHS is not necessarily an integer.
John McCalle3027922010-08-25 11:45:40 +00002353 case BO_MulAssign:
2354 case BO_DivAssign:
2355 case BO_RemAssign:
2356 case BO_AddAssign:
2357 case BO_SubAssign:
John McCall817d4af2010-11-10 23:38:19 +00002358 return IntRange::forValueOfType(C, E->getType());
John McCallff96ccd2010-02-23 19:22:29 +00002359
John McCall70aa5392010-01-06 05:24:50 +00002360 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00002361 case BO_PtrMemD:
2362 case BO_PtrMemI:
John McCall817d4af2010-11-10 23:38:19 +00002363 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002364
John McCall2ce81ad2010-01-06 22:07:33 +00002365 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00002366 case BO_And:
2367 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00002368 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2369 GetExprRange(C, BO->getRHS(), MaxWidth));
2370
John McCall70aa5392010-01-06 05:24:50 +00002371 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00002372 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00002373 // ...except that we want to treat '1 << (blah)' as logically
2374 // positive. It's an important idiom.
2375 if (IntegerLiteral *I
2376 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2377 if (I->getValue() == 1) {
John McCall817d4af2010-11-10 23:38:19 +00002378 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall1bff9932010-04-07 01:14:35 +00002379 return IntRange(R.Width, /*NonNegative*/ true);
2380 }
2381 }
2382 // fallthrough
2383
John McCalle3027922010-08-25 11:45:40 +00002384 case BO_ShlAssign:
John McCall817d4af2010-11-10 23:38:19 +00002385 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002386
John McCall2ce81ad2010-01-06 22:07:33 +00002387 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00002388 case BO_Shr:
2389 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00002390 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2391
2392 // If the shift amount is a positive constant, drop the width by
2393 // that much.
2394 llvm::APSInt shift;
2395 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2396 shift.isNonNegative()) {
2397 unsigned zext = shift.getZExtValue();
2398 if (zext >= L.Width)
2399 L.Width = (L.NonNegative ? 0 : 1);
2400 else
2401 L.Width -= zext;
2402 }
2403
2404 return L;
2405 }
2406
2407 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00002408 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00002409 return GetExprRange(C, BO->getRHS(), MaxWidth);
2410
John McCall2ce81ad2010-01-06 22:07:33 +00002411 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00002412 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00002413 if (BO->getLHS()->getType()->isPointerType())
John McCall817d4af2010-11-10 23:38:19 +00002414 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002415 // fallthrough
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002416
John McCall70aa5392010-01-06 05:24:50 +00002417 default:
2418 break;
2419 }
2420
2421 // Treat every other operator as if it were closed on the
2422 // narrowest type that encompasses both operands.
2423 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2424 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2425 return IntRange::join(L, R);
2426 }
2427
2428 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2429 switch (UO->getOpcode()) {
2430 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00002431 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00002432 return IntRange::forBoolType();
2433
2434 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00002435 case UO_Deref:
2436 case UO_AddrOf: // should be impossible
John McCall817d4af2010-11-10 23:38:19 +00002437 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002438
2439 default:
2440 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2441 }
2442 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002443
2444 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall817d4af2010-11-10 23:38:19 +00002445 IntRange::forValueOfType(C, E->getType());
Douglas Gregor882211c2010-04-28 22:16:22 +00002446 }
John McCall70aa5392010-01-06 05:24:50 +00002447
2448 FieldDecl *BitField = E->getBitField();
2449 if (BitField) {
2450 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2451 unsigned BitWidth = BitWidthAP.getZExtValue();
2452
2453 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2454 }
2455
John McCall817d4af2010-11-10 23:38:19 +00002456 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002457}
John McCall263a48b2010-01-04 23:31:57 +00002458
John McCallcc7e5bf2010-05-06 08:58:33 +00002459IntRange GetExprRange(ASTContext &C, Expr *E) {
2460 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2461}
2462
John McCall263a48b2010-01-04 23:31:57 +00002463/// Checks whether the given value, which currently has the given
2464/// source semantics, has the same value when coerced through the
2465/// target semantics.
John McCall70aa5392010-01-06 05:24:50 +00002466bool IsSameFloatAfterCast(const llvm::APFloat &value,
2467 const llvm::fltSemantics &Src,
2468 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00002469 llvm::APFloat truncated = value;
2470
2471 bool ignored;
2472 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2473 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2474
2475 return truncated.bitwiseIsEqual(value);
2476}
2477
2478/// Checks whether the given value, which currently has the given
2479/// source semantics, has the same value when coerced through the
2480/// target semantics.
2481///
2482/// The value might be a vector of floats (or a complex number).
John McCall70aa5392010-01-06 05:24:50 +00002483bool IsSameFloatAfterCast(const APValue &value,
2484 const llvm::fltSemantics &Src,
2485 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00002486 if (value.isFloat())
2487 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2488
2489 if (value.isVector()) {
2490 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2491 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2492 return false;
2493 return true;
2494 }
2495
2496 assert(value.isComplexFloat());
2497 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2498 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2499}
2500
John McCallacf0ee52010-10-08 02:01:28 +00002501void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002502
Ted Kremenek6274be42010-09-23 21:43:44 +00002503static bool IsZero(Sema &S, Expr *E) {
2504 // Suppress cases where we are comparing against an enum constant.
2505 if (const DeclRefExpr *DR =
2506 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2507 if (isa<EnumConstantDecl>(DR->getDecl()))
2508 return false;
2509
2510 // Suppress cases where the '0' value is expanded from a macro.
2511 if (E->getLocStart().isMacroID())
2512 return false;
2513
John McCallcc7e5bf2010-05-06 08:58:33 +00002514 llvm::APSInt Value;
2515 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2516}
2517
John McCall2551c1b2010-10-06 00:25:24 +00002518static bool HasEnumType(Expr *E) {
2519 // Strip off implicit integral promotions.
2520 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00002521 if (ICE->getCastKind() != CK_IntegralCast &&
2522 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00002523 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00002524 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00002525 }
2526
2527 return E->getType()->isEnumeralType();
2528}
2529
John McCallcc7e5bf2010-05-06 08:58:33 +00002530void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002531 BinaryOperatorKind op = E->getOpcode();
2532 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002533 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002534 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002535 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00002536 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002537 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002538 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002539 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00002540 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002541 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002542 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002543 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00002544 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002545 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002546 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002547 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2548 }
2549}
2550
2551/// Analyze the operands of the given comparison. Implements the
2552/// fallback case from AnalyzeComparison.
2553void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00002554 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2555 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00002556}
John McCall263a48b2010-01-04 23:31:57 +00002557
John McCallca01b222010-01-04 23:21:16 +00002558/// \brief Implements -Wsign-compare.
2559///
2560/// \param lex the left-hand expression
2561/// \param rex the right-hand expression
2562/// \param OpLoc the location of the joining operator
John McCall71d8d9b2010-03-11 19:43:18 +00002563/// \param BinOpc binary opcode or 0
John McCallcc7e5bf2010-05-06 08:58:33 +00002564void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2565 // The type the comparison is being performed in.
2566 QualType T = E->getLHS()->getType();
2567 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2568 && "comparison with mismatched types");
John McCallca01b222010-01-04 23:21:16 +00002569
John McCallcc7e5bf2010-05-06 08:58:33 +00002570 // We don't do anything special if this isn't an unsigned integral
2571 // comparison: we're only interested in integral comparisons, and
2572 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002573 if (!T->hasUnsignedIntegerRepresentation())
John McCallcc7e5bf2010-05-06 08:58:33 +00002574 return AnalyzeImpConvsInComparison(S, E);
John McCall70aa5392010-01-06 05:24:50 +00002575
John McCallcc7e5bf2010-05-06 08:58:33 +00002576 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2577 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallca01b222010-01-04 23:21:16 +00002578
John McCallcc7e5bf2010-05-06 08:58:33 +00002579 // Check to see if one of the (unmodified) operands is of different
2580 // signedness.
2581 Expr *signedOperand, *unsignedOperand;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002582 if (lex->getType()->hasSignedIntegerRepresentation()) {
2583 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00002584 "unsigned comparison between two signed integer expressions?");
2585 signedOperand = lex;
2586 unsignedOperand = rex;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002587 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002588 signedOperand = rex;
2589 unsignedOperand = lex;
John McCallca01b222010-01-04 23:21:16 +00002590 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00002591 CheckTrivialUnsignedComparison(S, E);
2592 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00002593 }
2594
John McCallcc7e5bf2010-05-06 08:58:33 +00002595 // Otherwise, calculate the effective range of the signed operand.
2596 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00002597
John McCallcc7e5bf2010-05-06 08:58:33 +00002598 // Go ahead and analyze implicit conversions in the operands. Note
2599 // that we skip the implicit conversions on both sides.
John McCallacf0ee52010-10-08 02:01:28 +00002600 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2601 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00002602
John McCallcc7e5bf2010-05-06 08:58:33 +00002603 // If the signed range is non-negative, -Wsign-compare won't fire,
2604 // but we should still check for comparisons which are always true
2605 // or false.
2606 if (signedRange.NonNegative)
2607 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00002608
2609 // For (in)equality comparisons, if the unsigned operand is a
2610 // constant which cannot collide with a overflowed signed operand,
2611 // then reinterpreting the signed operand as unsigned will not
2612 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00002613 if (E->isEqualityOp()) {
2614 unsigned comparisonWidth = S.Context.getIntWidth(T);
2615 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00002616
John McCallcc7e5bf2010-05-06 08:58:33 +00002617 // We should never be unable to prove that the unsigned operand is
2618 // non-negative.
2619 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2620
2621 if (unsignedRange.Width < comparisonWidth)
2622 return;
2623 }
2624
2625 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2626 << lex->getType() << rex->getType()
2627 << lex->getSourceRange() << rex->getSourceRange();
John McCallca01b222010-01-04 23:21:16 +00002628}
2629
John McCall1f425642010-11-11 03:21:53 +00002630/// Analyzes an attempt to assign the given value to a bitfield.
2631///
2632/// Returns true if there was something fishy about the attempt.
2633bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2634 SourceLocation InitLoc) {
2635 assert(Bitfield->isBitField());
2636 if (Bitfield->isInvalidDecl())
2637 return false;
2638
John McCalldeebbcf2010-11-11 05:33:51 +00002639 // White-list bool bitfields.
2640 if (Bitfield->getType()->isBooleanType())
2641 return false;
2642
John McCall1f425642010-11-11 03:21:53 +00002643 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2644
2645 llvm::APSInt Width(32);
2646 Expr::EvalResult InitValue;
2647 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCalldeebbcf2010-11-11 05:33:51 +00002648 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall1f425642010-11-11 03:21:53 +00002649 !InitValue.Val.isInt())
2650 return false;
2651
2652 const llvm::APSInt &Value = InitValue.Val.getInt();
2653 unsigned OriginalWidth = Value.getBitWidth();
2654 unsigned FieldWidth = Width.getZExtValue();
2655
2656 if (OriginalWidth <= FieldWidth)
2657 return false;
2658
2659 llvm::APSInt TruncatedValue = Value;
2660 TruncatedValue.trunc(FieldWidth);
2661
2662 // It's fairly common to write values into signed bitfields
2663 // that, if sign-extended, would end up becoming a different
2664 // value. We don't want to warn about that.
2665 if (Value.isSigned() && Value.isNegative())
2666 TruncatedValue.sext(OriginalWidth);
2667 else
2668 TruncatedValue.zext(OriginalWidth);
2669
2670 if (Value == TruncatedValue)
2671 return false;
2672
2673 std::string PrettyValue = Value.toString(10);
2674 std::string PrettyTrunc = TruncatedValue.toString(10);
2675
2676 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2677 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2678 << Init->getSourceRange();
2679
2680 return true;
2681}
2682
John McCalld2a53122010-11-09 23:24:47 +00002683/// Analyze the given simple or compound assignment for warning-worthy
2684/// operations.
2685void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2686 // Just recurse on the LHS.
2687 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2688
2689 // We want to recurse on the RHS as normal unless we're assigning to
2690 // a bitfield.
2691 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall1f425642010-11-11 03:21:53 +00002692 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2693 E->getOperatorLoc())) {
2694 // Recurse, ignoring any implicit conversions on the RHS.
2695 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2696 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00002697 }
2698 }
2699
2700 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2701}
2702
John McCall263a48b2010-01-04 23:31:57 +00002703/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCallacf0ee52010-10-08 02:01:28 +00002704void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2705 unsigned diag) {
2706 S.Diag(E->getExprLoc(), diag)
2707 << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
John McCall263a48b2010-01-04 23:31:57 +00002708}
2709
John McCall18a2c2c2010-11-09 22:22:12 +00002710std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2711 if (!Range.Width) return "0";
2712
2713 llvm::APSInt ValueInRange = Value;
2714 ValueInRange.setIsSigned(!Range.NonNegative);
2715 ValueInRange.trunc(Range.Width);
2716 return ValueInRange.toString(10);
2717}
2718
John McCallcc7e5bf2010-05-06 08:58:33 +00002719void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00002720 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002721 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00002722
John McCallcc7e5bf2010-05-06 08:58:33 +00002723 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2724 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2725 if (Source == Target) return;
2726 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00002727
John McCallacf0ee52010-10-08 02:01:28 +00002728 // If the conversion context location is invalid or instantiated
2729 // from a system macro, don't complain.
2730 if (CC.isInvalid() ||
2731 (CC.isMacroID() && S.Context.getSourceManager().isInSystemHeader(
2732 S.Context.getSourceManager().getSpellingLoc(CC))))
2733 return;
2734
John McCall263a48b2010-01-04 23:31:57 +00002735 // Never diagnose implicit casts to bool.
2736 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2737 return;
2738
2739 // Strip vector types.
2740 if (isa<VectorType>(Source)) {
2741 if (!isa<VectorType>(Target))
John McCallacf0ee52010-10-08 02:01:28 +00002742 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
John McCall263a48b2010-01-04 23:31:57 +00002743
2744 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2745 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2746 }
2747
2748 // Strip complex types.
2749 if (isa<ComplexType>(Source)) {
2750 if (!isa<ComplexType>(Target))
John McCallacf0ee52010-10-08 02:01:28 +00002751 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
John McCall263a48b2010-01-04 23:31:57 +00002752
2753 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2754 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2755 }
2756
2757 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2758 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2759
2760 // If the source is floating point...
2761 if (SourceBT && SourceBT->isFloatingPoint()) {
2762 // ...and the target is floating point...
2763 if (TargetBT && TargetBT->isFloatingPoint()) {
2764 // ...then warn if we're dropping FP rank.
2765
2766 // Builtin FP kinds are ordered by increasing FP rank.
2767 if (SourceBT->getKind() > TargetBT->getKind()) {
2768 // Don't warn about float constants that are precisely
2769 // representable in the target type.
2770 Expr::EvalResult result;
John McCallcc7e5bf2010-05-06 08:58:33 +00002771 if (E->Evaluate(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00002772 // Value might be a float, a float vector, or a float complex.
2773 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00002774 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2775 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00002776 return;
2777 }
2778
John McCallacf0ee52010-10-08 02:01:28 +00002779 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00002780 }
2781 return;
2782 }
2783
2784 // If the target is integral, always warn.
2785 if ((TargetBT && TargetBT->isInteger()))
2786 // TODO: don't warn for integer values?
John McCallacf0ee52010-10-08 02:01:28 +00002787 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
John McCall263a48b2010-01-04 23:31:57 +00002788
2789 return;
2790 }
2791
John McCall70aa5392010-01-06 05:24:50 +00002792 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall263a48b2010-01-04 23:31:57 +00002793 return;
2794
John McCallcc7e5bf2010-05-06 08:58:33 +00002795 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00002796 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00002797
2798 if (SourceRange.Width > TargetRange.Width) {
John McCall18a2c2c2010-11-09 22:22:12 +00002799 // If the source is a constant, use a default-on diagnostic.
2800 // TODO: this should happen for bitfield stores, too.
2801 llvm::APSInt Value(32);
2802 if (E->isIntegerConstantExpr(Value, S.Context)) {
2803 std::string PrettySourceValue = Value.toString(10);
2804 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2805
2806 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2807 << PrettySourceValue << PrettyTargetValue
2808 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2809 return;
2810 }
2811
John McCall263a48b2010-01-04 23:31:57 +00002812 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2813 // and by god we'll let them.
John McCall70aa5392010-01-06 05:24:50 +00002814 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallacf0ee52010-10-08 02:01:28 +00002815 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2816 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00002817 }
2818
2819 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2820 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2821 SourceRange.Width == TargetRange.Width)) {
2822 unsigned DiagID = diag::warn_impcast_integer_sign;
2823
2824 // Traditionally, gcc has warned about this under -Wsign-compare.
2825 // We also want to warn about it in -Wconversion.
2826 // So if -Wconversion is off, use a completely identical diagnostic
2827 // in the sign-compare group.
2828 // The conditional-checking code will
2829 if (ICContext) {
2830 DiagID = diag::warn_impcast_integer_sign_conditional;
2831 *ICContext = true;
2832 }
2833
John McCallacf0ee52010-10-08 02:01:28 +00002834 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00002835 }
2836
2837 return;
2838}
2839
John McCallcc7e5bf2010-05-06 08:58:33 +00002840void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2841
2842void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00002843 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002844 E = E->IgnoreParenImpCasts();
2845
2846 if (isa<ConditionalOperator>(E))
2847 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2848
John McCallacf0ee52010-10-08 02:01:28 +00002849 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002850 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00002851 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00002852 return;
2853}
2854
2855void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00002856 SourceLocation CC = E->getQuestionLoc();
2857
2858 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002859
2860 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00002861 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2862 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00002863
2864 // If -Wconversion would have warned about either of the candidates
2865 // for a signedness conversion to the context type...
2866 if (!Suspicious) return;
2867
2868 // ...but it's currently ignored...
2869 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional))
2870 return;
2871
2872 // ...and -Wsign-compare isn't...
2873 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional))
2874 return;
2875
2876 // ...then check whether it would have warned about either of the
2877 // candidates for a signedness conversion to the condition type.
2878 if (E->getType() != T) {
2879 Suspicious = false;
2880 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00002881 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00002882 if (!Suspicious)
2883 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00002884 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00002885 if (!Suspicious)
2886 return;
2887 }
2888
2889 // If so, emit a diagnostic under -Wsign-compare.
2890 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2891 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2892 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2893 << lex->getType() << rex->getType()
2894 << lex->getSourceRange() << rex->getSourceRange();
2895}
2896
2897/// AnalyzeImplicitConversions - Find and report any interesting
2898/// implicit conversions in the given expression. There are a couple
2899/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00002900void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002901 QualType T = OrigE->getType();
2902 Expr *E = OrigE->IgnoreParenImpCasts();
2903
2904 // For conditional operators, we analyze the arguments as if they
2905 // were being fed directly into the output.
2906 if (isa<ConditionalOperator>(E)) {
2907 ConditionalOperator *CO = cast<ConditionalOperator>(E);
2908 CheckConditionalOperator(S, CO, T);
2909 return;
2910 }
2911
2912 // Go ahead and check any implicit conversions we might have skipped.
2913 // The non-canonical typecheck is just an optimization;
2914 // CheckImplicitConversion will filter out dead implicit conversions.
2915 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00002916 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002917
2918 // Now continue drilling into this expression.
2919
2920 // Skip past explicit casts.
2921 if (isa<ExplicitCastExpr>(E)) {
2922 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00002923 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002924 }
2925
John McCalld2a53122010-11-09 23:24:47 +00002926 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2927 // Do a somewhat different check with comparison operators.
2928 if (BO->isComparisonOp())
2929 return AnalyzeComparison(S, BO);
2930
2931 // And with assignments and compound assignments.
2932 if (BO->isAssignmentOp())
2933 return AnalyzeAssignment(S, BO);
2934 }
John McCallcc7e5bf2010-05-06 08:58:33 +00002935
2936 // These break the otherwise-useful invariant below. Fortunately,
2937 // we don't really need to recurse into them, because any internal
2938 // expressions should have been analyzed already when they were
2939 // built into statements.
2940 if (isa<StmtExpr>(E)) return;
2941
2942 // Don't descend into unevaluated contexts.
2943 if (isa<SizeOfAlignOfExpr>(E)) return;
2944
2945 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00002946 CC = E->getExprLoc();
John McCallcc7e5bf2010-05-06 08:58:33 +00002947 for (Stmt::child_iterator I = E->child_begin(), IE = E->child_end();
2948 I != IE; ++I)
John McCallacf0ee52010-10-08 02:01:28 +00002949 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002950}
2951
2952} // end anonymous namespace
2953
2954/// Diagnoses "dangerous" implicit conversions within the given
2955/// expression (which is a full expression). Implements -Wconversion
2956/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00002957///
2958/// \param CC the "context" location of the implicit conversion, i.e.
2959/// the most location of the syntactic entity requiring the implicit
2960/// conversion
2961void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002962 // Don't diagnose in unevaluated contexts.
2963 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2964 return;
2965
2966 // Don't diagnose for value- or type-dependent expressions.
2967 if (E->isTypeDependent() || E->isValueDependent())
2968 return;
2969
John McCallacf0ee52010-10-08 02:01:28 +00002970 // This is not the right CC for (e.g.) a variable initialization.
2971 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002972}
2973
John McCall1f425642010-11-11 03:21:53 +00002974void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
2975 FieldDecl *BitField,
2976 Expr *Init) {
2977 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
2978}
2979
Mike Stump0c2ec772010-01-21 03:59:47 +00002980/// CheckParmsForFunctionDef - Check that the parameters of the given
2981/// function are appropriate for the definition of a function. This
2982/// takes care of any checks that cannot be performed on the
2983/// declaration itself, e.g., that the types of each of the function
2984/// parameters are complete.
Douglas Gregorb524d902010-11-01 18:37:59 +00002985bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
2986 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00002987 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00002988 for (; P != PEnd; ++P) {
2989 ParmVarDecl *Param = *P;
2990
Mike Stump0c2ec772010-01-21 03:59:47 +00002991 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2992 // function declarator that is part of a function definition of
2993 // that function shall not have incomplete type.
2994 //
2995 // This is also C++ [dcl.fct]p6.
2996 if (!Param->isInvalidDecl() &&
2997 RequireCompleteType(Param->getLocation(), Param->getType(),
2998 diag::err_typecheck_decl_incomplete_type)) {
2999 Param->setInvalidDecl();
3000 HasInvalidParm = true;
3001 }
3002
3003 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3004 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00003005 if (CheckParameterNames &&
3006 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00003007 !Param->isImplicit() &&
3008 !getLangOptions().CPlusPlus)
3009 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00003010
3011 // C99 6.7.5.3p12:
3012 // If the function declarator is not part of a definition of that
3013 // function, parameters may have incomplete type and may use the [*]
3014 // notation in their sequences of declarator specifiers to specify
3015 // variable length array types.
3016 QualType PType = Param->getOriginalType();
3017 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3018 if (AT->getSizeModifier() == ArrayType::Star) {
3019 // FIXME: This diagnosic should point the the '[*]' if source-location
3020 // information is added for it.
3021 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3022 }
3023 }
Mike Stump0c2ec772010-01-21 03:59:47 +00003024 }
3025
3026 return HasInvalidParm;
3027}
John McCall2b5c1b22010-08-12 21:44:57 +00003028
3029/// CheckCastAlign - Implements -Wcast-align, which warns when a
3030/// pointer cast increases the alignment requirements.
3031void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3032 // This is actually a lot of work to potentially be doing on every
3033 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
3034 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align)
3035 == Diagnostic::Ignored)
3036 return;
3037
3038 // Ignore dependent types.
3039 if (T->isDependentType() || Op->getType()->isDependentType())
3040 return;
3041
3042 // Require that the destination be a pointer type.
3043 const PointerType *DestPtr = T->getAs<PointerType>();
3044 if (!DestPtr) return;
3045
3046 // If the destination has alignment 1, we're done.
3047 QualType DestPointee = DestPtr->getPointeeType();
3048 if (DestPointee->isIncompleteType()) return;
3049 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3050 if (DestAlign.isOne()) return;
3051
3052 // Require that the source be a pointer type.
3053 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3054 if (!SrcPtr) return;
3055 QualType SrcPointee = SrcPtr->getPointeeType();
3056
3057 // Whitelist casts from cv void*. We already implicitly
3058 // whitelisted casts to cv void*, since they have alignment 1.
3059 // Also whitelist casts involving incomplete types, which implicitly
3060 // includes 'void'.
3061 if (SrcPointee->isIncompleteType()) return;
3062
3063 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3064 if (SrcAlign >= DestAlign) return;
3065
3066 Diag(TRange.getBegin(), diag::warn_cast_align)
3067 << Op->getType() << T
3068 << static_cast<unsigned>(SrcAlign.getQuantity())
3069 << static_cast<unsigned>(DestAlign.getQuantity())
3070 << TRange << Op->getSourceRange();
3071}
3072