blob: 6f5d6f8ecaf346888fe1d17267391de95e96ff10 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
Ted Kremeneke0e53132010-01-28 23:39:18 +000016#include "clang/Analysis/Analyses/PrintfFormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000017#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000018#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000020#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000021#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000022#include "clang/AST/DeclObjC.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/AST/StmtObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000025#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000026#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000027#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/STLExtras.h"
Nate Begeman0d15c532010-06-13 04:47:52 +000029#include "llvm/ADT/StringExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000030#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000031#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000032#include "clang/Basic/TargetInfo.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000033#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000034using namespace clang;
35
Chris Lattner60800082009-02-18 17:49:48 +000036/// getLocationOfStringLiteralByte - Return a source location that points to the
37/// specified byte of the specified string literal.
38///
39/// Strings are amazingly complex. They can be formed from multiple tokens and
40/// can have escape sequences in them in addition to the usual trigraph and
41/// escaped newline business. This routine handles this complexity.
42///
43SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44 unsigned ByteNo) const {
45 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000046
Chris Lattner60800082009-02-18 17:49:48 +000047 // Loop over all of the tokens in this string until we find the one that
48 // contains the byte we're looking for.
49 unsigned TokNo = 0;
50 while (1) {
51 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
52 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000053
Chris Lattner60800082009-02-18 17:49:48 +000054 // Get the spelling of the string so that we can get the data that makes up
55 // the string literal, not the identifier for the macro it is potentially
56 // expanded through.
57 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
58
59 // Re-lex the token to get its length and original spelling.
60 std::pair<FileID, unsigned> LocInfo =
61 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
Douglas Gregorf715ca12010-03-16 00:06:06 +000062 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000063 llvm::StringRef Buffer = SourceMgr.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +000064 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +000065 return StrTokSpellingLoc;
66
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000067 const char *StrData = Buffer.data()+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000068
Chris Lattner60800082009-02-18 17:49:48 +000069 // Create a langops struct and enable trigraphs. This is sufficient for
70 // relexing tokens.
71 LangOptions LangOpts;
72 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000073
Chris Lattner60800082009-02-18 17:49:48 +000074 // Create a lexer starting at the beginning of this token.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000075 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.begin(), StrData,
76 Buffer.end());
Chris Lattner60800082009-02-18 17:49:48 +000077 Token TheTok;
78 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000079
Chris Lattner443e53c2009-02-18 19:26:42 +000080 // Use the StringLiteralParser to compute the length of the string in bytes.
Douglas Gregorb90f4b32010-05-26 05:35:51 +000081 StringLiteralParser SLP(&TheTok, 1, PP, /*Complain=*/false);
Chris Lattner443e53c2009-02-18 19:26:42 +000082 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000083
Chris Lattner2197c962009-02-18 18:52:52 +000084 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000085 if (ByteNo < TokNumBytes ||
86 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000087 unsigned Offset =
Douglas Gregorb90f4b32010-05-26 05:35:51 +000088 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP,
89 /*Complain=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattner719e6152009-02-18 19:21:10 +000091 // Now that we know the offset of the token in the spelling, use the
92 // preprocessor to get the offset in the original source.
93 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000094 }
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattner60800082009-02-18 17:49:48 +000096 // Move to the next string token.
97 ++TokNo;
98 ByteNo -= TokNumBytes;
99 }
100}
101
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000102/// CheckablePrintfAttr - does a function call have a "printf" attribute
103/// and arguments that merit checking?
104bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
105 if (Format->getType() == "printf") return true;
106 if (Format->getType() == "printf0") {
107 // printf0 allows null "format" string; if so don't check format/args
108 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000109 // Does the index refer to the implicit object argument?
110 if (isa<CXXMemberCallExpr>(TheCall)) {
111 if (format_idx == 0)
112 return false;
113 --format_idx;
114 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000115 if (format_idx < TheCall->getNumArgs()) {
116 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +0000117 if (!Format->isNullPointerConstant(Context,
118 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000119 return true;
120 }
121 }
122 return false;
123}
Chris Lattner60800082009-02-18 17:49:48 +0000124
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000126Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000127 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000128
Anders Carlssond406bf02009-08-16 01:56:34 +0000129 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000130 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000131 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000132 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000133 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000134 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000135 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000136 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000137 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 if (SemaBuiltinVAStart(TheCall))
139 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000140 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000141 case Builtin::BI__builtin_isgreater:
142 case Builtin::BI__builtin_isgreaterequal:
143 case Builtin::BI__builtin_isless:
144 case Builtin::BI__builtin_islessequal:
145 case Builtin::BI__builtin_islessgreater:
146 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000147 if (SemaBuiltinUnorderedCompare(TheCall))
148 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000149 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000150 case Builtin::BI__builtin_fpclassify:
151 if (SemaBuiltinFPClassification(TheCall, 6))
152 return ExprError();
153 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000154 case Builtin::BI__builtin_isfinite:
155 case Builtin::BI__builtin_isinf:
156 case Builtin::BI__builtin_isinf_sign:
157 case Builtin::BI__builtin_isnan:
158 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000159 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000160 return ExprError();
161 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000162 case Builtin::BI__builtin_return_address:
Eric Christopher691ebc32010-04-17 02:26:23 +0000163 case Builtin::BI__builtin_frame_address: {
164 llvm::APSInt Result;
165 if (SemaBuiltinConstantArg(TheCall, 0, Result))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000166 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000167 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000168 }
169 case Builtin::BI__builtin_eh_return_data_regno: {
170 llvm::APSInt Result;
171 if (SemaBuiltinConstantArg(TheCall, 0, Result))
Chris Lattner21fb98e2009-09-23 06:06:36 +0000172 return ExprError();
173 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000174 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000175 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000176 return SemaBuiltinShuffleVector(TheCall);
177 // TheCall will be freed by the smart pointer here, but that's fine, since
178 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000179 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000180 if (SemaBuiltinPrefetch(TheCall))
181 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000182 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000183 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000184 if (SemaBuiltinObjectSize(TheCall))
185 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000186 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000187 case Builtin::BI__builtin_longjmp:
188 if (SemaBuiltinLongjmp(TheCall))
189 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000190 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000191 case Builtin::BI__sync_fetch_and_add:
192 case Builtin::BI__sync_fetch_and_sub:
193 case Builtin::BI__sync_fetch_and_or:
194 case Builtin::BI__sync_fetch_and_and:
195 case Builtin::BI__sync_fetch_and_xor:
196 case Builtin::BI__sync_add_and_fetch:
197 case Builtin::BI__sync_sub_and_fetch:
198 case Builtin::BI__sync_and_and_fetch:
199 case Builtin::BI__sync_or_and_fetch:
200 case Builtin::BI__sync_xor_and_fetch:
201 case Builtin::BI__sync_val_compare_and_swap:
202 case Builtin::BI__sync_bool_compare_and_swap:
203 case Builtin::BI__sync_lock_test_and_set:
204 case Builtin::BI__sync_lock_release:
205 if (SemaBuiltinAtomicOverloaded(TheCall))
206 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000207 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000208 }
209
210 // Since the target specific builtins for each arch overlap, only check those
211 // of the arch we are compiling for.
212 if (BuiltinID >= Builtin::FirstTSBuiltin) {
213 switch (Context.Target.getTriple().getArch()) {
214 case llvm::Triple::arm:
215 case llvm::Triple::thumb:
216 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
217 return ExprError();
218 break;
219 case llvm::Triple::x86:
220 case llvm::Triple::x86_64:
221 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
222 return ExprError();
223 break;
224 default:
225 break;
226 }
227 }
228
229 return move(TheCallResult);
230}
231
232bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
233 switch (BuiltinID) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000234 case X86::BI__builtin_ia32_palignr128:
235 case X86::BI__builtin_ia32_palignr: {
236 llvm::APSInt Result;
237 if (SemaBuiltinConstantArg(TheCall, 2, Result))
Nate Begeman26a31422010-06-08 02:47:44 +0000238 return true;
Eric Christopher691ebc32010-04-17 02:26:23 +0000239 break;
240 }
Anders Carlsson71993dd2007-08-17 05:31:46 +0000241 }
Nate Begeman26a31422010-06-08 02:47:44 +0000242 return false;
243}
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Nate Begeman61eecf52010-06-14 05:21:25 +0000245// Get the valid immediate range for the specified NEON type code.
246static unsigned RFT(unsigned t, bool shift = false) {
247 bool quad = t & 0x10;
248
249 switch (t & 0x7) {
250 case 0: // i8
251 return shift ? 7 : (8 << quad) - 1;
252 case 1: // i16
253 return shift ? 15 : (4 << quad) - 1;
254 case 2: // i32
255 return shift ? 31 : (2 << quad) - 1;
256 case 3: // i64
257 return shift ? 63 : (1 << quad) - 1;
258 case 4: // f32
259 assert(!shift && "cannot shift float types!");
260 return (2 << quad) - 1;
261 case 5: // poly8
262 assert(!shift && "cannot shift polynomial types!");
263 return (8 << quad) - 1;
264 case 6: // poly16
265 assert(!shift && "cannot shift polynomial types!");
266 return (4 << quad) - 1;
267 case 7: // float16
268 assert(!shift && "cannot shift float types!");
269 return (4 << quad) - 1;
270 }
271 return 0;
272}
273
Nate Begeman26a31422010-06-08 02:47:44 +0000274bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000275 llvm::APSInt Result;
276
Nate Begeman0d15c532010-06-13 04:47:52 +0000277 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000278 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000279 switch (BuiltinID) {
Nate Begeman0d15c532010-06-13 04:47:52 +0000280 case ARM::BI__builtin_neon_vaba_v: mask = 0x707; break;
281 case ARM::BI__builtin_neon_vabaq_v: mask = 0x7070000; break;
282 case ARM::BI__builtin_neon_vabal_v: mask = 0xE0E0000; break;
283 case ARM::BI__builtin_neon_vabd_v: mask = 0x717; break;
284 case ARM::BI__builtin_neon_vabdq_v: mask = 0x7170000; break;
285 case ARM::BI__builtin_neon_vabdl_v: mask = 0xE0E0000; break;
286 case ARM::BI__builtin_neon_vabs_v: mask = 0x17; break;
287 case ARM::BI__builtin_neon_vabsq_v: mask = 0x170000; break;
288 case ARM::BI__builtin_neon_vaddhn_v: mask = 0x707; break;
289 case ARM::BI__builtin_neon_vaddl_v: mask = 0xE0E0000; break;
290 case ARM::BI__builtin_neon_vaddw_v: mask = 0xE0E0000; break;
291 case ARM::BI__builtin_neon_vcage_v: mask = 0x400; break;
292 case ARM::BI__builtin_neon_vcageq_v: mask = 0x4000000; break;
293 case ARM::BI__builtin_neon_vcagt_v: mask = 0x400; break;
294 case ARM::BI__builtin_neon_vcagtq_v: mask = 0x4000000; break;
295 case ARM::BI__builtin_neon_vcale_v: mask = 0x400; break;
296 case ARM::BI__builtin_neon_vcaleq_v: mask = 0x4000000; break;
297 case ARM::BI__builtin_neon_vcalt_v: mask = 0x400; break;
298 case ARM::BI__builtin_neon_vcaltq_v: mask = 0x4000000; break;
299 case ARM::BI__builtin_neon_vcls_v: mask = 0x7; break;
300 case ARM::BI__builtin_neon_vclsq_v: mask = 0x70000; break;
301 case ARM::BI__builtin_neon_vclz_v: mask = 0x707; break;
302 case ARM::BI__builtin_neon_vclzq_v: mask = 0x7070000; break;
303 case ARM::BI__builtin_neon_vcnt_v: mask = 0x121; break;
304 case ARM::BI__builtin_neon_vcntq_v: mask = 0x1210000; break;
305 case ARM::BI__builtin_neon_vcvt_f16_v: mask = 0x80; break;
306 case ARM::BI__builtin_neon_vcvt_f32_v: mask = 0x404; break;
307 case ARM::BI__builtin_neon_vcvtq_f32_v: mask = 0x4040000; break;
308 case ARM::BI__builtin_neon_vcvt_f32_f16: mask = 0x100000; break;
309 case ARM::BI__builtin_neon_vcvt_n_f32_v: mask = 0x404; break;
310 case ARM::BI__builtin_neon_vcvtq_n_f32_v: mask = 0x4040000; break;
311 case ARM::BI__builtin_neon_vcvt_n_s32_v: mask = 0x4; break;
312 case ARM::BI__builtin_neon_vcvtq_n_s32_v: mask = 0x40000; break;
313 case ARM::BI__builtin_neon_vcvt_n_u32_v: mask = 0x400; break;
314 case ARM::BI__builtin_neon_vcvtq_n_u32_v: mask = 0x4000000; break;
315 case ARM::BI__builtin_neon_vcvt_s32_v: mask = 0x4; break;
316 case ARM::BI__builtin_neon_vcvtq_s32_v: mask = 0x40000; break;
317 case ARM::BI__builtin_neon_vcvt_u32_v: mask = 0x400; break;
318 case ARM::BI__builtin_neon_vcvtq_u32_v: mask = 0x4000000; break;
319 case ARM::BI__builtin_neon_vext_v: mask = 0xF6F; break;
320 case ARM::BI__builtin_neon_vextq_v: mask = 0xF6F0000; break;
321 case ARM::BI__builtin_neon_vhadd_v: mask = 0x707; break;
322 case ARM::BI__builtin_neon_vhaddq_v: mask = 0x7070000; break;
323 case ARM::BI__builtin_neon_vhsub_v: mask = 0x707; break;
324 case ARM::BI__builtin_neon_vhsubq_v: mask = 0x7070000; break;
325 case ARM::BI__builtin_neon_vld1_v: mask = 0xFFF; break;
326 case ARM::BI__builtin_neon_vld1q_v: mask = 0xFFF0000; break;
327 case ARM::BI__builtin_neon_vld1_dup_v: mask = 0xFFF; break;
328 case ARM::BI__builtin_neon_vld1q_dup_v: mask = 0xFFF0000; break;
329 case ARM::BI__builtin_neon_vld1_lane_v: mask = 0xFFF; break;
330 case ARM::BI__builtin_neon_vld1q_lane_v: mask = 0xFFF0000; break;
331 case ARM::BI__builtin_neon_vld2_v: mask = 0xFFF; break;
332 case ARM::BI__builtin_neon_vld2q_v: mask = 0x7F70000; break;
333 case ARM::BI__builtin_neon_vld2_dup_v: mask = 0xFFF; break;
334 case ARM::BI__builtin_neon_vld2_lane_v: mask = 0x7F7; break;
335 case ARM::BI__builtin_neon_vld2q_lane_v: mask = 0x6D60000; break;
336 case ARM::BI__builtin_neon_vld3_v: mask = 0xFFF; break;
337 case ARM::BI__builtin_neon_vld3q_v: mask = 0x7F70000; break;
338 case ARM::BI__builtin_neon_vld3_dup_v: mask = 0xFFF; break;
339 case ARM::BI__builtin_neon_vld3_lane_v: mask = 0x7F7; break;
340 case ARM::BI__builtin_neon_vld3q_lane_v: mask = 0x6D60000; break;
341 case ARM::BI__builtin_neon_vld4_v: mask = 0xFFF; break;
342 case ARM::BI__builtin_neon_vld4q_v: mask = 0x7F70000; break;
343 case ARM::BI__builtin_neon_vld4_dup_v: mask = 0xFFF; break;
344 case ARM::BI__builtin_neon_vld4_lane_v: mask = 0x7F7; break;
345 case ARM::BI__builtin_neon_vld4q_lane_v: mask = 0x6D60000; break;
346 case ARM::BI__builtin_neon_vmax_v: mask = 0x717; break;
347 case ARM::BI__builtin_neon_vmaxq_v: mask = 0x7170000; break;
348 case ARM::BI__builtin_neon_vmin_v: mask = 0x717; break;
349 case ARM::BI__builtin_neon_vminq_v: mask = 0x7170000; break;
350 case ARM::BI__builtin_neon_vmlal_v: mask = 0xE0E0000; break;
351 case ARM::BI__builtin_neon_vmlal_lane_v: mask = 0xC0C0000; break;
352 case ARM::BI__builtin_neon_vmla_lane_v: mask = 0x616; break;
353 case ARM::BI__builtin_neon_vmlaq_lane_v: mask = 0x6160000; break;
354 case ARM::BI__builtin_neon_vmlsl_v: mask = 0xE0E0000; break;
355 case ARM::BI__builtin_neon_vmlsl_lane_v: mask = 0xC0C0000; break;
356 case ARM::BI__builtin_neon_vmls_lane_v: mask = 0x616; break;
357 case ARM::BI__builtin_neon_vmlsq_lane_v: mask = 0x6160000; break;
358 case ARM::BI__builtin_neon_vmovl_v: mask = 0xE0E0000; break;
359 case ARM::BI__builtin_neon_vmovn_v: mask = 0x707; break;
360 case ARM::BI__builtin_neon_vmull_v: mask = 0xE4E0000; break;
361 case ARM::BI__builtin_neon_vmull_lane_v: mask = 0xC0C0000; break;
362 case ARM::BI__builtin_neon_vpadal_v: mask = 0xE0E; break;
363 case ARM::BI__builtin_neon_vpadalq_v: mask = 0xE0E0000; break;
364 case ARM::BI__builtin_neon_vpadd_v: mask = 0x717; break;
365 case ARM::BI__builtin_neon_vpaddl_v: mask = 0xE0E; break;
366 case ARM::BI__builtin_neon_vpaddlq_v: mask = 0xE0E0000; break;
367 case ARM::BI__builtin_neon_vpmax_v: mask = 0x717; break;
368 case ARM::BI__builtin_neon_vpmin_v: mask = 0x717; break;
369 case ARM::BI__builtin_neon_vqabs_v: mask = 0x7; break;
370 case ARM::BI__builtin_neon_vqabsq_v: mask = 0x70000; break;
371 case ARM::BI__builtin_neon_vqadd_v: mask = 0xF0F; break;
372 case ARM::BI__builtin_neon_vqaddq_v: mask = 0xF0F0000; break;
373 case ARM::BI__builtin_neon_vqdmlal_v: mask = 0xC0000; break;
374 case ARM::BI__builtin_neon_vqdmlal_lane_v: mask = 0xC0000; break;
375 case ARM::BI__builtin_neon_vqdmlsl_v: mask = 0xC0000; break;
376 case ARM::BI__builtin_neon_vqdmlsl_lane_v: mask = 0xC0000; break;
377 case ARM::BI__builtin_neon_vqdmulh_v: mask = 0x6; break;
378 case ARM::BI__builtin_neon_vqdmulhq_v: mask = 0x60000; break;
379 case ARM::BI__builtin_neon_vqdmulh_lane_v: mask = 0x6; break;
380 case ARM::BI__builtin_neon_vqdmulhq_lane_v: mask = 0x60000; break;
381 case ARM::BI__builtin_neon_vqdmull_v: mask = 0xC0000; break;
382 case ARM::BI__builtin_neon_vqdmull_lane_v: mask = 0xC0000; break;
383 case ARM::BI__builtin_neon_vqmovn_v: mask = 0x707; break;
384 case ARM::BI__builtin_neon_vqmovun_v: mask = 0x700; break;
385 case ARM::BI__builtin_neon_vqneg_v: mask = 0x7; break;
386 case ARM::BI__builtin_neon_vqnegq_v: mask = 0x70000; break;
387 case ARM::BI__builtin_neon_vqrdmulh_v: mask = 0x6; break;
388 case ARM::BI__builtin_neon_vqrdmulhq_v: mask = 0x60000; break;
389 case ARM::BI__builtin_neon_vqrdmulh_lane_v: mask = 0x6; break;
390 case ARM::BI__builtin_neon_vqrdmulhq_lane_v: mask = 0x60000; break;
391 case ARM::BI__builtin_neon_vqrshl_v: mask = 0xF0F; break;
392 case ARM::BI__builtin_neon_vqrshlq_v: mask = 0xF0F0000; break;
393 case ARM::BI__builtin_neon_vqrshrn_n_v: mask = 0x707; break;
394 case ARM::BI__builtin_neon_vqrshrun_n_v: mask = 0x700; break;
395 case ARM::BI__builtin_neon_vqshl_v: mask = 0xF0F; break;
396 case ARM::BI__builtin_neon_vqshlq_v: mask = 0xF0F0000; break;
397 case ARM::BI__builtin_neon_vqshlu_n_v: mask = 0xF00; break;
398 case ARM::BI__builtin_neon_vqshluq_n_v: mask = 0xF000000; break;
399 case ARM::BI__builtin_neon_vqshl_n_v: mask = 0xF0F; break;
400 case ARM::BI__builtin_neon_vqshlq_n_v: mask = 0xF0F0000; break;
401 case ARM::BI__builtin_neon_vqshrn_n_v: mask = 0x707; break;
402 case ARM::BI__builtin_neon_vqshrun_n_v: mask = 0x700; break;
403 case ARM::BI__builtin_neon_vqsub_v: mask = 0xF0F; break;
404 case ARM::BI__builtin_neon_vqsubq_v: mask = 0xF0F0000; break;
405 case ARM::BI__builtin_neon_vraddhn_v: mask = 0x707; break;
406 case ARM::BI__builtin_neon_vrecpe_v: mask = 0x410; break;
407 case ARM::BI__builtin_neon_vrecpeq_v: mask = 0x4100000; break;
408 case ARM::BI__builtin_neon_vrecps_v: mask = 0x10; break;
409 case ARM::BI__builtin_neon_vrecpsq_v: mask = 0x100000; break;
410 case ARM::BI__builtin_neon_vrhadd_v: mask = 0x707; break;
411 case ARM::BI__builtin_neon_vrhaddq_v: mask = 0x7070000; break;
412 case ARM::BI__builtin_neon_vrshl_v: mask = 0xF0F; break;
413 case ARM::BI__builtin_neon_vrshlq_v: mask = 0xF0F0000; break;
414 case ARM::BI__builtin_neon_vrshrn_n_v: mask = 0x707; break;
415 case ARM::BI__builtin_neon_vrshr_n_v: mask = 0xF0F; break;
416 case ARM::BI__builtin_neon_vrshrq_n_v: mask = 0xF0F0000; break;
417 case ARM::BI__builtin_neon_vrsqrte_v: mask = 0x410; break;
418 case ARM::BI__builtin_neon_vrsqrteq_v: mask = 0x4100000; break;
419 case ARM::BI__builtin_neon_vrsqrts_v: mask = 0x10; break;
420 case ARM::BI__builtin_neon_vrsqrtsq_v: mask = 0x100000; break;
421 case ARM::BI__builtin_neon_vrsra_n_v: mask = 0xF0F; break;
422 case ARM::BI__builtin_neon_vrsraq_n_v: mask = 0xF0F0000; break;
423 case ARM::BI__builtin_neon_vrsubhn_v: mask = 0x707; break;
424 case ARM::BI__builtin_neon_vshl_v: mask = 0xF0F; break;
425 case ARM::BI__builtin_neon_vshlq_v: mask = 0xF0F0000; break;
426 case ARM::BI__builtin_neon_vshll_n_v: mask = 0xE0E0000; break;
427 case ARM::BI__builtin_neon_vshl_n_v: mask = 0xF0F; break;
428 case ARM::BI__builtin_neon_vshlq_n_v: mask = 0xF0F0000; break;
429 case ARM::BI__builtin_neon_vshrn_n_v: mask = 0x707; break;
430 case ARM::BI__builtin_neon_vshr_n_v: mask = 0xF0F; break;
431 case ARM::BI__builtin_neon_vshrq_n_v: mask = 0xF0F0000; break;
432 case ARM::BI__builtin_neon_vsli_n_v: mask = 0xF6F; break;
433 case ARM::BI__builtin_neon_vsliq_n_v: mask = 0xF6F0000; break;
434 case ARM::BI__builtin_neon_vsra_n_v: mask = 0xF0F; break;
435 case ARM::BI__builtin_neon_vsraq_n_v: mask = 0xF0F0000; break;
436 case ARM::BI__builtin_neon_vsri_n_v: mask = 0xF6F; break;
437 case ARM::BI__builtin_neon_vsriq_n_v: mask = 0xF6F0000; break;
438 case ARM::BI__builtin_neon_vst1_v: mask = 0x9F; break;
439 case ARM::BI__builtin_neon_vst1q_v: mask = 0x9F0000; break;
440 case ARM::BI__builtin_neon_vst1_lane_v: mask = 0x9F; break;
441 case ARM::BI__builtin_neon_vst1q_lane_v: mask = 0x9F0000; break;
442 case ARM::BI__builtin_neon_vst2_v: mask = 0x9F; break;
443 case ARM::BI__builtin_neon_vst2q_v: mask = 0x970000; break;
444 case ARM::BI__builtin_neon_vst2_lane_v: mask = 0x97; break;
445 case ARM::BI__builtin_neon_vst2q_lane_v: mask = 0x960000; break;
446 case ARM::BI__builtin_neon_vst3_v: mask = 0x9F; break;
447 case ARM::BI__builtin_neon_vst3q_v: mask = 0x970000; break;
448 case ARM::BI__builtin_neon_vst3_lane_v: mask = 0x97; break;
449 case ARM::BI__builtin_neon_vst3q_lane_v: mask = 0x960000; break;
450 case ARM::BI__builtin_neon_vst4_v: mask = 0x9F; break;
451 case ARM::BI__builtin_neon_vst4q_v: mask = 0x970000; break;
452 case ARM::BI__builtin_neon_vst4_lane_v: mask = 0x97; break;
453 case ARM::BI__builtin_neon_vst4q_lane_v: mask = 0x960000; break;
454 case ARM::BI__builtin_neon_vsubhn_v: mask = 0x707; break;
455 case ARM::BI__builtin_neon_vsubl_v: mask = 0xE0E0000; break;
456 case ARM::BI__builtin_neon_vsubw_v: mask = 0xE0E0000; break;
457 case ARM::BI__builtin_neon_vtbl1_v: mask = 0x121; break;
458 case ARM::BI__builtin_neon_vtbl2_v: mask = 0x121; break;
459 case ARM::BI__builtin_neon_vtbl3_v: mask = 0x121; break;
460 case ARM::BI__builtin_neon_vtbl4_v: mask = 0x121; break;
461 case ARM::BI__builtin_neon_vtbx1_v: mask = 0x121; break;
462 case ARM::BI__builtin_neon_vtbx2_v: mask = 0x121; break;
463 case ARM::BI__builtin_neon_vtbx3_v: mask = 0x121; break;
464 case ARM::BI__builtin_neon_vtbx4_v: mask = 0x121; break;
465 case ARM::BI__builtin_neon_vtrn_v: mask = 0x777; break;
466 case ARM::BI__builtin_neon_vtrnq_v: mask = 0x7770000; break;
467 case ARM::BI__builtin_neon_vtst_v: mask = 0x700; break;
468 case ARM::BI__builtin_neon_vtstq_v: mask = 0x7000000; break;
469 case ARM::BI__builtin_neon_vuzp_v: mask = 0x777; break;
470 case ARM::BI__builtin_neon_vuzpq_v: mask = 0x7770000; break;
471 case ARM::BI__builtin_neon_vzip_v: mask = 0x373; break;
472 case ARM::BI__builtin_neon_vzipq_v: mask = 0x7770000; break;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000473 }
474
Nate Begeman0d15c532010-06-13 04:47:52 +0000475 // For NEON intrinsics which are overloaded on vector element type, validate
476 // the immediate which specifies which variant to emit.
477 if (mask) {
478 unsigned ArgNo = TheCall->getNumArgs()-1;
479 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
480 return true;
481
Nate Begeman61eecf52010-06-14 05:21:25 +0000482 TV = Result.getLimitedValue(32);
483 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000484 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
485 << TheCall->getArg(ArgNo)->getSourceRange();
486 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000487
Nate Begeman0d15c532010-06-13 04:47:52 +0000488 // For NEON intrinsics which take an immediate value as part of the
489 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000490 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000491 switch (BuiltinID) {
492 default: return false;
Nate Begeman61eecf52010-06-14 05:21:25 +0000493 case ARM::BI__builtin_neon_vcvt_n_f32_v: i = 1; u = RFT(TV); break;
494 case ARM::BI__builtin_neon_vcvtq_n_f32_v: i = 1; u = RFT(TV); break;
495 case ARM::BI__builtin_neon_vcvt_n_s32_v: i = 1; u = RFT(TV); break;
496 case ARM::BI__builtin_neon_vcvtq_n_s32_v: i = 1; u = RFT(TV); break;
497 case ARM::BI__builtin_neon_vcvt_n_u32_v: i = 1; u = RFT(TV); break;
498 case ARM::BI__builtin_neon_vcvtq_n_u32_v: i = 1; u = RFT(TV); break;
499 case ARM::BI__builtin_neon_vext_v: i = 2; u = RFT(TV); break;
500 case ARM::BI__builtin_neon_vextq_v: i = 2; u = RFT(TV); break;
501 case ARM::BI__builtin_neon_vget_lane_i8: i = 1; u = 7; break;
502 case ARM::BI__builtin_neon_vget_lane_i16: i = 1; u = 3; break;
503 case ARM::BI__builtin_neon_vget_lane_i32: i = 1; u = 1; break;
504 case ARM::BI__builtin_neon_vget_lane_f32: i = 1; u = 1; break;
505 case ARM::BI__builtin_neon_vgetq_lane_i8: i = 1; u = 15; break;
506 case ARM::BI__builtin_neon_vgetq_lane_i16: i = 1; u = 7; break;
507 case ARM::BI__builtin_neon_vgetq_lane_i32: i = 1; u = 3; break;
508 case ARM::BI__builtin_neon_vgetq_lane_f32: i = 1; u = 3; break;
509 case ARM::BI__builtin_neon_vget_lane_i64: i = 1; u = 0; break;
510 case ARM::BI__builtin_neon_vgetq_lane_i64: i = 1; u = 1; break;
511 case ARM::BI__builtin_neon_vld1q_lane_v: i = 1; u = RFT(TV); break;
512 case ARM::BI__builtin_neon_vld1_lane_v: i = 1; u = RFT(TV); break;
513 case ARM::BI__builtin_neon_vld2q_lane_v: i = 1; u = RFT(TV); break;
514 case ARM::BI__builtin_neon_vld2_lane_v: i = 1; u = RFT(TV); break;
515 case ARM::BI__builtin_neon_vld3q_lane_v: i = 1; u = RFT(TV); break;
516 case ARM::BI__builtin_neon_vld3_lane_v: i = 1; u = RFT(TV); break;
517 case ARM::BI__builtin_neon_vld4q_lane_v: i = 1; u = RFT(TV); break;
518 case ARM::BI__builtin_neon_vld4_lane_v: i = 1; u = RFT(TV); break;
519 case ARM::BI__builtin_neon_vmlal_lane_v: i = 3; u = RFT(TV); break;
520 case ARM::BI__builtin_neon_vmla_lane_v: i = 3; u = RFT(TV); break;
521 case ARM::BI__builtin_neon_vmlaq_lane_v: i = 3; u = RFT(TV); break;
522 case ARM::BI__builtin_neon_vmlsl_lane_v: i = 3; u = RFT(TV); break;
523 case ARM::BI__builtin_neon_vmls_lane_v: i = 3; u = RFT(TV); break;
524 case ARM::BI__builtin_neon_vmlsq_lane_v: i = 3; u = RFT(TV); break;
525 case ARM::BI__builtin_neon_vmull_lane_v: i = 2; u = RFT(TV); break;
526 case ARM::BI__builtin_neon_vqdmlal_lane_v: i = 3; u = RFT(TV); break;
527 case ARM::BI__builtin_neon_vqdmlsl_lane_v: i = 3; u = RFT(TV); break;
528 case ARM::BI__builtin_neon_vqdmulh_lane_v: i = 2; u = RFT(TV); break;
529 case ARM::BI__builtin_neon_vqdmulhq_lane_v: i = 2; u = RFT(TV); break;
530 case ARM::BI__builtin_neon_vqdmull_lane_v: i = 2; u = RFT(TV); break;
531 case ARM::BI__builtin_neon_vqrdmulh_lane_v: i = 2; u = RFT(TV); break;
532 case ARM::BI__builtin_neon_vqrdmulhq_lane_v: i = 2; u = RFT(TV); break;
533 case ARM::BI__builtin_neon_vqrshrn_n_v: i = 1; l = 1; u = RFT(TV, true); break;
534 case ARM::BI__builtin_neon_vqrshrun_n_v: i = 1; l = 1; u = RFT(TV, true); break;
535 case ARM::BI__builtin_neon_vqshlu_n_v: i = 1; u = RFT(TV, true); break;
536 case ARM::BI__builtin_neon_vqshluq_n_v: i = 1; u = RFT(TV, true); break;
537 case ARM::BI__builtin_neon_vqshl_n_v: i = 1; u = RFT(TV, true); break;
538 case ARM::BI__builtin_neon_vqshlq_n_v: i = 1; u = RFT(TV, true); break;
539 case ARM::BI__builtin_neon_vqshrn_n_v: i = 1; l = 1; u = RFT(TV, true); break;
540 case ARM::BI__builtin_neon_vqshrun_n_v: i = 1; l = 1; u = RFT(TV, true); break;
541 case ARM::BI__builtin_neon_vrshrn_n_v: i = 1; l = 1; u = RFT(TV, true); break;
542 case ARM::BI__builtin_neon_vrshr_n_v: i = 1; l = 1; u = RFT(TV, true); break;
543 case ARM::BI__builtin_neon_vrshrq_n_v: i = 1; l = 1; u = RFT(TV, true); break;
544 case ARM::BI__builtin_neon_vrsra_n_v: i = 2; l = 1; u = RFT(TV, true); break;
545 case ARM::BI__builtin_neon_vrsraq_n_v: i = 2; l = 1; u = RFT(TV, true); break;
546 case ARM::BI__builtin_neon_vset_lane_i8: i = 2; u = 7; break;
547 case ARM::BI__builtin_neon_vset_lane_i16: i = 2; u = 3; break;
548 case ARM::BI__builtin_neon_vset_lane_i32: i = 2; u = 1; break;
549 case ARM::BI__builtin_neon_vset_lane_f32: i = 2; u = 1; break;
550 case ARM::BI__builtin_neon_vsetq_lane_i8: i = 2; u = 15; break;
551 case ARM::BI__builtin_neon_vsetq_lane_i16: i = 2; u = 7; break;
552 case ARM::BI__builtin_neon_vsetq_lane_i32: i = 2; u = 3; break;
553 case ARM::BI__builtin_neon_vsetq_lane_f32: i = 2; u = 3; break;
554 case ARM::BI__builtin_neon_vset_lane_i64: i = 2; u = 0; break;
555 case ARM::BI__builtin_neon_vsetq_lane_i64: i = 2; u = 1; break;
556 case ARM::BI__builtin_neon_vshll_n_v: i = 1; u = RFT(TV, true); break;
557 case ARM::BI__builtin_neon_vshl_n_v: i = 1; u = RFT(TV, true); break;
558 case ARM::BI__builtin_neon_vshlq_n_v: i = 1; u = RFT(TV, true); break;
559 case ARM::BI__builtin_neon_vshrn_n_v: i = 1; l = 1; u = RFT(TV, true); break;
560 case ARM::BI__builtin_neon_vshr_n_v: i = 1; l = 1; u = RFT(TV, true); break;
561 case ARM::BI__builtin_neon_vshrq_n_v: i = 1; l = 1; u = RFT(TV, true); break;
562 case ARM::BI__builtin_neon_vsli_n_v: i = 2; u = RFT(TV, true); break;
563 case ARM::BI__builtin_neon_vsliq_n_v: i = 2; u = RFT(TV, true); break;
564 case ARM::BI__builtin_neon_vsra_n_v: i = 2; l = 1; u = RFT(TV, true); break;
565 case ARM::BI__builtin_neon_vsraq_n_v: i = 2; l = 1; u = RFT(TV, true); break;
566 case ARM::BI__builtin_neon_vsri_n_v: i = 2; l = 1; u = RFT(TV, true); break;
567 case ARM::BI__builtin_neon_vsriq_n_v: i = 2; l = 1; u = RFT(TV, true); break;
568 case ARM::BI__builtin_neon_vst1q_lane_v: i = 2; u = RFT(TV); break;
569 case ARM::BI__builtin_neon_vst1_lane_v: i = 2; u = RFT(TV); break;
570 case ARM::BI__builtin_neon_vst2q_lane_v: i = 2; u = RFT(TV); break;
571 case ARM::BI__builtin_neon_vst2_lane_v: i = 2; u = RFT(TV); break;
572 case ARM::BI__builtin_neon_vst3q_lane_v: i = 2; u = RFT(TV); break;
573 case ARM::BI__builtin_neon_vst3_lane_v: i = 2; u = RFT(TV); break;
574 case ARM::BI__builtin_neon_vst4q_lane_v: i = 2; u = RFT(TV); break;
575 case ARM::BI__builtin_neon_vst4_lane_v: i = 2; u = RFT(TV); break;
Nate Begeman0d15c532010-06-13 04:47:52 +0000576 };
577
Nate Begeman61eecf52010-06-14 05:21:25 +0000578 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000579 if (SemaBuiltinConstantArg(TheCall, i, Result))
580 return true;
581
Nate Begeman61eecf52010-06-14 05:21:25 +0000582 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000583 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000584 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000585 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Nate Begeman61eecf52010-06-14 05:21:25 +0000586 << llvm::utostr(l) << llvm::utostr(u+l)
587 << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000588
Nate Begeman26a31422010-06-08 02:47:44 +0000589 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000590}
Daniel Dunbarde454282008-10-02 18:44:07 +0000591
Anders Carlssond406bf02009-08-16 01:56:34 +0000592/// CheckFunctionCall - Check a direct function call for various correctness
593/// and safety properties not strictly enforced by the C type system.
594bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
595 // Get the IdentifierInfo* for the called function.
596 IdentifierInfo *FnInfo = FDecl->getIdentifier();
597
598 // None of the checks below are needed for functions that don't have
599 // simple names (e.g., C++ conversion functions).
600 if (!FnInfo)
601 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Daniel Dunbarde454282008-10-02 18:44:07 +0000603 // FIXME: This mechanism should be abstracted to be less fragile and
604 // more efficient. For example, just map function ids to custom
605 // handlers.
606
Chris Lattner59907c42007-08-10 20:18:51 +0000607 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000608 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000609 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000610 bool HasVAListArg = Format->getFirstArg() == 0;
Douglas Gregor3c385e52009-02-14 18:57:46 +0000611 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000612 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000613 }
Chris Lattner59907c42007-08-10 20:18:51 +0000614 }
Mike Stump1eb44332009-09-09 15:08:12 +0000615
616 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000617 NonNull = NonNull->getNext<NonNullAttr>())
618 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000619
Anders Carlssond406bf02009-08-16 01:56:34 +0000620 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000621}
622
Anders Carlssond406bf02009-08-16 01:56:34 +0000623bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000624 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000625 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000626 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000627 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000629 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
630 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000631 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000633 QualType Ty = V->getType();
634 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000635 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Anders Carlssond406bf02009-08-16 01:56:34 +0000637 if (!CheckablePrintfAttr(Format, TheCall))
638 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Anders Carlssond406bf02009-08-16 01:56:34 +0000640 bool HasVAListArg = Format->getFirstArg() == 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000641 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
642 HasVAListArg ? 0 : Format->getFirstArg() - 1);
643
644 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000645}
646
Chris Lattner5caa3702009-05-08 06:58:22 +0000647/// SemaBuiltinAtomicOverloaded - We have a call to a function like
648/// __sync_fetch_and_add, which is an overloaded function based on the pointer
649/// type of its first argument. The main ActOnCallExpr routines have already
650/// promoted the types of arguments because all of these calls are prototyped as
651/// void(...).
652///
653/// This function goes through and does final semantic checking for these
654/// builtins,
655bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
656 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
657 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
658
659 // Ensure that we have at least one argument to do type inference from.
660 if (TheCall->getNumArgs() < 1)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000661 return Diag(TheCall->getLocEnd(),
662 diag::err_typecheck_call_too_few_args_at_least)
663 << 0 << 1 << TheCall->getNumArgs()
664 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Chris Lattner5caa3702009-05-08 06:58:22 +0000666 // Inspect the first argument of the atomic builtin. This should always be
667 // a pointer type, whose element is an integral scalar or pointer type.
668 // Because it is a pointer type, we don't have to worry about any implicit
669 // casts here.
670 Expr *FirstArg = TheCall->getArg(0);
671 if (!FirstArg->getType()->isPointerType())
672 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
673 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Ted Kremenek6217b802009-07-29 21:53:49 +0000675 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000676 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000677 !ValType->isBlockPointerType())
678 return Diag(DRE->getLocStart(),
679 diag::err_atomic_builtin_must_be_pointer_intptr)
680 << FirstArg->getType() << FirstArg->getSourceRange();
681
682 // We need to figure out which concrete builtin this maps onto. For example,
683 // __sync_fetch_and_add with a 2 byte object turns into
684 // __sync_fetch_and_add_2.
685#define BUILTIN_ROW(x) \
686 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
687 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Chris Lattner5caa3702009-05-08 06:58:22 +0000689 static const unsigned BuiltinIndices[][5] = {
690 BUILTIN_ROW(__sync_fetch_and_add),
691 BUILTIN_ROW(__sync_fetch_and_sub),
692 BUILTIN_ROW(__sync_fetch_and_or),
693 BUILTIN_ROW(__sync_fetch_and_and),
694 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Chris Lattner5caa3702009-05-08 06:58:22 +0000696 BUILTIN_ROW(__sync_add_and_fetch),
697 BUILTIN_ROW(__sync_sub_and_fetch),
698 BUILTIN_ROW(__sync_and_and_fetch),
699 BUILTIN_ROW(__sync_or_and_fetch),
700 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Chris Lattner5caa3702009-05-08 06:58:22 +0000702 BUILTIN_ROW(__sync_val_compare_and_swap),
703 BUILTIN_ROW(__sync_bool_compare_and_swap),
704 BUILTIN_ROW(__sync_lock_test_and_set),
705 BUILTIN_ROW(__sync_lock_release)
706 };
Mike Stump1eb44332009-09-09 15:08:12 +0000707#undef BUILTIN_ROW
708
Chris Lattner5caa3702009-05-08 06:58:22 +0000709 // Determine the index of the size.
710 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000711 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000712 case 1: SizeIndex = 0; break;
713 case 2: SizeIndex = 1; break;
714 case 4: SizeIndex = 2; break;
715 case 8: SizeIndex = 3; break;
716 case 16: SizeIndex = 4; break;
717 default:
718 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
719 << FirstArg->getType() << FirstArg->getSourceRange();
720 }
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Chris Lattner5caa3702009-05-08 06:58:22 +0000722 // Each of these builtins has one pointer argument, followed by some number of
723 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
724 // that we ignore. Find out which row of BuiltinIndices to read from as well
725 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000726 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000727 unsigned BuiltinIndex, NumFixed = 1;
728 switch (BuiltinID) {
729 default: assert(0 && "Unknown overloaded atomic builtin!");
730 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
731 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
732 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
733 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
734 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000736 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
737 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
738 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
739 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
740 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Chris Lattner5caa3702009-05-08 06:58:22 +0000742 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000743 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000744 NumFixed = 2;
745 break;
746 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000747 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000748 NumFixed = 2;
749 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000750 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000751 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000752 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000753 NumFixed = 0;
754 break;
755 }
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Chris Lattner5caa3702009-05-08 06:58:22 +0000757 // Now that we know how many fixed arguments we expect, first check that we
758 // have at least that many.
759 if (TheCall->getNumArgs() < 1+NumFixed)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000760 return Diag(TheCall->getLocEnd(),
761 diag::err_typecheck_call_too_few_args_at_least)
762 << 0 << 1+NumFixed << TheCall->getNumArgs()
763 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000764
765
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000766 // Get the decl for the concrete builtin from this, we can tell what the
767 // concrete integer type we should convert to is.
768 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
769 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
770 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000771 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000772 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
773 TUScope, false, DRE->getLocStart()));
774 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000775 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000776 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000778 // If the first type needs to be converted (e.g. void** -> int*), do it now.
779 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000780 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000781 TheCall->setArg(0, FirstArg);
782 }
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Chris Lattner5caa3702009-05-08 06:58:22 +0000784 // Next, walk the valid ones promoting to the right type.
785 for (unsigned i = 0; i != NumFixed; ++i) {
786 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Chris Lattner5caa3702009-05-08 06:58:22 +0000788 // If the argument is an implicit cast, then there was a promotion due to
789 // "...", just remove it now.
790 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
791 Arg = ICE->getSubExpr();
792 ICE->setSubExpr(0);
793 ICE->Destroy(Context);
794 TheCall->setArg(i+1, Arg);
795 }
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Chris Lattner5caa3702009-05-08 06:58:22 +0000797 // GCC does an implicit conversion to the pointer or integer ValType. This
798 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000799 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000800 CXXBaseSpecifierArray BasePath;
801 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, BasePath))
Chris Lattner5caa3702009-05-08 06:58:22 +0000802 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Chris Lattner5caa3702009-05-08 06:58:22 +0000804 // Okay, we have something that *can* be converted to the right type. Check
805 // to see if there is a potentially weird extension going on here. This can
806 // happen when you do an atomic operation on something like an char* and
807 // pass in 42. The 42 gets converted to char. This is even more strange
808 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000809 // FIXME: Do this check.
Anders Carlsson80971bd2010-04-24 16:36:20 +0000810 ImpCastExprToType(Arg, ValType, Kind);
Chris Lattner5caa3702009-05-08 06:58:22 +0000811 TheCall->setArg(i+1, Arg);
812 }
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattner5caa3702009-05-08 06:58:22 +0000814 // Switch the DeclRefExpr to refer to the new decl.
815 DRE->setDecl(NewBuiltinDecl);
816 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Chris Lattner5caa3702009-05-08 06:58:22 +0000818 // Set the callee in the CallExpr.
819 // FIXME: This leaks the original parens and implicit casts.
820 Expr *PromotedCall = DRE;
821 UsualUnaryConversions(PromotedCall);
822 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Chris Lattner5caa3702009-05-08 06:58:22 +0000824
825 // Change the result type of the call to match the result type of the decl.
826 TheCall->setType(NewBuiltinDecl->getResultType());
827 return false;
828}
829
830
Chris Lattner69039812009-02-18 06:01:06 +0000831/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000832/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000833/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000834/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000835/// belong to the input codeset UTF-8"
836/// Note: It might also make sense to do the UTF-16 conversion here (would
837/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000838bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000839 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000840 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
841
842 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000843 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
844 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000845 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000846 }
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Daniel Dunbarf015b032009-09-22 10:03:52 +0000848 const char *Data = Literal->getStrData();
849 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Daniel Dunbarf015b032009-09-22 10:03:52 +0000851 for (unsigned i = 0; i < Length; ++i) {
852 if (!Data[i]) {
853 Diag(getLocationOfStringLiteralByte(Literal, i),
854 diag::warn_cfstring_literal_contains_nul_character)
855 << Arg->getSourceRange();
856 break;
857 }
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000860 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000861}
862
Chris Lattnerc27c6652007-12-20 00:05:45 +0000863/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
864/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000865bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
866 Expr *Fn = TheCall->getCallee();
867 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000868 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000869 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000870 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
871 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000872 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000873 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000874 return true;
875 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000876
877 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000878 return Diag(TheCall->getLocEnd(),
879 diag::err_typecheck_call_too_few_args_at_least)
880 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000881 }
882
Chris Lattnerc27c6652007-12-20 00:05:45 +0000883 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000884 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000885 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000886 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000887 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000888 else if (FunctionDecl *FD = getCurFunctionDecl())
889 isVariadic = FD->isVariadic();
890 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000891 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Chris Lattnerc27c6652007-12-20 00:05:45 +0000893 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000894 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
895 return true;
896 }
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Chris Lattner30ce3442007-12-19 23:59:04 +0000898 // Verify that the second argument to the builtin is the last argument of the
899 // current function or method.
900 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000901 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Anders Carlsson88cf2262008-02-11 04:20:54 +0000903 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
904 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000905 // FIXME: This isn't correct for methods (results in bogus warning).
906 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000907 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000908 if (CurBlock)
909 LastArg = *(CurBlock->TheDecl->param_end()-1);
910 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000911 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000912 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000913 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000914 SecondArgIsLastNamedArgument = PV == LastArg;
915 }
916 }
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Chris Lattner30ce3442007-12-19 23:59:04 +0000918 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000919 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000920 diag::warn_second_parameter_of_va_start_not_last_named_argument);
921 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000922}
Chris Lattner30ce3442007-12-19 23:59:04 +0000923
Chris Lattner1b9a0792007-12-20 00:26:33 +0000924/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
925/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000926bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
927 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000928 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000929 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000930 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000931 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000932 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000933 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000934 << SourceRange(TheCall->getArg(2)->getLocStart(),
935 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Chris Lattner925e60d2007-12-28 05:29:59 +0000937 Expr *OrigArg0 = TheCall->getArg(0);
938 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000939
Chris Lattner1b9a0792007-12-20 00:26:33 +0000940 // Do standard promotions between the two arguments, returning their common
941 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000942 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000943
944 // Make sure any conversions are pushed back into the call; this is
945 // type safe since unordered compare builtins are declared as "_Bool
946 // foo(...)".
947 TheCall->setArg(0, OrigArg0);
948 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Douglas Gregorcde01732009-05-19 22:10:17 +0000950 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
951 return false;
952
Chris Lattner1b9a0792007-12-20 00:26:33 +0000953 // If the common type isn't a real floating type, then the arguments were
954 // invalid for this operation.
955 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000956 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000957 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000958 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000959 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattner1b9a0792007-12-20 00:26:33 +0000961 return false;
962}
963
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000964/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
965/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000966/// to check everything. We expect the last argument to be a floating point
967/// value.
968bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
969 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000970 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000971 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000972 if (TheCall->getNumArgs() > NumArgs)
973 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000974 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000975 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000976 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000977 (*(TheCall->arg_end()-1))->getLocEnd());
978
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000979 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Eli Friedman9ac6f622009-08-31 20:06:00 +0000981 if (OrigArg->isTypeDependent())
982 return false;
983
Chris Lattner81368fb2010-05-06 05:50:07 +0000984 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000985 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000986 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000987 diag::err_typecheck_call_invalid_unary_fp)
988 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Chris Lattner81368fb2010-05-06 05:50:07 +0000990 // If this is an implicit conversion from float -> double, remove it.
991 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
992 Expr *CastArg = Cast->getSubExpr();
993 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
994 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
995 "promotion from float to double is the only expected cast here");
996 Cast->setSubExpr(0);
997 Cast->Destroy(Context);
998 TheCall->setArg(NumArgs-1, CastArg);
999 OrigArg = CastArg;
1000 }
1001 }
1002
Eli Friedman9ac6f622009-08-31 20:06:00 +00001003 return false;
1004}
1005
Eli Friedmand38617c2008-05-14 19:38:39 +00001006/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1007// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001008Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001009 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001010 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001011 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001012 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001013 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001014
Nate Begeman37b6a572010-06-08 00:16:34 +00001015 // Determine which of the following types of shufflevector we're checking:
1016 // 1) unary, vector mask: (lhs, mask)
1017 // 2) binary, vector mask: (lhs, rhs, mask)
1018 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1019 QualType resType = TheCall->getArg(0)->getType();
1020 unsigned numElements = 0;
1021
Douglas Gregorcde01732009-05-19 22:10:17 +00001022 if (!TheCall->getArg(0)->isTypeDependent() &&
1023 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001024 QualType LHSType = TheCall->getArg(0)->getType();
1025 QualType RHSType = TheCall->getArg(1)->getType();
1026
1027 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001028 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001029 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001030 TheCall->getArg(1)->getLocEnd());
1031 return ExprError();
1032 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001033
1034 numElements = LHSType->getAs<VectorType>()->getNumElements();
1035 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Nate Begeman37b6a572010-06-08 00:16:34 +00001037 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1038 // with mask. If so, verify that RHS is an integer vector type with the
1039 // same number of elts as lhs.
1040 if (TheCall->getNumArgs() == 2) {
1041 if (!RHSType->isIntegerType() ||
1042 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1043 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1044 << SourceRange(TheCall->getArg(1)->getLocStart(),
1045 TheCall->getArg(1)->getLocEnd());
1046 numResElements = numElements;
1047 }
1048 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001049 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001050 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001051 TheCall->getArg(1)->getLocEnd());
1052 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001053 } else if (numElements != numResElements) {
1054 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1055 resType = Context.getVectorType(eltType, numResElements, false, false);
Douglas Gregorcde01732009-05-19 22:10:17 +00001056 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001057 }
1058
1059 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001060 if (TheCall->getArg(i)->isTypeDependent() ||
1061 TheCall->getArg(i)->isValueDependent())
1062 continue;
1063
Nate Begeman37b6a572010-06-08 00:16:34 +00001064 llvm::APSInt Result(32);
1065 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1066 return ExprError(Diag(TheCall->getLocStart(),
1067 diag::err_shufflevector_nonconstant_argument)
1068 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001069
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001070 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001071 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001072 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001073 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001074 }
1075
1076 llvm::SmallVector<Expr*, 32> exprs;
1077
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001078 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001079 exprs.push_back(TheCall->getArg(i));
1080 TheCall->setArg(i, 0);
1081 }
1082
Nate Begemana88dc302009-08-12 02:10:25 +00001083 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001084 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001085 TheCall->getCallee()->getLocStart(),
1086 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001087}
Chris Lattner30ce3442007-12-19 23:59:04 +00001088
Daniel Dunbar4493f792008-07-21 22:59:13 +00001089/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1090// This is declared to take (const void*, ...) and can take two
1091// optional constant int args.
1092bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001093 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001094
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001095 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001096 return Diag(TheCall->getLocEnd(),
1097 diag::err_typecheck_call_too_many_args_at_most)
1098 << 0 /*function call*/ << 3 << NumArgs
1099 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001100
1101 // Argument 0 is checked for us and the remaining arguments must be
1102 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001103 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001104 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001105
Eli Friedman9aef7262009-12-04 00:30:06 +00001106 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001107 if (SemaBuiltinConstantArg(TheCall, i, Result))
1108 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Daniel Dunbar4493f792008-07-21 22:59:13 +00001110 // FIXME: gcc issues a warning and rewrites these to 0. These
1111 // seems especially odd for the third argument since the default
1112 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001113 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001114 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001115 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001116 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001117 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001118 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001119 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001120 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001121 }
1122 }
1123
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001124 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001125}
1126
Eric Christopher691ebc32010-04-17 02:26:23 +00001127/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1128/// TheCall is a constant expression.
1129bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1130 llvm::APSInt &Result) {
1131 Expr *Arg = TheCall->getArg(ArgNum);
1132 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1133 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1134
1135 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1136
1137 if (!Arg->isIntegerConstantExpr(Result, Context))
1138 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001139 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001140
Chris Lattner21fb98e2009-09-23 06:06:36 +00001141 return false;
1142}
1143
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001144/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1145/// int type). This simply type checks that type is one of the defined
1146/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +00001147// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001148bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001149 llvm::APSInt Result;
1150
1151 // Check constant-ness first.
1152 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1153 return true;
1154
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001155 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001156 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001157 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1158 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001159 }
1160
1161 return false;
1162}
1163
Eli Friedman586d6a82009-05-03 06:04:26 +00001164/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001165/// This checks that val is a constant 1.
1166bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1167 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001168 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001169
Eric Christopher691ebc32010-04-17 02:26:23 +00001170 // TODO: This is less than ideal. Overload this to take a value.
1171 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1172 return true;
1173
1174 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001175 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1176 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1177
1178 return false;
1179}
1180
Ted Kremenekd30ef872009-01-12 23:09:09 +00001181// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +00001182bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1183 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +00001184 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001185 if (E->isTypeDependent() || E->isValueDependent())
1186 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001187
1188 switch (E->getStmtClass()) {
1189 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +00001190 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +00001191 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +00001192 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +00001193 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +00001194 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001195 }
1196
1197 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +00001198 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001199 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +00001200 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001201 }
1202
1203 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +00001204 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001205 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +00001206 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001207 }
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Ted Kremenek082d9362009-03-20 21:35:28 +00001209 case Stmt::DeclRefExprClass: {
1210 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Ted Kremenek082d9362009-03-20 21:35:28 +00001212 // As an exception, do not flag errors for variables binding to
1213 // const string literals.
1214 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1215 bool isConstant = false;
1216 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001217
Ted Kremenek082d9362009-03-20 21:35:28 +00001218 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1219 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001220 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001221 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001222 PT->getPointeeType().isConstant(Context);
1223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Ted Kremenek082d9362009-03-20 21:35:28 +00001225 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001226 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001227 return SemaCheckStringLiteral(Init, TheCall,
1228 HasVAListArg, format_idx, firstDataArg);
1229 }
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Anders Carlssond966a552009-06-28 19:55:58 +00001231 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1232 // special check to see if the format string is a function parameter
1233 // of the function calling the printf function. If the function
1234 // has an attribute indicating it is a printf-like function, then we
1235 // should suppress warnings concerning non-literals being used in a call
1236 // to a vprintf function. For example:
1237 //
1238 // void
1239 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1240 // va_list ap;
1241 // va_start(ap, fmt);
1242 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1243 // ...
1244 //
1245 //
1246 // FIXME: We don't have full attribute support yet, so just check to see
1247 // if the argument is a DeclRefExpr that references a parameter. We'll
1248 // add proper support for checking the attribute later.
1249 if (HasVAListArg)
1250 if (isa<ParmVarDecl>(VD))
1251 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001252 }
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Ted Kremenek082d9362009-03-20 21:35:28 +00001254 return false;
1255 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001256
Anders Carlsson8f031b32009-06-27 04:05:33 +00001257 case Stmt::CallExprClass: {
1258 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001259 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001260 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1261 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1262 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001263 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001264 unsigned ArgIndex = FA->getFormatIdx();
1265 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
1267 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +00001268 format_idx, firstDataArg);
1269 }
1270 }
1271 }
1272 }
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Anders Carlsson8f031b32009-06-27 04:05:33 +00001274 return false;
1275 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001276 case Stmt::ObjCStringLiteralClass:
1277 case Stmt::StringLiteralClass: {
1278 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Ted Kremenek082d9362009-03-20 21:35:28 +00001280 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001281 StrE = ObjCFExpr->getString();
1282 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001283 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Ted Kremenekd30ef872009-01-12 23:09:09 +00001285 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +00001286 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +00001287 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001288 return true;
1289 }
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Ted Kremenekd30ef872009-01-12 23:09:09 +00001291 return false;
1292 }
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Ted Kremenek082d9362009-03-20 21:35:28 +00001294 default:
1295 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001296 }
1297}
1298
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001299void
Mike Stump1eb44332009-09-09 15:08:12 +00001300Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1301 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001302 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
1303 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +00001304 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001305 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001306 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +00001307 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1308 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001309 }
1310}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001311
Chris Lattner59907c42007-08-10 20:18:51 +00001312/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +00001313/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +00001314///
1315/// HasVAListArg - A predicate indicating whether the printf-like
1316/// function is passed an explicit va_arg argument (e.g., vprintf)
1317///
1318/// format_idx - The index into Args for the format string.
1319///
1320/// Improper format strings to functions in the printf family can be
1321/// the source of bizarre bugs and very serious security holes. A
1322/// good source of information is available in the following paper
1323/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +00001324///
1325/// FormatGuard: Automatic Protection From printf Format String
1326/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +00001327///
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001328/// TODO:
Ted Kremenek71895b92007-08-14 17:39:48 +00001329/// Functionality implemented:
1330///
1331/// We can statically check the following properties for string
1332/// literal format strings for non v.*printf functions (where the
1333/// arguments are passed directly):
1334//
1335/// (1) Are the number of format conversions equal to the number of
1336/// data arguments?
1337///
1338/// (2) Does each format conversion correctly match the type of the
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001339/// corresponding data argument?
Ted Kremenek71895b92007-08-14 17:39:48 +00001340///
1341/// Moreover, for all printf functions we can:
1342///
1343/// (3) Check for a missing format string (when not caught by type checking).
1344///
1345/// (4) Check for no-operation flags; e.g. using "#" with format
1346/// conversion 'c' (TODO)
1347///
1348/// (5) Check the use of '%n', a major source of security holes.
1349///
1350/// (6) Check for malformed format conversions that don't specify anything.
1351///
1352/// (7) Check for empty format strings. e.g: printf("");
1353///
1354/// (8) Check that the format string is a wide literal.
1355///
1356/// All of these checks can be done by parsing the format string.
1357///
Chris Lattner59907c42007-08-10 20:18:51 +00001358void
Mike Stump1eb44332009-09-09 15:08:12 +00001359Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +00001360 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +00001361 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001362
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001363 // The way the format attribute works in GCC, the implicit this argument
1364 // of member functions is counted. However, it doesn't appear in our own
1365 // lists, so decrement format_idx in that case.
1366 if (isa<CXXMemberCallExpr>(TheCall)) {
1367 // Catch a format attribute mistakenly referring to the object argument.
1368 if (format_idx == 0)
1369 return;
1370 --format_idx;
1371 if(firstDataArg != 0)
1372 --firstDataArg;
1373 }
1374
Mike Stump1eb44332009-09-09 15:08:12 +00001375 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001376 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001377 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1378 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001379 return;
1380 }
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Ted Kremenek082d9362009-03-20 21:35:28 +00001382 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Chris Lattner59907c42007-08-10 20:18:51 +00001384 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001385 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001386 // Dynamically generated format strings are difficult to
1387 // automatically vet at compile time. Requiring that format strings
1388 // are string literals: (1) permits the checking of format strings by
1389 // the compiler and thereby (2) can practically remove the source of
1390 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001391
Mike Stump1eb44332009-09-09 15:08:12 +00001392 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001393 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001394 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001395 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001396 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1397 firstDataArg))
1398 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001399
Chris Lattner655f1412009-04-29 04:59:47 +00001400 // If there are no arguments specified, warn with -Wformat-security, otherwise
1401 // warn only with -Wformat-nonliteral.
1402 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001403 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001404 diag::warn_printf_nonliteral_noargs)
1405 << OrigFormatExpr->getSourceRange();
1406 else
Mike Stump1eb44332009-09-09 15:08:12 +00001407 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001408 diag::warn_printf_nonliteral)
1409 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001410}
Ted Kremenek71895b92007-08-14 17:39:48 +00001411
Ted Kremeneke0e53132010-01-28 23:39:18 +00001412namespace {
Ted Kremenek74d56a12010-02-04 20:46:58 +00001413class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001414 Sema &S;
1415 const StringLiteral *FExpr;
1416 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001417 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001418 const unsigned NumDataArgs;
1419 const bool IsObjCLiteral;
1420 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001421 const bool HasVAListArg;
1422 const CallExpr *TheCall;
1423 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001424 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001425 bool usesPositionalArgs;
1426 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001427public:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001428 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001429 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001430 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001431 const char *beg, bool hasVAListArg,
1432 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001433 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001434 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001435 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001436 IsObjCLiteral(isObjCLiteral), Beg(beg),
1437 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001438 TheCall(theCall), FormatIdx(formatIdx),
1439 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001440 CoveredArgs.resize(numDataArgs);
1441 CoveredArgs.reset();
1442 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001443
Ted Kremenek07d161f2010-01-29 01:50:07 +00001444 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001445
Ted Kremenek808015a2010-01-29 03:16:21 +00001446 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1447 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001448
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001449 bool
Ted Kremenek74d56a12010-02-04 20:46:58 +00001450 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1451 const char *startSpecifier,
1452 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001453
Ted Kremenekefaff192010-02-27 01:41:03 +00001454 virtual void HandleInvalidPosition(const char *startSpecifier,
1455 unsigned specifierLen,
1456 analyze_printf::PositionContext p);
1457
1458 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1459
Ted Kremeneke0e53132010-01-28 23:39:18 +00001460 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001461
Ted Kremeneke0e53132010-01-28 23:39:18 +00001462 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1463 const char *startSpecifier,
1464 unsigned specifierLen);
1465private:
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001466 SourceRange getFormatStringRange();
1467 SourceRange getFormatSpecifierRange(const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001468 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001469 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001470
Ted Kremenekefaff192010-02-27 01:41:03 +00001471 bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k,
1472 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001473 void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1474 llvm::StringRef flag, llvm::StringRef cspec,
1475 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001476
Ted Kremenek0d277352010-01-29 01:06:55 +00001477 const Expr *getDataArg(unsigned i) const;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001478};
1479}
1480
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001481SourceRange CheckPrintfHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001482 return OrigFormatExpr->getSourceRange();
1483}
1484
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001485SourceRange CheckPrintfHandler::
1486getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1487 return SourceRange(getLocationOfByte(startSpecifier),
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001488 getLocationOfByte(startSpecifier+specifierLen-1));
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001489}
1490
Ted Kremeneke0e53132010-01-28 23:39:18 +00001491SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001492 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001493}
1494
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001495void CheckPrintfHandler::
Ted Kremenek808015a2010-01-29 03:16:21 +00001496HandleIncompleteFormatSpecifier(const char *startSpecifier,
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001497 unsigned specifierLen) {
Ted Kremenek808015a2010-01-29 03:16:21 +00001498 SourceLocation Loc = getLocationOfByte(startSpecifier);
1499 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001500 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001501}
1502
Ted Kremenekefaff192010-02-27 01:41:03 +00001503void
1504CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1505 analyze_printf::PositionContext p) {
1506 SourceLocation Loc = getLocationOfByte(startPos);
1507 S.Diag(Loc, diag::warn_printf_invalid_positional_specifier)
1508 << (unsigned) p << getFormatSpecifierRange(startPos, posLen);
1509}
1510
1511void CheckPrintfHandler::HandleZeroPosition(const char *startPos,
1512 unsigned posLen) {
1513 SourceLocation Loc = getLocationOfByte(startPos);
1514 S.Diag(Loc, diag::warn_printf_zero_positional_specifier)
1515 << getFormatSpecifierRange(startPos, posLen);
1516}
1517
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001518bool CheckPrintfHandler::
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001519HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1520 const char *startSpecifier,
1521 unsigned specifierLen) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001522
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001523 unsigned argIndex = FS.getArgIndex();
1524 bool keepGoing = true;
1525 if (argIndex < NumDataArgs) {
1526 // Consider the argument coverered, even though the specifier doesn't
1527 // make sense.
1528 CoveredArgs.set(argIndex);
1529 }
1530 else {
1531 // If argIndex exceeds the number of data arguments we
1532 // don't issue a warning because that is just a cascade of warnings (and
1533 // they may have intended '%%' anyway). We don't want to continue processing
1534 // the format string after this point, however, as we will like just get
1535 // gibberish when trying to match arguments.
1536 keepGoing = false;
1537 }
1538
Ted Kremenek808015a2010-01-29 03:16:21 +00001539 const analyze_printf::ConversionSpecifier &CS =
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001540 FS.getConversionSpecifier();
Ted Kremenek808015a2010-01-29 03:16:21 +00001541 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001542 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenek808015a2010-01-29 03:16:21 +00001543 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001544 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001545
1546 return keepGoing;
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001547}
1548
Ted Kremeneke0e53132010-01-28 23:39:18 +00001549void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1550 // The presence of a null character is likely an error.
1551 S.Diag(getLocationOfByte(nullCharacter),
1552 diag::warn_printf_format_string_contains_null_char)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001553 << getFormatStringRange();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001554}
1555
Ted Kremenek0d277352010-01-29 01:06:55 +00001556const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001557 return TheCall->getArg(FirstDataArg + i);
Ted Kremenek0d277352010-01-29 01:06:55 +00001558}
1559
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001560void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1561 llvm::StringRef flag,
1562 llvm::StringRef cspec,
1563 const char *startSpecifier,
1564 unsigned specifierLen) {
1565 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1566 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1567 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1568}
1569
Ted Kremenek0d277352010-01-29 01:06:55 +00001570bool
1571CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
Ted Kremenekefaff192010-02-27 01:41:03 +00001572 unsigned k, const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001573 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001574
1575 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001576 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001577 unsigned argIndex = Amt.getArgIndex();
1578 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001579 S.Diag(getLocationOfByte(Amt.getStart()),
1580 diag::warn_printf_asterisk_missing_arg)
1581 << k << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001582 // Don't do any more checking. We will just emit
1583 // spurious errors.
1584 return false;
1585 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001586
Ted Kremenek0d277352010-01-29 01:06:55 +00001587 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001588 // Although not in conformance with C99, we also allow the argument to be
1589 // an 'unsigned int' as that is a reasonably safe case. GCC also
1590 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001591 CoveredArgs.set(argIndex);
1592 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001593 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001594
1595 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1596 assert(ATR.isValid());
1597
1598 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001599 S.Diag(getLocationOfByte(Amt.getStart()),
1600 diag::warn_printf_asterisk_wrong_type)
1601 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001602 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001603 << getFormatSpecifierRange(startSpecifier, specifierLen)
1604 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001605 // Don't do any more checking. We will just emit
1606 // spurious errors.
1607 return false;
1608 }
1609 }
1610 }
1611 return true;
1612}
Ted Kremenek0d277352010-01-29 01:06:55 +00001613
Ted Kremeneke0e53132010-01-28 23:39:18 +00001614bool
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001615CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1616 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001617 const char *startSpecifier,
1618 unsigned specifierLen) {
1619
Ted Kremenekefaff192010-02-27 01:41:03 +00001620 using namespace analyze_printf;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001621 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1622
Ted Kremenekefaff192010-02-27 01:41:03 +00001623 if (atFirstArg) {
1624 atFirstArg = false;
1625 usesPositionalArgs = FS.usesPositionalArg();
1626 }
1627 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1628 // Cannot mix-and-match positional and non-positional arguments.
1629 S.Diag(getLocationOfByte(CS.getStart()),
1630 diag::warn_printf_mix_positional_nonpositional_args)
1631 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001632 return false;
1633 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001634
Ted Kremenekefaff192010-02-27 01:41:03 +00001635 // First check if the field width, precision, and conversion specifier
1636 // have matching data arguments.
1637 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1638 startSpecifier, specifierLen)) {
1639 return false;
1640 }
1641
1642 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1643 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001644 return false;
1645 }
1646
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001647 if (!CS.consumesDataArgument()) {
1648 // FIXME: Technically specifying a precision or field width here
1649 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001650 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001651 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001652
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001653 // Consume the argument.
1654 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001655 if (argIndex < NumDataArgs) {
1656 // The check to see if the argIndex is valid will come later.
1657 // We set the bit here because we may exit early from this
1658 // function if we encounter some other error.
1659 CoveredArgs.set(argIndex);
1660 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001661
1662 // Check for using an Objective-C specific conversion specifier
1663 // in a non-ObjC literal.
1664 if (!IsObjCLiteral && CS.isObjCArg()) {
1665 return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1666 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001667
Ted Kremeneke82d8042010-01-29 01:35:25 +00001668 // Are we using '%n'? Issue a warning about this being
1669 // a possible security issue.
1670 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1671 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001672 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001673 // Continue checking the other format specifiers.
1674 return true;
1675 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001676
1677 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1678 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001679 S.Diag(getLocationOfByte(CS.getStart()),
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001680 diag::warn_printf_nonsensical_precision)
1681 << CS.getCharacters()
1682 << getFormatSpecifierRange(startSpecifier, specifierLen);
1683 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001684 if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1685 CS.getKind() == ConversionSpecifier::CStrArg) {
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001686 // FIXME: Instead of using "0", "+", etc., eventually get them from
1687 // the FormatSpecifier.
1688 if (FS.hasLeadingZeros())
1689 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1690 if (FS.hasPlusPrefix())
1691 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1692 if (FS.hasSpacePrefix())
1693 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001694 }
1695
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001696 // The remaining checks depend on the data arguments.
1697 if (HasVAListArg)
1698 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001699
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001700 if (argIndex >= NumDataArgs) {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001701 if (FS.usesPositionalArg()) {
1702 S.Diag(getLocationOfByte(CS.getStart()),
1703 diag::warn_printf_positional_arg_exceeds_data_args)
1704 << (argIndex+1) << NumDataArgs
1705 << getFormatSpecifierRange(startSpecifier, specifierLen);
1706 }
1707 else {
1708 S.Diag(getLocationOfByte(CS.getStart()),
1709 diag::warn_printf_insufficient_data_args)
1710 << getFormatSpecifierRange(startSpecifier, specifierLen);
1711 }
1712
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001713 // Don't do any more checking.
1714 return false;
1715 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001716
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001717 // Now type check the data expression that matches the
1718 // format specifier.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001719 const Expr *Ex = getDataArg(argIndex);
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001720 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001721 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1722 // Check if we didn't match because of an implicit cast from a 'char'
1723 // or 'short' to an 'int'. This is done because printf is a varargs
1724 // function.
1725 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1726 if (ICE->getType() == S.Context.IntTy)
1727 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1728 return true;
Ted Kremenek105d41c2010-02-01 19:38:10 +00001729
Tom Care3bfc5f42010-06-09 04:11:11 +00001730 // We may be able to offer a FixItHint if it is a supported type.
1731 FormatSpecifier fixedFS = FS;
1732 bool success = fixedFS.fixType(Ex->getType());
1733
1734 if (success) {
1735 // Get the fix string from the fixed format specifier
1736 llvm::SmallString<128> buf;
1737 llvm::raw_svector_ostream os(buf);
1738 fixedFS.toString(os);
1739
1740 S.Diag(getLocationOfByte(CS.getStart()),
1741 diag::warn_printf_conversion_argument_type_mismatch)
1742 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1743 << getFormatSpecifierRange(startSpecifier, specifierLen)
1744 << Ex->getSourceRange()
1745 << FixItHint::CreateReplacement(
1746 getFormatSpecifierRange(startSpecifier, specifierLen),
1747 os.str());
1748 }
1749 else {
1750 S.Diag(getLocationOfByte(CS.getStart()),
1751 diag::warn_printf_conversion_argument_type_mismatch)
1752 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1753 << getFormatSpecifierRange(startSpecifier, specifierLen)
1754 << Ex->getSourceRange();
1755 }
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001756 }
Ted Kremeneke0e53132010-01-28 23:39:18 +00001757
1758 return true;
1759}
1760
Ted Kremenek07d161f2010-01-29 01:50:07 +00001761void CheckPrintfHandler::DoneProcessing() {
1762 // Does the number of data arguments exceed the number of
1763 // format conversions in the format string?
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001764 if (!HasVAListArg) {
1765 // Find any arguments that weren't covered.
1766 CoveredArgs.flip();
1767 signed notCoveredArg = CoveredArgs.find_first();
1768 if (notCoveredArg >= 0) {
1769 assert((unsigned)notCoveredArg < NumDataArgs);
1770 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1771 diag::warn_printf_data_arg_not_used)
1772 << getFormatStringRange();
1773 }
1774 }
Ted Kremenek07d161f2010-01-29 01:50:07 +00001775}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001776
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001777void Sema::CheckPrintfString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001778 const Expr *OrigFormatExpr,
1779 const CallExpr *TheCall, bool HasVAListArg,
1780 unsigned format_idx, unsigned firstDataArg) {
1781
Ted Kremeneke0e53132010-01-28 23:39:18 +00001782 // CHECK: is the format string a wide literal?
1783 if (FExpr->isWide()) {
1784 Diag(FExpr->getLocStart(),
1785 diag::warn_printf_format_string_is_wide_literal)
1786 << OrigFormatExpr->getSourceRange();
1787 return;
1788 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001789
Ted Kremeneke0e53132010-01-28 23:39:18 +00001790 // Str - The format string. NOTE: this is NOT null-terminated!
1791 const char *Str = FExpr->getStrData();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001792
Ted Kremeneke0e53132010-01-28 23:39:18 +00001793 // CHECK: empty format string?
1794 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001795
Ted Kremeneke0e53132010-01-28 23:39:18 +00001796 if (StrLen == 0) {
1797 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1798 << OrigFormatExpr->getSourceRange();
1799 return;
1800 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001801
Ted Kremenek6ee76532010-03-25 03:59:12 +00001802 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001803 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek0d277352010-01-29 01:06:55 +00001804 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1805 HasVAListArg, TheCall, format_idx);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001806
Ted Kremenek74d56a12010-02-04 20:46:58 +00001807 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
Ted Kremenek808015a2010-01-29 03:16:21 +00001808 H.DoneProcessing();
Ted Kremenekce7024e2010-01-28 01:18:22 +00001809}
1810
Ted Kremenek06de2762007-08-17 16:46:58 +00001811//===--- CHECK: Return Address of Stack Variable --------------------------===//
1812
1813static DeclRefExpr* EvalVal(Expr *E);
1814static DeclRefExpr* EvalAddr(Expr* E);
1815
1816/// CheckReturnStackAddr - Check if a return statement returns the address
1817/// of a stack variable.
1818void
1819Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1820 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Ted Kremenek06de2762007-08-17 16:46:58 +00001822 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001823 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001824 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001825 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001826 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Steve Naroffc50a4a52008-09-16 22:25:10 +00001828 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001829 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001830
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001831 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001832 if (C->hasBlockDeclRefExprs())
1833 Diag(C->getLocStart(), diag::err_ret_local_block)
1834 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001835
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001836 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1837 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1838 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001839
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001840 } else if (lhsType->isReferenceType()) {
1841 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001842 // Check for a reference to the stack
1843 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001844 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001845 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001846 }
1847}
1848
1849/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1850/// check if the expression in a return statement evaluates to an address
1851/// to a location on the stack. The recursion is used to traverse the
1852/// AST of the return expression, with recursion backtracking when we
1853/// encounter a subexpression that (1) clearly does not lead to the address
1854/// of a stack variable or (2) is something we cannot determine leads to
1855/// the address of a stack variable based on such local checking.
1856///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001857/// EvalAddr processes expressions that are pointers that are used as
1858/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001859/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001860/// the refers to a stack variable.
1861///
1862/// This implementation handles:
1863///
1864/// * pointer-to-pointer casts
1865/// * implicit conversions from array references to pointers
1866/// * taking the address of fields
1867/// * arbitrary interplay between "&" and "*" operators
1868/// * pointer arithmetic from an address of a stack variable
1869/// * taking the address of an array element where the array is on the stack
1870static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001871 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001872 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001873 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001874 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001875 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Ted Kremenek06de2762007-08-17 16:46:58 +00001877 // Our "symbolic interpreter" is just a dispatch off the currently
1878 // viewed AST node. We then recursively traverse the AST by calling
1879 // EvalAddr and EvalVal appropriately.
1880 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001881 case Stmt::ParenExprClass:
1882 // Ignore parentheses.
1883 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001884
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001885 case Stmt::UnaryOperatorClass: {
1886 // The only unary operator that make sense to handle here
1887 // is AddrOf. All others don't make sense as pointers.
1888 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001890 if (U->getOpcode() == UnaryOperator::AddrOf)
1891 return EvalVal(U->getSubExpr());
1892 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001893 return NULL;
1894 }
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001896 case Stmt::BinaryOperatorClass: {
1897 // Handle pointer arithmetic. All other binary operators are not valid
1898 // in this context.
1899 BinaryOperator *B = cast<BinaryOperator>(E);
1900 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001902 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1903 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001905 Expr *Base = B->getLHS();
1906
1907 // Determine which argument is the real pointer base. It could be
1908 // the RHS argument instead of the LHS.
1909 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001911 assert (Base->getType()->isPointerType());
1912 return EvalAddr(Base);
1913 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001914
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001915 // For conditional operators we need to see if either the LHS or RHS are
1916 // valid DeclRefExpr*s. If one of them is valid, we return it.
1917 case Stmt::ConditionalOperatorClass: {
1918 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001920 // Handle the GNU extension for missing LHS.
1921 if (Expr *lhsExpr = C->getLHS())
1922 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1923 return LHS;
1924
1925 return EvalAddr(C->getRHS());
1926 }
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Ted Kremenek54b52742008-08-07 00:49:01 +00001928 // For casts, we need to handle conversions from arrays to
1929 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001930 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001931 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001932 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001933 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001934 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Steve Naroffdd972f22008-09-05 22:11:13 +00001936 if (SubExpr->getType()->isPointerType() ||
1937 SubExpr->getType()->isBlockPointerType() ||
1938 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001939 return EvalAddr(SubExpr);
1940 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001941 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001942 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001943 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001944 }
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001946 // C++ casts. For dynamic casts, static casts, and const casts, we
1947 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001948 // through the cast. In the case the dynamic cast doesn't fail (and
1949 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001950 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001951 // FIXME: The comment about is wrong; we're not always converting
1952 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001953 // handle references to objects.
1954 case Stmt::CXXStaticCastExprClass:
1955 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001956 case Stmt::CXXConstCastExprClass:
1957 case Stmt::CXXReinterpretCastExprClass: {
1958 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001959 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001960 return EvalAddr(S);
1961 else
1962 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001963 }
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001965 // Everything else: we simply don't reason about them.
1966 default:
1967 return NULL;
1968 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001969}
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Ted Kremenek06de2762007-08-17 16:46:58 +00001971
1972/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1973/// See the comments for EvalAddr for more details.
1974static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001976 // We should only be called for evaluating non-pointer expressions, or
1977 // expressions with a pointer type that are not used as references but instead
1978 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Ted Kremenek06de2762007-08-17 16:46:58 +00001980 // Our "symbolic interpreter" is just a dispatch off the currently
1981 // viewed AST node. We then recursively traverse the AST by calling
1982 // EvalAddr and EvalVal appropriately.
1983 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001984 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001985 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1986 // at code that refers to a variable's name. We check if it has local
1987 // storage within the function, and if so, return the expression.
1988 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Ted Kremenek06de2762007-08-17 16:46:58 +00001990 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001991 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1992
Ted Kremenek06de2762007-08-17 16:46:58 +00001993 return NULL;
1994 }
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Ted Kremenek06de2762007-08-17 16:46:58 +00001996 case Stmt::ParenExprClass:
1997 // Ignore parentheses.
1998 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Ted Kremenek06de2762007-08-17 16:46:58 +00002000 case Stmt::UnaryOperatorClass: {
2001 // The only unary operator that make sense to handle here
2002 // is Deref. All others don't resolve to a "name." This includes
2003 // handling all sorts of rvalues passed to a unary operator.
2004 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Ted Kremenek06de2762007-08-17 16:46:58 +00002006 if (U->getOpcode() == UnaryOperator::Deref)
2007 return EvalAddr(U->getSubExpr());
2008
2009 return NULL;
2010 }
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Ted Kremenek06de2762007-08-17 16:46:58 +00002012 case Stmt::ArraySubscriptExprClass: {
2013 // Array subscripts are potential references to data on the stack. We
2014 // retrieve the DeclRefExpr* for the array variable if it indeed
2015 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00002016 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00002017 }
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Ted Kremenek06de2762007-08-17 16:46:58 +00002019 case Stmt::ConditionalOperatorClass: {
2020 // For conditional operators we need to see if either the LHS or RHS are
2021 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
2022 ConditionalOperator *C = cast<ConditionalOperator>(E);
2023
Anders Carlsson39073232007-11-30 19:04:31 +00002024 // Handle the GNU extension for missing LHS.
2025 if (Expr *lhsExpr = C->getLHS())
2026 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
2027 return LHS;
2028
2029 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00002030 }
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Ted Kremenek06de2762007-08-17 16:46:58 +00002032 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002033 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002034 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Ted Kremenek06de2762007-08-17 16:46:58 +00002036 // Check for indirect access. We only want direct field accesses.
2037 if (!M->isArrow())
2038 return EvalVal(M->getBase());
2039 else
2040 return NULL;
2041 }
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Ted Kremenek06de2762007-08-17 16:46:58 +00002043 // Everything else: we simply don't reason about them.
2044 default:
2045 return NULL;
2046 }
2047}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002048
2049//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2050
2051/// Check for comparisons of floating point operands using != and ==.
2052/// Issue a warning if these are no self-comparisons, as they are not likely
2053/// to do what the programmer intended.
2054void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2055 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002057 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00002058 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002059
2060 // Special case: check for x == x (which is OK).
2061 // Do not emit warnings for such cases.
2062 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2063 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2064 if (DRL->getDecl() == DRR->getDecl())
2065 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002066
2067
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002068 // Special case: check for comparisons against literals that can be exactly
2069 // represented by APFloat. In such cases, do not emit a warning. This
2070 // is a heuristic: often comparison against such literals are used to
2071 // detect if a value in a variable has not changed. This clearly can
2072 // lead to false negatives.
2073 if (EmitWarning) {
2074 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2075 if (FLL->isExact())
2076 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002077 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002078 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2079 if (FLR->isExact())
2080 EmitWarning = false;
2081 }
2082 }
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002084 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002085 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002086 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002087 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002088 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Sebastian Redl0eb23302009-01-19 00:08:26 +00002090 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002091 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002092 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002093 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002095 // Emit the diagnostic.
2096 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002097 Diag(loc, diag::warn_floatingpoint_eq)
2098 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002099}
John McCallba26e582010-01-04 23:21:16 +00002100
John McCallf2370c92010-01-06 05:24:50 +00002101//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2102//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002103
John McCallf2370c92010-01-06 05:24:50 +00002104namespace {
John McCallba26e582010-01-04 23:21:16 +00002105
John McCallf2370c92010-01-06 05:24:50 +00002106/// Structure recording the 'active' range of an integer-valued
2107/// expression.
2108struct IntRange {
2109 /// The number of bits active in the int.
2110 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002111
John McCallf2370c92010-01-06 05:24:50 +00002112 /// True if the int is known not to have negative values.
2113 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002114
John McCallf2370c92010-01-06 05:24:50 +00002115 IntRange() {}
2116 IntRange(unsigned Width, bool NonNegative)
2117 : Width(Width), NonNegative(NonNegative)
2118 {}
John McCallba26e582010-01-04 23:21:16 +00002119
John McCallf2370c92010-01-06 05:24:50 +00002120 // Returns the range of the bool type.
2121 static IntRange forBoolType() {
2122 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002123 }
2124
John McCallf2370c92010-01-06 05:24:50 +00002125 // Returns the range of an integral type.
2126 static IntRange forType(ASTContext &C, QualType T) {
2127 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002128 }
2129
John McCallf2370c92010-01-06 05:24:50 +00002130 // Returns the range of an integeral type based on its canonical
2131 // representation.
2132 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
2133 assert(T->isCanonicalUnqualified());
2134
2135 if (const VectorType *VT = dyn_cast<VectorType>(T))
2136 T = VT->getElementType().getTypePtr();
2137 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2138 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002139
2140 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2141 EnumDecl *Enum = ET->getDecl();
2142 unsigned NumPositive = Enum->getNumPositiveBits();
2143 unsigned NumNegative = Enum->getNumNegativeBits();
2144
2145 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2146 }
John McCallf2370c92010-01-06 05:24:50 +00002147
2148 const BuiltinType *BT = cast<BuiltinType>(T);
2149 assert(BT->isInteger());
2150
2151 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2152 }
2153
2154 // Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002155 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002156 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002157 L.NonNegative && R.NonNegative);
2158 }
2159
2160 // Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002161 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002162 return IntRange(std::min(L.Width, R.Width),
2163 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002164 }
2165};
2166
2167IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2168 if (value.isSigned() && value.isNegative())
2169 return IntRange(value.getMinSignedBits(), false);
2170
2171 if (value.getBitWidth() > MaxWidth)
2172 value.trunc(MaxWidth);
2173
2174 // isNonNegative() just checks the sign bit without considering
2175 // signedness.
2176 return IntRange(value.getActiveBits(), true);
2177}
2178
John McCall0acc3112010-01-06 22:57:21 +00002179IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002180 unsigned MaxWidth) {
2181 if (result.isInt())
2182 return GetValueRange(C, result.getInt(), MaxWidth);
2183
2184 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002185 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2186 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2187 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2188 R = IntRange::join(R, El);
2189 }
John McCallf2370c92010-01-06 05:24:50 +00002190 return R;
2191 }
2192
2193 if (result.isComplexInt()) {
2194 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2195 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2196 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002197 }
2198
2199 // This can happen with lossless casts to intptr_t of "based" lvalues.
2200 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002201 // FIXME: The only reason we need to pass the type in here is to get
2202 // the sign right on this one case. It would be nice if APValue
2203 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002204 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002205 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002206}
John McCallf2370c92010-01-06 05:24:50 +00002207
2208/// Pseudo-evaluate the given integer expression, estimating the
2209/// range of values it might take.
2210///
2211/// \param MaxWidth - the width to which the value will be truncated
2212IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2213 E = E->IgnoreParens();
2214
2215 // Try a full evaluation first.
2216 Expr::EvalResult result;
2217 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002218 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002219
2220 // I think we only want to look through implicit casts here; if the
2221 // user has an explicit widening cast, we should treat the value as
2222 // being of the new, wider type.
2223 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
2224 if (CE->getCastKind() == CastExpr::CK_NoOp)
2225 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2226
2227 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
2228
John McCall60fad452010-01-06 22:07:33 +00002229 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
2230 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
2231 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
2232
John McCallf2370c92010-01-06 05:24:50 +00002233 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002234 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002235 return OutputTypeRange;
2236
2237 IntRange SubRange
2238 = GetExprRange(C, CE->getSubExpr(),
2239 std::min(MaxWidth, OutputTypeRange.Width));
2240
2241 // Bail out if the subexpr's range is as wide as the cast type.
2242 if (SubRange.Width >= OutputTypeRange.Width)
2243 return OutputTypeRange;
2244
2245 // Otherwise, we take the smaller width, and we're non-negative if
2246 // either the output type or the subexpr is.
2247 return IntRange(SubRange.Width,
2248 SubRange.NonNegative || OutputTypeRange.NonNegative);
2249 }
2250
2251 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2252 // If we can fold the condition, just take that operand.
2253 bool CondResult;
2254 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2255 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2256 : CO->getFalseExpr(),
2257 MaxWidth);
2258
2259 // Otherwise, conservatively merge.
2260 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2261 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2262 return IntRange::join(L, R);
2263 }
2264
2265 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2266 switch (BO->getOpcode()) {
2267
2268 // Boolean-valued operations are single-bit and positive.
2269 case BinaryOperator::LAnd:
2270 case BinaryOperator::LOr:
2271 case BinaryOperator::LT:
2272 case BinaryOperator::GT:
2273 case BinaryOperator::LE:
2274 case BinaryOperator::GE:
2275 case BinaryOperator::EQ:
2276 case BinaryOperator::NE:
2277 return IntRange::forBoolType();
2278
John McCallc0cd21d2010-02-23 19:22:29 +00002279 // The type of these compound assignments is the type of the LHS,
2280 // so the RHS is not necessarily an integer.
2281 case BinaryOperator::MulAssign:
2282 case BinaryOperator::DivAssign:
2283 case BinaryOperator::RemAssign:
2284 case BinaryOperator::AddAssign:
2285 case BinaryOperator::SubAssign:
2286 return IntRange::forType(C, E->getType());
2287
John McCallf2370c92010-01-06 05:24:50 +00002288 // Operations with opaque sources are black-listed.
2289 case BinaryOperator::PtrMemD:
2290 case BinaryOperator::PtrMemI:
2291 return IntRange::forType(C, E->getType());
2292
John McCall60fad452010-01-06 22:07:33 +00002293 // Bitwise-and uses the *infinum* of the two source ranges.
2294 case BinaryOperator::And:
John McCallc0cd21d2010-02-23 19:22:29 +00002295 case BinaryOperator::AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002296 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2297 GetExprRange(C, BO->getRHS(), MaxWidth));
2298
John McCallf2370c92010-01-06 05:24:50 +00002299 // Left shift gets black-listed based on a judgement call.
2300 case BinaryOperator::Shl:
John McCall3aae6092010-04-07 01:14:35 +00002301 // ...except that we want to treat '1 << (blah)' as logically
2302 // positive. It's an important idiom.
2303 if (IntegerLiteral *I
2304 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2305 if (I->getValue() == 1) {
2306 IntRange R = IntRange::forType(C, E->getType());
2307 return IntRange(R.Width, /*NonNegative*/ true);
2308 }
2309 }
2310 // fallthrough
2311
John McCallc0cd21d2010-02-23 19:22:29 +00002312 case BinaryOperator::ShlAssign:
John McCallf2370c92010-01-06 05:24:50 +00002313 return IntRange::forType(C, E->getType());
2314
John McCall60fad452010-01-06 22:07:33 +00002315 // Right shift by a constant can narrow its left argument.
John McCallc0cd21d2010-02-23 19:22:29 +00002316 case BinaryOperator::Shr:
2317 case BinaryOperator::ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002318 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2319
2320 // If the shift amount is a positive constant, drop the width by
2321 // that much.
2322 llvm::APSInt shift;
2323 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2324 shift.isNonNegative()) {
2325 unsigned zext = shift.getZExtValue();
2326 if (zext >= L.Width)
2327 L.Width = (L.NonNegative ? 0 : 1);
2328 else
2329 L.Width -= zext;
2330 }
2331
2332 return L;
2333 }
2334
2335 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00002336 case BinaryOperator::Comma:
2337 return GetExprRange(C, BO->getRHS(), MaxWidth);
2338
John McCall60fad452010-01-06 22:07:33 +00002339 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00002340 case BinaryOperator::Sub:
2341 if (BO->getLHS()->getType()->isPointerType())
2342 return IntRange::forType(C, E->getType());
2343 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002344
John McCallf2370c92010-01-06 05:24:50 +00002345 default:
2346 break;
2347 }
2348
2349 // Treat every other operator as if it were closed on the
2350 // narrowest type that encompasses both operands.
2351 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2352 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2353 return IntRange::join(L, R);
2354 }
2355
2356 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2357 switch (UO->getOpcode()) {
2358 // Boolean-valued operations are white-listed.
2359 case UnaryOperator::LNot:
2360 return IntRange::forBoolType();
2361
2362 // Operations with opaque sources are black-listed.
2363 case UnaryOperator::Deref:
2364 case UnaryOperator::AddrOf: // should be impossible
2365 case UnaryOperator::OffsetOf:
2366 return IntRange::forType(C, E->getType());
2367
2368 default:
2369 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2370 }
2371 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002372
2373 if (dyn_cast<OffsetOfExpr>(E)) {
2374 IntRange::forType(C, E->getType());
2375 }
John McCallf2370c92010-01-06 05:24:50 +00002376
2377 FieldDecl *BitField = E->getBitField();
2378 if (BitField) {
2379 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2380 unsigned BitWidth = BitWidthAP.getZExtValue();
2381
2382 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2383 }
2384
2385 return IntRange::forType(C, E->getType());
2386}
John McCall51313c32010-01-04 23:31:57 +00002387
John McCall323ed742010-05-06 08:58:33 +00002388IntRange GetExprRange(ASTContext &C, Expr *E) {
2389 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2390}
2391
John McCall51313c32010-01-04 23:31:57 +00002392/// Checks whether the given value, which currently has the given
2393/// source semantics, has the same value when coerced through the
2394/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002395bool IsSameFloatAfterCast(const llvm::APFloat &value,
2396 const llvm::fltSemantics &Src,
2397 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002398 llvm::APFloat truncated = value;
2399
2400 bool ignored;
2401 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2402 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2403
2404 return truncated.bitwiseIsEqual(value);
2405}
2406
2407/// Checks whether the given value, which currently has the given
2408/// source semantics, has the same value when coerced through the
2409/// target semantics.
2410///
2411/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002412bool IsSameFloatAfterCast(const APValue &value,
2413 const llvm::fltSemantics &Src,
2414 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002415 if (value.isFloat())
2416 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2417
2418 if (value.isVector()) {
2419 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2420 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2421 return false;
2422 return true;
2423 }
2424
2425 assert(value.isComplexFloat());
2426 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2427 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2428}
2429
John McCall323ed742010-05-06 08:58:33 +00002430void AnalyzeImplicitConversions(Sema &S, Expr *E);
2431
2432bool IsZero(Sema &S, Expr *E) {
2433 llvm::APSInt Value;
2434 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2435}
2436
2437void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
2438 BinaryOperator::Opcode op = E->getOpcode();
2439 if (op == BinaryOperator::LT && IsZero(S, E->getRHS())) {
2440 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2441 << "< 0" << "false"
2442 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2443 } else if (op == BinaryOperator::GE && IsZero(S, E->getRHS())) {
2444 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2445 << ">= 0" << "true"
2446 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2447 } else if (op == BinaryOperator::GT && IsZero(S, E->getLHS())) {
2448 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2449 << "0 >" << "false"
2450 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2451 } else if (op == BinaryOperator::LE && IsZero(S, E->getLHS())) {
2452 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2453 << "0 <=" << "true"
2454 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2455 }
2456}
2457
2458/// Analyze the operands of the given comparison. Implements the
2459/// fallback case from AnalyzeComparison.
2460void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
2461 AnalyzeImplicitConversions(S, E->getLHS());
2462 AnalyzeImplicitConversions(S, E->getRHS());
2463}
John McCall51313c32010-01-04 23:31:57 +00002464
John McCallba26e582010-01-04 23:21:16 +00002465/// \brief Implements -Wsign-compare.
2466///
2467/// \param lex the left-hand expression
2468/// \param rex the right-hand expression
2469/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002470/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002471void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2472 // The type the comparison is being performed in.
2473 QualType T = E->getLHS()->getType();
2474 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2475 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002476
John McCall323ed742010-05-06 08:58:33 +00002477 // We don't do anything special if this isn't an unsigned integral
2478 // comparison: we're only interested in integral comparisons, and
2479 // signed comparisons only happen in cases we don't care to warn about.
2480 if (!T->isUnsignedIntegerType())
2481 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002482
John McCall323ed742010-05-06 08:58:33 +00002483 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2484 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002485
John McCall323ed742010-05-06 08:58:33 +00002486 // Check to see if one of the (unmodified) operands is of different
2487 // signedness.
2488 Expr *signedOperand, *unsignedOperand;
2489 if (lex->getType()->isSignedIntegerType()) {
2490 assert(!rex->getType()->isSignedIntegerType() &&
2491 "unsigned comparison between two signed integer expressions?");
2492 signedOperand = lex;
2493 unsignedOperand = rex;
2494 } else if (rex->getType()->isSignedIntegerType()) {
2495 signedOperand = rex;
2496 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002497 } else {
John McCall323ed742010-05-06 08:58:33 +00002498 CheckTrivialUnsignedComparison(S, E);
2499 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002500 }
2501
John McCall323ed742010-05-06 08:58:33 +00002502 // Otherwise, calculate the effective range of the signed operand.
2503 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002504
John McCall323ed742010-05-06 08:58:33 +00002505 // Go ahead and analyze implicit conversions in the operands. Note
2506 // that we skip the implicit conversions on both sides.
2507 AnalyzeImplicitConversions(S, lex);
2508 AnalyzeImplicitConversions(S, rex);
John McCallba26e582010-01-04 23:21:16 +00002509
John McCall323ed742010-05-06 08:58:33 +00002510 // If the signed range is non-negative, -Wsign-compare won't fire,
2511 // but we should still check for comparisons which are always true
2512 // or false.
2513 if (signedRange.NonNegative)
2514 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002515
2516 // For (in)equality comparisons, if the unsigned operand is a
2517 // constant which cannot collide with a overflowed signed operand,
2518 // then reinterpreting the signed operand as unsigned will not
2519 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002520 if (E->isEqualityOp()) {
2521 unsigned comparisonWidth = S.Context.getIntWidth(T);
2522 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002523
John McCall323ed742010-05-06 08:58:33 +00002524 // We should never be unable to prove that the unsigned operand is
2525 // non-negative.
2526 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2527
2528 if (unsignedRange.Width < comparisonWidth)
2529 return;
2530 }
2531
2532 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2533 << lex->getType() << rex->getType()
2534 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002535}
2536
John McCall51313c32010-01-04 23:31:57 +00002537/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCall323ed742010-05-06 08:58:33 +00002538void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
John McCall51313c32010-01-04 23:31:57 +00002539 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2540}
2541
John McCall323ed742010-05-06 08:58:33 +00002542void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
2543 bool *ICContext = 0) {
2544 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002545
John McCall323ed742010-05-06 08:58:33 +00002546 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2547 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2548 if (Source == Target) return;
2549 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002550
2551 // Never diagnose implicit casts to bool.
2552 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2553 return;
2554
2555 // Strip vector types.
2556 if (isa<VectorType>(Source)) {
2557 if (!isa<VectorType>(Target))
John McCall323ed742010-05-06 08:58:33 +00002558 return DiagnoseImpCast(S, E, T, diag::warn_impcast_vector_scalar);
John McCall51313c32010-01-04 23:31:57 +00002559
2560 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2561 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2562 }
2563
2564 // Strip complex types.
2565 if (isa<ComplexType>(Source)) {
2566 if (!isa<ComplexType>(Target))
John McCall323ed742010-05-06 08:58:33 +00002567 return DiagnoseImpCast(S, E, T, diag::warn_impcast_complex_scalar);
John McCall51313c32010-01-04 23:31:57 +00002568
2569 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2570 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2571 }
2572
2573 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2574 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2575
2576 // If the source is floating point...
2577 if (SourceBT && SourceBT->isFloatingPoint()) {
2578 // ...and the target is floating point...
2579 if (TargetBT && TargetBT->isFloatingPoint()) {
2580 // ...then warn if we're dropping FP rank.
2581
2582 // Builtin FP kinds are ordered by increasing FP rank.
2583 if (SourceBT->getKind() > TargetBT->getKind()) {
2584 // Don't warn about float constants that are precisely
2585 // representable in the target type.
2586 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002587 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002588 // Value might be a float, a float vector, or a float complex.
2589 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002590 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2591 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002592 return;
2593 }
2594
John McCall323ed742010-05-06 08:58:33 +00002595 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002596 }
2597 return;
2598 }
2599
2600 // If the target is integral, always warn.
2601 if ((TargetBT && TargetBT->isInteger()))
2602 // TODO: don't warn for integer values?
John McCall323ed742010-05-06 08:58:33 +00002603 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_integer);
John McCall51313c32010-01-04 23:31:57 +00002604
2605 return;
2606 }
2607
John McCallf2370c92010-01-06 05:24:50 +00002608 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002609 return;
2610
John McCall323ed742010-05-06 08:58:33 +00002611 IntRange SourceRange = GetExprRange(S.Context, E);
2612 IntRange TargetRange = IntRange::forCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002613
2614 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002615 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2616 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002617 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall323ed742010-05-06 08:58:33 +00002618 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_64_32);
2619 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_precision);
2620 }
2621
2622 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2623 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2624 SourceRange.Width == TargetRange.Width)) {
2625 unsigned DiagID = diag::warn_impcast_integer_sign;
2626
2627 // Traditionally, gcc has warned about this under -Wsign-compare.
2628 // We also want to warn about it in -Wconversion.
2629 // So if -Wconversion is off, use a completely identical diagnostic
2630 // in the sign-compare group.
2631 // The conditional-checking code will
2632 if (ICContext) {
2633 DiagID = diag::warn_impcast_integer_sign_conditional;
2634 *ICContext = true;
2635 }
2636
2637 return DiagnoseImpCast(S, E, T, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002638 }
2639
2640 return;
2641}
2642
John McCall323ed742010-05-06 08:58:33 +00002643void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2644
2645void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
2646 bool &ICContext) {
2647 E = E->IgnoreParenImpCasts();
2648
2649 if (isa<ConditionalOperator>(E))
2650 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2651
2652 AnalyzeImplicitConversions(S, E);
2653 if (E->getType() != T)
2654 return CheckImplicitConversion(S, E, T, &ICContext);
2655 return;
2656}
2657
2658void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
2659 AnalyzeImplicitConversions(S, E->getCond());
2660
2661 bool Suspicious = false;
2662 CheckConditionalOperand(S, E->getTrueExpr(), T, Suspicious);
2663 CheckConditionalOperand(S, E->getFalseExpr(), T, Suspicious);
2664
2665 // If -Wconversion would have warned about either of the candidates
2666 // for a signedness conversion to the context type...
2667 if (!Suspicious) return;
2668
2669 // ...but it's currently ignored...
2670 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional))
2671 return;
2672
2673 // ...and -Wsign-compare isn't...
2674 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional))
2675 return;
2676
2677 // ...then check whether it would have warned about either of the
2678 // candidates for a signedness conversion to the condition type.
2679 if (E->getType() != T) {
2680 Suspicious = false;
2681 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
2682 E->getType(), &Suspicious);
2683 if (!Suspicious)
2684 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
2685 E->getType(), &Suspicious);
2686 if (!Suspicious)
2687 return;
2688 }
2689
2690 // If so, emit a diagnostic under -Wsign-compare.
2691 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2692 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2693 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2694 << lex->getType() << rex->getType()
2695 << lex->getSourceRange() << rex->getSourceRange();
2696}
2697
2698/// AnalyzeImplicitConversions - Find and report any interesting
2699/// implicit conversions in the given expression. There are a couple
2700/// of competing diagnostics here, -Wconversion and -Wsign-compare.
2701void AnalyzeImplicitConversions(Sema &S, Expr *OrigE) {
2702 QualType T = OrigE->getType();
2703 Expr *E = OrigE->IgnoreParenImpCasts();
2704
2705 // For conditional operators, we analyze the arguments as if they
2706 // were being fed directly into the output.
2707 if (isa<ConditionalOperator>(E)) {
2708 ConditionalOperator *CO = cast<ConditionalOperator>(E);
2709 CheckConditionalOperator(S, CO, T);
2710 return;
2711 }
2712
2713 // Go ahead and check any implicit conversions we might have skipped.
2714 // The non-canonical typecheck is just an optimization;
2715 // CheckImplicitConversion will filter out dead implicit conversions.
2716 if (E->getType() != T)
2717 CheckImplicitConversion(S, E, T);
2718
2719 // Now continue drilling into this expression.
2720
2721 // Skip past explicit casts.
2722 if (isa<ExplicitCastExpr>(E)) {
2723 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
2724 return AnalyzeImplicitConversions(S, E);
2725 }
2726
2727 // Do a somewhat different check with comparison operators.
2728 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isComparisonOp())
2729 return AnalyzeComparison(S, cast<BinaryOperator>(E));
2730
2731 // These break the otherwise-useful invariant below. Fortunately,
2732 // we don't really need to recurse into them, because any internal
2733 // expressions should have been analyzed already when they were
2734 // built into statements.
2735 if (isa<StmtExpr>(E)) return;
2736
2737 // Don't descend into unevaluated contexts.
2738 if (isa<SizeOfAlignOfExpr>(E)) return;
2739
2740 // Now just recurse over the expression's children.
2741 for (Stmt::child_iterator I = E->child_begin(), IE = E->child_end();
2742 I != IE; ++I)
2743 AnalyzeImplicitConversions(S, cast<Expr>(*I));
2744}
2745
2746} // end anonymous namespace
2747
2748/// Diagnoses "dangerous" implicit conversions within the given
2749/// expression (which is a full expression). Implements -Wconversion
2750/// and -Wsign-compare.
2751void Sema::CheckImplicitConversions(Expr *E) {
2752 // Don't diagnose in unevaluated contexts.
2753 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2754 return;
2755
2756 // Don't diagnose for value- or type-dependent expressions.
2757 if (E->isTypeDependent() || E->isValueDependent())
2758 return;
2759
2760 AnalyzeImplicitConversions(*this, E);
2761}
2762
Mike Stumpf8c49212010-01-21 03:59:47 +00002763/// CheckParmsForFunctionDef - Check that the parameters of the given
2764/// function are appropriate for the definition of a function. This
2765/// takes care of any checks that cannot be performed on the
2766/// declaration itself, e.g., that the types of each of the function
2767/// parameters are complete.
2768bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2769 bool HasInvalidParm = false;
2770 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2771 ParmVarDecl *Param = FD->getParamDecl(p);
2772
2773 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2774 // function declarator that is part of a function definition of
2775 // that function shall not have incomplete type.
2776 //
2777 // This is also C++ [dcl.fct]p6.
2778 if (!Param->isInvalidDecl() &&
2779 RequireCompleteType(Param->getLocation(), Param->getType(),
2780 diag::err_typecheck_decl_incomplete_type)) {
2781 Param->setInvalidDecl();
2782 HasInvalidParm = true;
2783 }
2784
2785 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2786 // declaration of each parameter shall include an identifier.
2787 if (Param->getIdentifier() == 0 &&
2788 !Param->isImplicit() &&
2789 !getLangOptions().CPlusPlus)
2790 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002791
2792 // C99 6.7.5.3p12:
2793 // If the function declarator is not part of a definition of that
2794 // function, parameters may have incomplete type and may use the [*]
2795 // notation in their sequences of declarator specifiers to specify
2796 // variable length array types.
2797 QualType PType = Param->getOriginalType();
2798 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2799 if (AT->getSizeModifier() == ArrayType::Star) {
2800 // FIXME: This diagnosic should point the the '[*]' if source-location
2801 // information is added for it.
2802 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2803 }
2804 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002805 }
2806
2807 return HasInvalidParm;
2808}