blob: 7fa5762f06a42e936c5689387b0c697f28f866f3 [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"
Eric Christopher691ebc32010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000030#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000031using namespace clang;
32
Chris Lattner60800082009-02-18 17:49:48 +000033/// getLocationOfStringLiteralByte - Return a source location that points to the
34/// specified byte of the specified string literal.
35///
36/// Strings are amazingly complex. They can be formed from multiple tokens and
37/// can have escape sequences in them in addition to the usual trigraph and
38/// escaped newline business. This routine handles this complexity.
39///
40SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
41 unsigned ByteNo) const {
42 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044 // Loop over all of the tokens in this string until we find the one that
45 // contains the byte we're looking for.
46 unsigned TokNo = 0;
47 while (1) {
48 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
49 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000050
Chris Lattner60800082009-02-18 17:49:48 +000051 // Get the spelling of the string so that we can get the data that makes up
52 // the string literal, not the identifier for the macro it is potentially
53 // expanded through.
54 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
55
56 // Re-lex the token to get its length and original spelling.
57 std::pair<FileID, unsigned> LocInfo =
58 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
Douglas Gregorf715ca12010-03-16 00:06:06 +000059 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000060 llvm::StringRef Buffer = SourceMgr.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +000061 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +000062 return StrTokSpellingLoc;
63
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000064 const char *StrData = Buffer.data()+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner60800082009-02-18 17:49:48 +000066 // Create a langops struct and enable trigraphs. This is sufficient for
67 // relexing tokens.
68 LangOptions LangOpts;
69 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattner60800082009-02-18 17:49:48 +000071 // Create a lexer starting at the beginning of this token.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000072 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.begin(), StrData,
73 Buffer.end());
Chris Lattner60800082009-02-18 17:49:48 +000074 Token TheTok;
75 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000076
Chris Lattner443e53c2009-02-18 19:26:42 +000077 // Use the StringLiteralParser to compute the length of the string in bytes.
Douglas Gregorb90f4b32010-05-26 05:35:51 +000078 StringLiteralParser SLP(&TheTok, 1, PP, /*Complain=*/false);
Chris Lattner443e53c2009-02-18 19:26:42 +000079 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattner2197c962009-02-18 18:52:52 +000081 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000082 if (ByteNo < TokNumBytes ||
83 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000084 unsigned Offset =
Douglas Gregorb90f4b32010-05-26 05:35:51 +000085 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP,
86 /*Complain=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +000087
Chris Lattner719e6152009-02-18 19:21:10 +000088 // Now that we know the offset of the token in the spelling, use the
89 // preprocessor to get the offset in the original source.
90 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000091 }
Mike Stump1eb44332009-09-09 15:08:12 +000092
Chris Lattner60800082009-02-18 17:49:48 +000093 // Move to the next string token.
94 ++TokNo;
95 ByteNo -= TokNumBytes;
96 }
97}
98
Ryan Flynn4403a5e2009-08-06 03:00:50 +000099/// CheckablePrintfAttr - does a function call have a "printf" attribute
100/// and arguments that merit checking?
101bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
102 if (Format->getType() == "printf") return true;
103 if (Format->getType() == "printf0") {
104 // printf0 allows null "format" string; if so don't check format/args
105 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000106 // Does the index refer to the implicit object argument?
107 if (isa<CXXMemberCallExpr>(TheCall)) {
108 if (format_idx == 0)
109 return false;
110 --format_idx;
111 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000112 if (format_idx < TheCall->getNumArgs()) {
113 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +0000114 if (!Format->isNullPointerConstant(Context,
115 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000116 return true;
117 }
118 }
119 return false;
120}
Chris Lattner60800082009-02-18 17:49:48 +0000121
Sebastian Redl0eb23302009-01-19 00:08:26 +0000122Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000123Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000124 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000125
Anders Carlssond406bf02009-08-16 01:56:34 +0000126 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000127 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000128 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000129 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000130 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000131 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000132 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000133 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000134 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000135 if (SemaBuiltinVAStart(TheCall))
136 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000137 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000138 case Builtin::BI__builtin_isgreater:
139 case Builtin::BI__builtin_isgreaterequal:
140 case Builtin::BI__builtin_isless:
141 case Builtin::BI__builtin_islessequal:
142 case Builtin::BI__builtin_islessgreater:
143 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000144 if (SemaBuiltinUnorderedCompare(TheCall))
145 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000146 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000147 case Builtin::BI__builtin_fpclassify:
148 if (SemaBuiltinFPClassification(TheCall, 6))
149 return ExprError();
150 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000151 case Builtin::BI__builtin_isfinite:
152 case Builtin::BI__builtin_isinf:
153 case Builtin::BI__builtin_isinf_sign:
154 case Builtin::BI__builtin_isnan:
155 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000156 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000157 return ExprError();
158 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000159 case Builtin::BI__builtin_return_address:
Eric Christopher691ebc32010-04-17 02:26:23 +0000160 case Builtin::BI__builtin_frame_address: {
161 llvm::APSInt Result;
162 if (SemaBuiltinConstantArg(TheCall, 0, Result))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000163 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000164 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000165 }
166 case Builtin::BI__builtin_eh_return_data_regno: {
167 llvm::APSInt Result;
168 if (SemaBuiltinConstantArg(TheCall, 0, Result))
Chris Lattner21fb98e2009-09-23 06:06:36 +0000169 return ExprError();
170 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000171 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000172 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000173 return SemaBuiltinShuffleVector(TheCall);
174 // TheCall will be freed by the smart pointer here, but that's fine, since
175 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000176 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000177 if (SemaBuiltinPrefetch(TheCall))
178 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000179 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000180 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000181 if (SemaBuiltinObjectSize(TheCall))
182 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000183 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000184 case Builtin::BI__builtin_longjmp:
185 if (SemaBuiltinLongjmp(TheCall))
186 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000187 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000188 case Builtin::BI__sync_fetch_and_add:
189 case Builtin::BI__sync_fetch_and_sub:
190 case Builtin::BI__sync_fetch_and_or:
191 case Builtin::BI__sync_fetch_and_and:
192 case Builtin::BI__sync_fetch_and_xor:
193 case Builtin::BI__sync_add_and_fetch:
194 case Builtin::BI__sync_sub_and_fetch:
195 case Builtin::BI__sync_and_and_fetch:
196 case Builtin::BI__sync_or_and_fetch:
197 case Builtin::BI__sync_xor_and_fetch:
198 case Builtin::BI__sync_val_compare_and_swap:
199 case Builtin::BI__sync_bool_compare_and_swap:
200 case Builtin::BI__sync_lock_test_and_set:
201 case Builtin::BI__sync_lock_release:
202 if (SemaBuiltinAtomicOverloaded(TheCall))
203 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000204 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000205
206 // Target specific builtins start here.
207 case X86::BI__builtin_ia32_palignr128:
208 case X86::BI__builtin_ia32_palignr: {
209 llvm::APSInt Result;
210 if (SemaBuiltinConstantArg(TheCall, 2, Result))
211 return ExprError();
212 break;
213 }
Anders Carlsson71993dd2007-08-17 05:31:46 +0000214 }
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Anders Carlssond406bf02009-08-16 01:56:34 +0000216 return move(TheCallResult);
217}
Daniel Dunbarde454282008-10-02 18:44:07 +0000218
Anders Carlssond406bf02009-08-16 01:56:34 +0000219/// CheckFunctionCall - Check a direct function call for various correctness
220/// and safety properties not strictly enforced by the C type system.
221bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
222 // Get the IdentifierInfo* for the called function.
223 IdentifierInfo *FnInfo = FDecl->getIdentifier();
224
225 // None of the checks below are needed for functions that don't have
226 // simple names (e.g., C++ conversion functions).
227 if (!FnInfo)
228 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Daniel Dunbarde454282008-10-02 18:44:07 +0000230 // FIXME: This mechanism should be abstracted to be less fragile and
231 // more efficient. For example, just map function ids to custom
232 // handlers.
233
Chris Lattner59907c42007-08-10 20:18:51 +0000234 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000235 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000236 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000237 bool HasVAListArg = Format->getFirstArg() == 0;
Douglas Gregor3c385e52009-02-14 18:57:46 +0000238 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000239 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000240 }
Chris Lattner59907c42007-08-10 20:18:51 +0000241 }
Mike Stump1eb44332009-09-09 15:08:12 +0000242
243 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000244 NonNull = NonNull->getNext<NonNullAttr>())
245 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000246
Anders Carlssond406bf02009-08-16 01:56:34 +0000247 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000248}
249
Anders Carlssond406bf02009-08-16 01:56:34 +0000250bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000251 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000252 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000253 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000254 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000255
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000256 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
257 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000258 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000260 QualType Ty = V->getType();
261 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000262 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Anders Carlssond406bf02009-08-16 01:56:34 +0000264 if (!CheckablePrintfAttr(Format, TheCall))
265 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Anders Carlssond406bf02009-08-16 01:56:34 +0000267 bool HasVAListArg = Format->getFirstArg() == 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000268 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
269 HasVAListArg ? 0 : Format->getFirstArg() - 1);
270
271 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000272}
273
Chris Lattner5caa3702009-05-08 06:58:22 +0000274/// SemaBuiltinAtomicOverloaded - We have a call to a function like
275/// __sync_fetch_and_add, which is an overloaded function based on the pointer
276/// type of its first argument. The main ActOnCallExpr routines have already
277/// promoted the types of arguments because all of these calls are prototyped as
278/// void(...).
279///
280/// This function goes through and does final semantic checking for these
281/// builtins,
282bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
283 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
284 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
285
286 // Ensure that we have at least one argument to do type inference from.
287 if (TheCall->getNumArgs() < 1)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000288 return Diag(TheCall->getLocEnd(),
289 diag::err_typecheck_call_too_few_args_at_least)
290 << 0 << 1 << TheCall->getNumArgs()
291 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Chris Lattner5caa3702009-05-08 06:58:22 +0000293 // Inspect the first argument of the atomic builtin. This should always be
294 // a pointer type, whose element is an integral scalar or pointer type.
295 // Because it is a pointer type, we don't have to worry about any implicit
296 // casts here.
297 Expr *FirstArg = TheCall->getArg(0);
298 if (!FirstArg->getType()->isPointerType())
299 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
300 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Ted Kremenek6217b802009-07-29 21:53:49 +0000302 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000303 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000304 !ValType->isBlockPointerType())
305 return Diag(DRE->getLocStart(),
306 diag::err_atomic_builtin_must_be_pointer_intptr)
307 << FirstArg->getType() << FirstArg->getSourceRange();
308
309 // We need to figure out which concrete builtin this maps onto. For example,
310 // __sync_fetch_and_add with a 2 byte object turns into
311 // __sync_fetch_and_add_2.
312#define BUILTIN_ROW(x) \
313 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
314 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chris Lattner5caa3702009-05-08 06:58:22 +0000316 static const unsigned BuiltinIndices[][5] = {
317 BUILTIN_ROW(__sync_fetch_and_add),
318 BUILTIN_ROW(__sync_fetch_and_sub),
319 BUILTIN_ROW(__sync_fetch_and_or),
320 BUILTIN_ROW(__sync_fetch_and_and),
321 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattner5caa3702009-05-08 06:58:22 +0000323 BUILTIN_ROW(__sync_add_and_fetch),
324 BUILTIN_ROW(__sync_sub_and_fetch),
325 BUILTIN_ROW(__sync_and_and_fetch),
326 BUILTIN_ROW(__sync_or_and_fetch),
327 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattner5caa3702009-05-08 06:58:22 +0000329 BUILTIN_ROW(__sync_val_compare_and_swap),
330 BUILTIN_ROW(__sync_bool_compare_and_swap),
331 BUILTIN_ROW(__sync_lock_test_and_set),
332 BUILTIN_ROW(__sync_lock_release)
333 };
Mike Stump1eb44332009-09-09 15:08:12 +0000334#undef BUILTIN_ROW
335
Chris Lattner5caa3702009-05-08 06:58:22 +0000336 // Determine the index of the size.
337 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000338 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000339 case 1: SizeIndex = 0; break;
340 case 2: SizeIndex = 1; break;
341 case 4: SizeIndex = 2; break;
342 case 8: SizeIndex = 3; break;
343 case 16: SizeIndex = 4; break;
344 default:
345 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
346 << FirstArg->getType() << FirstArg->getSourceRange();
347 }
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Chris Lattner5caa3702009-05-08 06:58:22 +0000349 // Each of these builtins has one pointer argument, followed by some number of
350 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
351 // that we ignore. Find out which row of BuiltinIndices to read from as well
352 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000353 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000354 unsigned BuiltinIndex, NumFixed = 1;
355 switch (BuiltinID) {
356 default: assert(0 && "Unknown overloaded atomic builtin!");
357 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
358 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
359 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
360 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
361 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000363 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
364 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
365 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
366 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
367 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Chris Lattner5caa3702009-05-08 06:58:22 +0000369 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000370 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000371 NumFixed = 2;
372 break;
373 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000374 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000375 NumFixed = 2;
376 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000377 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000378 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000379 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000380 NumFixed = 0;
381 break;
382 }
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Chris Lattner5caa3702009-05-08 06:58:22 +0000384 // Now that we know how many fixed arguments we expect, first check that we
385 // have at least that many.
386 if (TheCall->getNumArgs() < 1+NumFixed)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000387 return Diag(TheCall->getLocEnd(),
388 diag::err_typecheck_call_too_few_args_at_least)
389 << 0 << 1+NumFixed << TheCall->getNumArgs()
390 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000391
392
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000393 // Get the decl for the concrete builtin from this, we can tell what the
394 // concrete integer type we should convert to is.
395 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
396 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
397 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000398 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000399 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
400 TUScope, false, DRE->getLocStart()));
401 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000402 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000403 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000405 // If the first type needs to be converted (e.g. void** -> int*), do it now.
406 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000407 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000408 TheCall->setArg(0, FirstArg);
409 }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Chris Lattner5caa3702009-05-08 06:58:22 +0000411 // Next, walk the valid ones promoting to the right type.
412 for (unsigned i = 0; i != NumFixed; ++i) {
413 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner5caa3702009-05-08 06:58:22 +0000415 // If the argument is an implicit cast, then there was a promotion due to
416 // "...", just remove it now.
417 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
418 Arg = ICE->getSubExpr();
419 ICE->setSubExpr(0);
420 ICE->Destroy(Context);
421 TheCall->setArg(i+1, Arg);
422 }
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattner5caa3702009-05-08 06:58:22 +0000424 // GCC does an implicit conversion to the pointer or integer ValType. This
425 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000426 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000427 CXXBaseSpecifierArray BasePath;
428 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, BasePath))
Chris Lattner5caa3702009-05-08 06:58:22 +0000429 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Chris Lattner5caa3702009-05-08 06:58:22 +0000431 // Okay, we have something that *can* be converted to the right type. Check
432 // to see if there is a potentially weird extension going on here. This can
433 // happen when you do an atomic operation on something like an char* and
434 // pass in 42. The 42 gets converted to char. This is even more strange
435 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000436 // FIXME: Do this check.
Anders Carlsson80971bd2010-04-24 16:36:20 +0000437 ImpCastExprToType(Arg, ValType, Kind);
Chris Lattner5caa3702009-05-08 06:58:22 +0000438 TheCall->setArg(i+1, Arg);
439 }
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chris Lattner5caa3702009-05-08 06:58:22 +0000441 // Switch the DeclRefExpr to refer to the new decl.
442 DRE->setDecl(NewBuiltinDecl);
443 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Chris Lattner5caa3702009-05-08 06:58:22 +0000445 // Set the callee in the CallExpr.
446 // FIXME: This leaks the original parens and implicit casts.
447 Expr *PromotedCall = DRE;
448 UsualUnaryConversions(PromotedCall);
449 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattner5caa3702009-05-08 06:58:22 +0000451
452 // Change the result type of the call to match the result type of the decl.
453 TheCall->setType(NewBuiltinDecl->getResultType());
454 return false;
455}
456
457
Chris Lattner69039812009-02-18 06:01:06 +0000458/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000459/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000460/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000461/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000462/// belong to the input codeset UTF-8"
463/// Note: It might also make sense to do the UTF-16 conversion here (would
464/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000465bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000466 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000467 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
468
469 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000470 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
471 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000472 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Daniel Dunbarf015b032009-09-22 10:03:52 +0000475 const char *Data = Literal->getStrData();
476 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Daniel Dunbarf015b032009-09-22 10:03:52 +0000478 for (unsigned i = 0; i < Length; ++i) {
479 if (!Data[i]) {
480 Diag(getLocationOfStringLiteralByte(Literal, i),
481 diag::warn_cfstring_literal_contains_nul_character)
482 << Arg->getSourceRange();
483 break;
484 }
485 }
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000487 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000488}
489
Chris Lattnerc27c6652007-12-20 00:05:45 +0000490/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
491/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000492bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
493 Expr *Fn = TheCall->getCallee();
494 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000495 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000496 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000497 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
498 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000499 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000500 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000501 return true;
502 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000503
504 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000505 return Diag(TheCall->getLocEnd(),
506 diag::err_typecheck_call_too_few_args_at_least)
507 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000508 }
509
Chris Lattnerc27c6652007-12-20 00:05:45 +0000510 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000511 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000512 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000513 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000514 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000515 else if (FunctionDecl *FD = getCurFunctionDecl())
516 isVariadic = FD->isVariadic();
517 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000518 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Chris Lattnerc27c6652007-12-20 00:05:45 +0000520 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000521 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
522 return true;
523 }
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Chris Lattner30ce3442007-12-19 23:59:04 +0000525 // Verify that the second argument to the builtin is the last argument of the
526 // current function or method.
527 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000528 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Anders Carlsson88cf2262008-02-11 04:20:54 +0000530 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
531 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000532 // FIXME: This isn't correct for methods (results in bogus warning).
533 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000534 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000535 if (CurBlock)
536 LastArg = *(CurBlock->TheDecl->param_end()-1);
537 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000538 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000539 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000540 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000541 SecondArgIsLastNamedArgument = PV == LastArg;
542 }
543 }
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner30ce3442007-12-19 23:59:04 +0000545 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000546 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000547 diag::warn_second_parameter_of_va_start_not_last_named_argument);
548 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000549}
Chris Lattner30ce3442007-12-19 23:59:04 +0000550
Chris Lattner1b9a0792007-12-20 00:26:33 +0000551/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
552/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000553bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
554 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000555 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000556 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000557 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000558 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000559 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000560 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000561 << SourceRange(TheCall->getArg(2)->getLocStart(),
562 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Chris Lattner925e60d2007-12-28 05:29:59 +0000564 Expr *OrigArg0 = TheCall->getArg(0);
565 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000566
Chris Lattner1b9a0792007-12-20 00:26:33 +0000567 // Do standard promotions between the two arguments, returning their common
568 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000569 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000570
571 // Make sure any conversions are pushed back into the call; this is
572 // type safe since unordered compare builtins are declared as "_Bool
573 // foo(...)".
574 TheCall->setArg(0, OrigArg0);
575 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Douglas Gregorcde01732009-05-19 22:10:17 +0000577 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
578 return false;
579
Chris Lattner1b9a0792007-12-20 00:26:33 +0000580 // If the common type isn't a real floating type, then the arguments were
581 // invalid for this operation.
582 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000583 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000584 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000585 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000586 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Chris Lattner1b9a0792007-12-20 00:26:33 +0000588 return false;
589}
590
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000591/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
592/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000593/// to check everything. We expect the last argument to be a floating point
594/// value.
595bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
596 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000597 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000598 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000599 if (TheCall->getNumArgs() > NumArgs)
600 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000601 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000602 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000603 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000604 (*(TheCall->arg_end()-1))->getLocEnd());
605
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000606 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Eli Friedman9ac6f622009-08-31 20:06:00 +0000608 if (OrigArg->isTypeDependent())
609 return false;
610
Chris Lattner81368fb2010-05-06 05:50:07 +0000611 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000612 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000613 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000614 diag::err_typecheck_call_invalid_unary_fp)
615 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Chris Lattner81368fb2010-05-06 05:50:07 +0000617 // If this is an implicit conversion from float -> double, remove it.
618 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
619 Expr *CastArg = Cast->getSubExpr();
620 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
621 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
622 "promotion from float to double is the only expected cast here");
623 Cast->setSubExpr(0);
624 Cast->Destroy(Context);
625 TheCall->setArg(NumArgs-1, CastArg);
626 OrigArg = CastArg;
627 }
628 }
629
Eli Friedman9ac6f622009-08-31 20:06:00 +0000630 return false;
631}
632
Eli Friedmand38617c2008-05-14 19:38:39 +0000633/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
634// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000635Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000636 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000637 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000638 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000639 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000640 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000641
Nate Begeman37b6a572010-06-08 00:16:34 +0000642 // Determine which of the following types of shufflevector we're checking:
643 // 1) unary, vector mask: (lhs, mask)
644 // 2) binary, vector mask: (lhs, rhs, mask)
645 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
646 QualType resType = TheCall->getArg(0)->getType();
647 unsigned numElements = 0;
648
Douglas Gregorcde01732009-05-19 22:10:17 +0000649 if (!TheCall->getArg(0)->isTypeDependent() &&
650 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000651 QualType LHSType = TheCall->getArg(0)->getType();
652 QualType RHSType = TheCall->getArg(1)->getType();
653
654 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000655 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000656 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000657 TheCall->getArg(1)->getLocEnd());
658 return ExprError();
659 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000660
661 numElements = LHSType->getAs<VectorType>()->getNumElements();
662 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000663
Nate Begeman37b6a572010-06-08 00:16:34 +0000664 // Check to see if we have a call with 2 vector arguments, the unary shuffle
665 // with mask. If so, verify that RHS is an integer vector type with the
666 // same number of elts as lhs.
667 if (TheCall->getNumArgs() == 2) {
668 if (!RHSType->isIntegerType() ||
669 RHSType->getAs<VectorType>()->getNumElements() != numElements)
670 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
671 << SourceRange(TheCall->getArg(1)->getLocStart(),
672 TheCall->getArg(1)->getLocEnd());
673 numResElements = numElements;
674 }
675 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000676 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000677 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000678 TheCall->getArg(1)->getLocEnd());
679 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000680 } else if (numElements != numResElements) {
681 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
682 resType = Context.getVectorType(eltType, numResElements, false, false);
Douglas Gregorcde01732009-05-19 22:10:17 +0000683 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000684 }
685
686 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000687 if (TheCall->getArg(i)->isTypeDependent() ||
688 TheCall->getArg(i)->isValueDependent())
689 continue;
690
Nate Begeman37b6a572010-06-08 00:16:34 +0000691 llvm::APSInt Result(32);
692 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
693 return ExprError(Diag(TheCall->getLocStart(),
694 diag::err_shufflevector_nonconstant_argument)
695 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000696
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000697 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000698 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000699 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000700 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000701 }
702
703 llvm::SmallVector<Expr*, 32> exprs;
704
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000705 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000706 exprs.push_back(TheCall->getArg(i));
707 TheCall->setArg(i, 0);
708 }
709
Nate Begemana88dc302009-08-12 02:10:25 +0000710 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000711 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000712 TheCall->getCallee()->getLocStart(),
713 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000714}
Chris Lattner30ce3442007-12-19 23:59:04 +0000715
Daniel Dunbar4493f792008-07-21 22:59:13 +0000716/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
717// This is declared to take (const void*, ...) and can take two
718// optional constant int args.
719bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000720 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000721
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000722 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000723 return Diag(TheCall->getLocEnd(),
724 diag::err_typecheck_call_too_many_args_at_most)
725 << 0 /*function call*/ << 3 << NumArgs
726 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000727
728 // Argument 0 is checked for us and the remaining arguments must be
729 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000730 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000731 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000732
Eli Friedman9aef7262009-12-04 00:30:06 +0000733 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000734 if (SemaBuiltinConstantArg(TheCall, i, Result))
735 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Daniel Dunbar4493f792008-07-21 22:59:13 +0000737 // FIXME: gcc issues a warning and rewrites these to 0. These
738 // seems especially odd for the third argument since the default
739 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000740 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000741 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000742 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000743 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000744 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000745 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000746 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000747 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000748 }
749 }
750
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000751 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000752}
753
Eric Christopher691ebc32010-04-17 02:26:23 +0000754/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
755/// TheCall is a constant expression.
756bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
757 llvm::APSInt &Result) {
758 Expr *Arg = TheCall->getArg(ArgNum);
759 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
760 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
761
762 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
763
764 if (!Arg->isIntegerConstantExpr(Result, Context))
765 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000766 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000767
Chris Lattner21fb98e2009-09-23 06:06:36 +0000768 return false;
769}
770
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000771/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
772/// int type). This simply type checks that type is one of the defined
773/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000774// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000775bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000776 llvm::APSInt Result;
777
778 // Check constant-ness first.
779 if (SemaBuiltinConstantArg(TheCall, 1, Result))
780 return true;
781
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000782 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000783 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000784 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
785 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000786 }
787
788 return false;
789}
790
Eli Friedman586d6a82009-05-03 06:04:26 +0000791/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000792/// This checks that val is a constant 1.
793bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
794 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000795 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000796
Eric Christopher691ebc32010-04-17 02:26:23 +0000797 // TODO: This is less than ideal. Overload this to take a value.
798 if (SemaBuiltinConstantArg(TheCall, 1, Result))
799 return true;
800
801 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000802 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
803 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
804
805 return false;
806}
807
Ted Kremenekd30ef872009-01-12 23:09:09 +0000808// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000809bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
810 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000811 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000812 if (E->isTypeDependent() || E->isValueDependent())
813 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000814
815 switch (E->getStmtClass()) {
816 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000817 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000818 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000819 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000820 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000821 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000822 }
823
824 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000825 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000826 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000827 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000828 }
829
830 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000831 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000832 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000833 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000834 }
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Ted Kremenek082d9362009-03-20 21:35:28 +0000836 case Stmt::DeclRefExprClass: {
837 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Ted Kremenek082d9362009-03-20 21:35:28 +0000839 // As an exception, do not flag errors for variables binding to
840 // const string literals.
841 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
842 bool isConstant = false;
843 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000844
Ted Kremenek082d9362009-03-20 21:35:28 +0000845 if (const ArrayType *AT = Context.getAsArrayType(T)) {
846 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000847 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000848 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000849 PT->getPointeeType().isConstant(Context);
850 }
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Ted Kremenek082d9362009-03-20 21:35:28 +0000852 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000853 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000854 return SemaCheckStringLiteral(Init, TheCall,
855 HasVAListArg, format_idx, firstDataArg);
856 }
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Anders Carlssond966a552009-06-28 19:55:58 +0000858 // For vprintf* functions (i.e., HasVAListArg==true), we add a
859 // special check to see if the format string is a function parameter
860 // of the function calling the printf function. If the function
861 // has an attribute indicating it is a printf-like function, then we
862 // should suppress warnings concerning non-literals being used in a call
863 // to a vprintf function. For example:
864 //
865 // void
866 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
867 // va_list ap;
868 // va_start(ap, fmt);
869 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
870 // ...
871 //
872 //
873 // FIXME: We don't have full attribute support yet, so just check to see
874 // if the argument is a DeclRefExpr that references a parameter. We'll
875 // add proper support for checking the attribute later.
876 if (HasVAListArg)
877 if (isa<ParmVarDecl>(VD))
878 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000879 }
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Ted Kremenek082d9362009-03-20 21:35:28 +0000881 return false;
882 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000883
Anders Carlsson8f031b32009-06-27 04:05:33 +0000884 case Stmt::CallExprClass: {
885 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000886 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000887 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
888 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
889 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000890 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000891 unsigned ArgIndex = FA->getFormatIdx();
892 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000893
894 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000895 format_idx, firstDataArg);
896 }
897 }
898 }
899 }
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Anders Carlsson8f031b32009-06-27 04:05:33 +0000901 return false;
902 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000903 case Stmt::ObjCStringLiteralClass:
904 case Stmt::StringLiteralClass: {
905 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Ted Kremenek082d9362009-03-20 21:35:28 +0000907 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000908 StrE = ObjCFExpr->getString();
909 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000910 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Ted Kremenekd30ef872009-01-12 23:09:09 +0000912 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000913 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000914 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000915 return true;
916 }
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Ted Kremenekd30ef872009-01-12 23:09:09 +0000918 return false;
919 }
Mike Stump1eb44332009-09-09 15:08:12 +0000920
Ted Kremenek082d9362009-03-20 21:35:28 +0000921 default:
922 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000923 }
924}
925
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000926void
Mike Stump1eb44332009-09-09 15:08:12 +0000927Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
928 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000929 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
930 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000931 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000932 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +0000933 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000934 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
935 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000936 }
937}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000938
Chris Lattner59907c42007-08-10 20:18:51 +0000939/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000940/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000941///
942/// HasVAListArg - A predicate indicating whether the printf-like
943/// function is passed an explicit va_arg argument (e.g., vprintf)
944///
945/// format_idx - The index into Args for the format string.
946///
947/// Improper format strings to functions in the printf family can be
948/// the source of bizarre bugs and very serious security holes. A
949/// good source of information is available in the following paper
950/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000951///
952/// FormatGuard: Automatic Protection From printf Format String
953/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000954///
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000955/// TODO:
Ted Kremenek71895b92007-08-14 17:39:48 +0000956/// Functionality implemented:
957///
958/// We can statically check the following properties for string
959/// literal format strings for non v.*printf functions (where the
960/// arguments are passed directly):
961//
962/// (1) Are the number of format conversions equal to the number of
963/// data arguments?
964///
965/// (2) Does each format conversion correctly match the type of the
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000966/// corresponding data argument?
Ted Kremenek71895b92007-08-14 17:39:48 +0000967///
968/// Moreover, for all printf functions we can:
969///
970/// (3) Check for a missing format string (when not caught by type checking).
971///
972/// (4) Check for no-operation flags; e.g. using "#" with format
973/// conversion 'c' (TODO)
974///
975/// (5) Check the use of '%n', a major source of security holes.
976///
977/// (6) Check for malformed format conversions that don't specify anything.
978///
979/// (7) Check for empty format strings. e.g: printf("");
980///
981/// (8) Check that the format string is a wide literal.
982///
983/// All of these checks can be done by parsing the format string.
984///
Chris Lattner59907c42007-08-10 20:18:51 +0000985void
Mike Stump1eb44332009-09-09 15:08:12 +0000986Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000987 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000988 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000989
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000990 // The way the format attribute works in GCC, the implicit this argument
991 // of member functions is counted. However, it doesn't appear in our own
992 // lists, so decrement format_idx in that case.
993 if (isa<CXXMemberCallExpr>(TheCall)) {
994 // Catch a format attribute mistakenly referring to the object argument.
995 if (format_idx == 0)
996 return;
997 --format_idx;
998 if(firstDataArg != 0)
999 --firstDataArg;
1000 }
1001
Mike Stump1eb44332009-09-09 15:08:12 +00001002 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001003 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001004 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1005 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001006 return;
1007 }
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Ted Kremenek082d9362009-03-20 21:35:28 +00001009 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Chris Lattner59907c42007-08-10 20:18:51 +00001011 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001012 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001013 // Dynamically generated format strings are difficult to
1014 // automatically vet at compile time. Requiring that format strings
1015 // are string literals: (1) permits the checking of format strings by
1016 // the compiler and thereby (2) can practically remove the source of
1017 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001018
Mike Stump1eb44332009-09-09 15:08:12 +00001019 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001020 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001021 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001022 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001023 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1024 firstDataArg))
1025 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001026
Chris Lattner655f1412009-04-29 04:59:47 +00001027 // If there are no arguments specified, warn with -Wformat-security, otherwise
1028 // warn only with -Wformat-nonliteral.
1029 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001030 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001031 diag::warn_printf_nonliteral_noargs)
1032 << OrigFormatExpr->getSourceRange();
1033 else
Mike Stump1eb44332009-09-09 15:08:12 +00001034 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001035 diag::warn_printf_nonliteral)
1036 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001037}
Ted Kremenek71895b92007-08-14 17:39:48 +00001038
Ted Kremeneke0e53132010-01-28 23:39:18 +00001039namespace {
Ted Kremenek74d56a12010-02-04 20:46:58 +00001040class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001041 Sema &S;
1042 const StringLiteral *FExpr;
1043 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001044 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001045 const unsigned NumDataArgs;
1046 const bool IsObjCLiteral;
1047 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001048 const bool HasVAListArg;
1049 const CallExpr *TheCall;
1050 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001051 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001052 bool usesPositionalArgs;
1053 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001054public:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001055 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001056 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001057 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001058 const char *beg, bool hasVAListArg,
1059 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001060 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001061 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001062 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001063 IsObjCLiteral(isObjCLiteral), Beg(beg),
1064 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001065 TheCall(theCall), FormatIdx(formatIdx),
1066 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001067 CoveredArgs.resize(numDataArgs);
1068 CoveredArgs.reset();
1069 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001070
Ted Kremenek07d161f2010-01-29 01:50:07 +00001071 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001072
Ted Kremenek808015a2010-01-29 03:16:21 +00001073 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1074 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001075
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001076 bool
Ted Kremenek74d56a12010-02-04 20:46:58 +00001077 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1078 const char *startSpecifier,
1079 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001080
Ted Kremenekefaff192010-02-27 01:41:03 +00001081 virtual void HandleInvalidPosition(const char *startSpecifier,
1082 unsigned specifierLen,
1083 analyze_printf::PositionContext p);
1084
1085 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1086
Ted Kremeneke0e53132010-01-28 23:39:18 +00001087 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001088
Ted Kremeneke0e53132010-01-28 23:39:18 +00001089 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1090 const char *startSpecifier,
1091 unsigned specifierLen);
1092private:
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001093 SourceRange getFormatStringRange();
1094 SourceRange getFormatSpecifierRange(const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001095 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001096 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001097
Ted Kremenekefaff192010-02-27 01:41:03 +00001098 bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k,
1099 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001100 void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1101 llvm::StringRef flag, llvm::StringRef cspec,
1102 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001103
Ted Kremenek0d277352010-01-29 01:06:55 +00001104 const Expr *getDataArg(unsigned i) const;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001105};
1106}
1107
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001108SourceRange CheckPrintfHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001109 return OrigFormatExpr->getSourceRange();
1110}
1111
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001112SourceRange CheckPrintfHandler::
1113getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1114 return SourceRange(getLocationOfByte(startSpecifier),
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001115 getLocationOfByte(startSpecifier+specifierLen-1));
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001116}
1117
Ted Kremeneke0e53132010-01-28 23:39:18 +00001118SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001119 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001120}
1121
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001122void CheckPrintfHandler::
Ted Kremenek808015a2010-01-29 03:16:21 +00001123HandleIncompleteFormatSpecifier(const char *startSpecifier,
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001124 unsigned specifierLen) {
Ted Kremenek808015a2010-01-29 03:16:21 +00001125 SourceLocation Loc = getLocationOfByte(startSpecifier);
1126 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001127 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001128}
1129
Ted Kremenekefaff192010-02-27 01:41:03 +00001130void
1131CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1132 analyze_printf::PositionContext p) {
1133 SourceLocation Loc = getLocationOfByte(startPos);
1134 S.Diag(Loc, diag::warn_printf_invalid_positional_specifier)
1135 << (unsigned) p << getFormatSpecifierRange(startPos, posLen);
1136}
1137
1138void CheckPrintfHandler::HandleZeroPosition(const char *startPos,
1139 unsigned posLen) {
1140 SourceLocation Loc = getLocationOfByte(startPos);
1141 S.Diag(Loc, diag::warn_printf_zero_positional_specifier)
1142 << getFormatSpecifierRange(startPos, posLen);
1143}
1144
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001145bool CheckPrintfHandler::
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001146HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1147 const char *startSpecifier,
1148 unsigned specifierLen) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001149
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001150 unsigned argIndex = FS.getArgIndex();
1151 bool keepGoing = true;
1152 if (argIndex < NumDataArgs) {
1153 // Consider the argument coverered, even though the specifier doesn't
1154 // make sense.
1155 CoveredArgs.set(argIndex);
1156 }
1157 else {
1158 // If argIndex exceeds the number of data arguments we
1159 // don't issue a warning because that is just a cascade of warnings (and
1160 // they may have intended '%%' anyway). We don't want to continue processing
1161 // the format string after this point, however, as we will like just get
1162 // gibberish when trying to match arguments.
1163 keepGoing = false;
1164 }
1165
Ted Kremenek808015a2010-01-29 03:16:21 +00001166 const analyze_printf::ConversionSpecifier &CS =
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001167 FS.getConversionSpecifier();
Ted Kremenek808015a2010-01-29 03:16:21 +00001168 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001169 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenek808015a2010-01-29 03:16:21 +00001170 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001171 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001172
1173 return keepGoing;
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001174}
1175
Ted Kremeneke0e53132010-01-28 23:39:18 +00001176void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1177 // The presence of a null character is likely an error.
1178 S.Diag(getLocationOfByte(nullCharacter),
1179 diag::warn_printf_format_string_contains_null_char)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001180 << getFormatStringRange();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001181}
1182
Ted Kremenek0d277352010-01-29 01:06:55 +00001183const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001184 return TheCall->getArg(FirstDataArg + i);
Ted Kremenek0d277352010-01-29 01:06:55 +00001185}
1186
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001187void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1188 llvm::StringRef flag,
1189 llvm::StringRef cspec,
1190 const char *startSpecifier,
1191 unsigned specifierLen) {
1192 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1193 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1194 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1195}
1196
Ted Kremenek0d277352010-01-29 01:06:55 +00001197bool
1198CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
Ted Kremenekefaff192010-02-27 01:41:03 +00001199 unsigned k, const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001200 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001201
1202 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001203 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001204 unsigned argIndex = Amt.getArgIndex();
1205 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001206 S.Diag(getLocationOfByte(Amt.getStart()),
1207 diag::warn_printf_asterisk_missing_arg)
1208 << k << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001209 // Don't do any more checking. We will just emit
1210 // spurious errors.
1211 return false;
1212 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001213
Ted Kremenek0d277352010-01-29 01:06:55 +00001214 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001215 // Although not in conformance with C99, we also allow the argument to be
1216 // an 'unsigned int' as that is a reasonably safe case. GCC also
1217 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001218 CoveredArgs.set(argIndex);
1219 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001220 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001221
1222 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1223 assert(ATR.isValid());
1224
1225 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001226 S.Diag(getLocationOfByte(Amt.getStart()),
1227 diag::warn_printf_asterisk_wrong_type)
1228 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001229 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001230 << getFormatSpecifierRange(startSpecifier, specifierLen)
1231 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001232 // Don't do any more checking. We will just emit
1233 // spurious errors.
1234 return false;
1235 }
1236 }
1237 }
1238 return true;
1239}
Ted Kremenek0d277352010-01-29 01:06:55 +00001240
Ted Kremeneke0e53132010-01-28 23:39:18 +00001241bool
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001242CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1243 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001244 const char *startSpecifier,
1245 unsigned specifierLen) {
1246
Ted Kremenekefaff192010-02-27 01:41:03 +00001247 using namespace analyze_printf;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001248 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1249
Ted Kremenekefaff192010-02-27 01:41:03 +00001250 if (atFirstArg) {
1251 atFirstArg = false;
1252 usesPositionalArgs = FS.usesPositionalArg();
1253 }
1254 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1255 // Cannot mix-and-match positional and non-positional arguments.
1256 S.Diag(getLocationOfByte(CS.getStart()),
1257 diag::warn_printf_mix_positional_nonpositional_args)
1258 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001259 return false;
1260 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001261
Ted Kremenekefaff192010-02-27 01:41:03 +00001262 // First check if the field width, precision, and conversion specifier
1263 // have matching data arguments.
1264 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1265 startSpecifier, specifierLen)) {
1266 return false;
1267 }
1268
1269 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1270 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001271 return false;
1272 }
1273
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001274 if (!CS.consumesDataArgument()) {
1275 // FIXME: Technically specifying a precision or field width here
1276 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001277 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001278 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001279
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001280 // Consume the argument.
1281 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001282 if (argIndex < NumDataArgs) {
1283 // The check to see if the argIndex is valid will come later.
1284 // We set the bit here because we may exit early from this
1285 // function if we encounter some other error.
1286 CoveredArgs.set(argIndex);
1287 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001288
1289 // Check for using an Objective-C specific conversion specifier
1290 // in a non-ObjC literal.
1291 if (!IsObjCLiteral && CS.isObjCArg()) {
1292 return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1293 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001294
Ted Kremeneke82d8042010-01-29 01:35:25 +00001295 // Are we using '%n'? Issue a warning about this being
1296 // a possible security issue.
1297 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1298 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001299 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001300 // Continue checking the other format specifiers.
1301 return true;
1302 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001303
1304 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1305 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001306 S.Diag(getLocationOfByte(CS.getStart()),
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001307 diag::warn_printf_nonsensical_precision)
1308 << CS.getCharacters()
1309 << getFormatSpecifierRange(startSpecifier, specifierLen);
1310 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001311 if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1312 CS.getKind() == ConversionSpecifier::CStrArg) {
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001313 // FIXME: Instead of using "0", "+", etc., eventually get them from
1314 // the FormatSpecifier.
1315 if (FS.hasLeadingZeros())
1316 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1317 if (FS.hasPlusPrefix())
1318 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1319 if (FS.hasSpacePrefix())
1320 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001321 }
1322
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001323 // The remaining checks depend on the data arguments.
1324 if (HasVAListArg)
1325 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001326
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001327 if (argIndex >= NumDataArgs) {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001328 if (FS.usesPositionalArg()) {
1329 S.Diag(getLocationOfByte(CS.getStart()),
1330 diag::warn_printf_positional_arg_exceeds_data_args)
1331 << (argIndex+1) << NumDataArgs
1332 << getFormatSpecifierRange(startSpecifier, specifierLen);
1333 }
1334 else {
1335 S.Diag(getLocationOfByte(CS.getStart()),
1336 diag::warn_printf_insufficient_data_args)
1337 << getFormatSpecifierRange(startSpecifier, specifierLen);
1338 }
1339
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001340 // Don't do any more checking.
1341 return false;
1342 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001343
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001344 // Now type check the data expression that matches the
1345 // format specifier.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001346 const Expr *Ex = getDataArg(argIndex);
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001347 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001348 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1349 // Check if we didn't match because of an implicit cast from a 'char'
1350 // or 'short' to an 'int'. This is done because printf is a varargs
1351 // function.
1352 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1353 if (ICE->getType() == S.Context.IntTy)
1354 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1355 return true;
Ted Kremenek105d41c2010-02-01 19:38:10 +00001356
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001357 S.Diag(getLocationOfByte(CS.getStart()),
1358 diag::warn_printf_conversion_argument_type_mismatch)
1359 << ATR.getRepresentativeType(S.Context) << Ex->getType()
Ted Kremenek1497bff2010-02-11 19:37:25 +00001360 << getFormatSpecifierRange(startSpecifier, specifierLen)
1361 << Ex->getSourceRange();
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001362 }
Ted Kremeneke0e53132010-01-28 23:39:18 +00001363
1364 return true;
1365}
1366
Ted Kremenek07d161f2010-01-29 01:50:07 +00001367void CheckPrintfHandler::DoneProcessing() {
1368 // Does the number of data arguments exceed the number of
1369 // format conversions in the format string?
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001370 if (!HasVAListArg) {
1371 // Find any arguments that weren't covered.
1372 CoveredArgs.flip();
1373 signed notCoveredArg = CoveredArgs.find_first();
1374 if (notCoveredArg >= 0) {
1375 assert((unsigned)notCoveredArg < NumDataArgs);
1376 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1377 diag::warn_printf_data_arg_not_used)
1378 << getFormatStringRange();
1379 }
1380 }
Ted Kremenek07d161f2010-01-29 01:50:07 +00001381}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001382
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001383void Sema::CheckPrintfString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001384 const Expr *OrigFormatExpr,
1385 const CallExpr *TheCall, bool HasVAListArg,
1386 unsigned format_idx, unsigned firstDataArg) {
1387
Ted Kremeneke0e53132010-01-28 23:39:18 +00001388 // CHECK: is the format string a wide literal?
1389 if (FExpr->isWide()) {
1390 Diag(FExpr->getLocStart(),
1391 diag::warn_printf_format_string_is_wide_literal)
1392 << OrigFormatExpr->getSourceRange();
1393 return;
1394 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001395
Ted Kremeneke0e53132010-01-28 23:39:18 +00001396 // Str - The format string. NOTE: this is NOT null-terminated!
1397 const char *Str = FExpr->getStrData();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001398
Ted Kremeneke0e53132010-01-28 23:39:18 +00001399 // CHECK: empty format string?
1400 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001401
Ted Kremeneke0e53132010-01-28 23:39:18 +00001402 if (StrLen == 0) {
1403 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1404 << OrigFormatExpr->getSourceRange();
1405 return;
1406 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001407
Ted Kremenek6ee76532010-03-25 03:59:12 +00001408 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001409 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek0d277352010-01-29 01:06:55 +00001410 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1411 HasVAListArg, TheCall, format_idx);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001412
Ted Kremenek74d56a12010-02-04 20:46:58 +00001413 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
Ted Kremenek808015a2010-01-29 03:16:21 +00001414 H.DoneProcessing();
Ted Kremenekce7024e2010-01-28 01:18:22 +00001415}
1416
Ted Kremenek06de2762007-08-17 16:46:58 +00001417//===--- CHECK: Return Address of Stack Variable --------------------------===//
1418
1419static DeclRefExpr* EvalVal(Expr *E);
1420static DeclRefExpr* EvalAddr(Expr* E);
1421
1422/// CheckReturnStackAddr - Check if a return statement returns the address
1423/// of a stack variable.
1424void
1425Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1426 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Ted Kremenek06de2762007-08-17 16:46:58 +00001428 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001429 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001430 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001431 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001432 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Steve Naroffc50a4a52008-09-16 22:25:10 +00001434 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001435 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001436
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001437 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001438 if (C->hasBlockDeclRefExprs())
1439 Diag(C->getLocStart(), diag::err_ret_local_block)
1440 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001441
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001442 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1443 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1444 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001445
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001446 } else if (lhsType->isReferenceType()) {
1447 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001448 // Check for a reference to the stack
1449 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001450 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001451 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001452 }
1453}
1454
1455/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1456/// check if the expression in a return statement evaluates to an address
1457/// to a location on the stack. The recursion is used to traverse the
1458/// AST of the return expression, with recursion backtracking when we
1459/// encounter a subexpression that (1) clearly does not lead to the address
1460/// of a stack variable or (2) is something we cannot determine leads to
1461/// the address of a stack variable based on such local checking.
1462///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001463/// EvalAddr processes expressions that are pointers that are used as
1464/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001465/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001466/// the refers to a stack variable.
1467///
1468/// This implementation handles:
1469///
1470/// * pointer-to-pointer casts
1471/// * implicit conversions from array references to pointers
1472/// * taking the address of fields
1473/// * arbitrary interplay between "&" and "*" operators
1474/// * pointer arithmetic from an address of a stack variable
1475/// * taking the address of an array element where the array is on the stack
1476static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001477 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001478 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001479 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001480 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001481 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Ted Kremenek06de2762007-08-17 16:46:58 +00001483 // Our "symbolic interpreter" is just a dispatch off the currently
1484 // viewed AST node. We then recursively traverse the AST by calling
1485 // EvalAddr and EvalVal appropriately.
1486 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001487 case Stmt::ParenExprClass:
1488 // Ignore parentheses.
1489 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001490
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001491 case Stmt::UnaryOperatorClass: {
1492 // The only unary operator that make sense to handle here
1493 // is AddrOf. All others don't make sense as pointers.
1494 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001496 if (U->getOpcode() == UnaryOperator::AddrOf)
1497 return EvalVal(U->getSubExpr());
1498 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001499 return NULL;
1500 }
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001502 case Stmt::BinaryOperatorClass: {
1503 // Handle pointer arithmetic. All other binary operators are not valid
1504 // in this context.
1505 BinaryOperator *B = cast<BinaryOperator>(E);
1506 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001508 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1509 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001511 Expr *Base = B->getLHS();
1512
1513 // Determine which argument is the real pointer base. It could be
1514 // the RHS argument instead of the LHS.
1515 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001517 assert (Base->getType()->isPointerType());
1518 return EvalAddr(Base);
1519 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001520
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001521 // For conditional operators we need to see if either the LHS or RHS are
1522 // valid DeclRefExpr*s. If one of them is valid, we return it.
1523 case Stmt::ConditionalOperatorClass: {
1524 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001526 // Handle the GNU extension for missing LHS.
1527 if (Expr *lhsExpr = C->getLHS())
1528 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1529 return LHS;
1530
1531 return EvalAddr(C->getRHS());
1532 }
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Ted Kremenek54b52742008-08-07 00:49:01 +00001534 // For casts, we need to handle conversions from arrays to
1535 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001536 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001537 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001538 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001539 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001540 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001541
Steve Naroffdd972f22008-09-05 22:11:13 +00001542 if (SubExpr->getType()->isPointerType() ||
1543 SubExpr->getType()->isBlockPointerType() ||
1544 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001545 return EvalAddr(SubExpr);
1546 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001547 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001548 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001549 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001550 }
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001552 // C++ casts. For dynamic casts, static casts, and const casts, we
1553 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001554 // through the cast. In the case the dynamic cast doesn't fail (and
1555 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001556 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001557 // FIXME: The comment about is wrong; we're not always converting
1558 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001559 // handle references to objects.
1560 case Stmt::CXXStaticCastExprClass:
1561 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001562 case Stmt::CXXConstCastExprClass:
1563 case Stmt::CXXReinterpretCastExprClass: {
1564 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001565 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001566 return EvalAddr(S);
1567 else
1568 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001569 }
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001571 // Everything else: we simply don't reason about them.
1572 default:
1573 return NULL;
1574 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001575}
Mike Stump1eb44332009-09-09 15:08:12 +00001576
Ted Kremenek06de2762007-08-17 16:46:58 +00001577
1578/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1579/// See the comments for EvalAddr for more details.
1580static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001582 // We should only be called for evaluating non-pointer expressions, or
1583 // expressions with a pointer type that are not used as references but instead
1584 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Ted Kremenek06de2762007-08-17 16:46:58 +00001586 // Our "symbolic interpreter" is just a dispatch off the currently
1587 // viewed AST node. We then recursively traverse the AST by calling
1588 // EvalAddr and EvalVal appropriately.
1589 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001590 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001591 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1592 // at code that refers to a variable's name. We check if it has local
1593 // storage within the function, and if so, return the expression.
1594 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Ted Kremenek06de2762007-08-17 16:46:58 +00001596 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001597 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1598
Ted Kremenek06de2762007-08-17 16:46:58 +00001599 return NULL;
1600 }
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Ted Kremenek06de2762007-08-17 16:46:58 +00001602 case Stmt::ParenExprClass:
1603 // Ignore parentheses.
1604 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Ted Kremenek06de2762007-08-17 16:46:58 +00001606 case Stmt::UnaryOperatorClass: {
1607 // The only unary operator that make sense to handle here
1608 // is Deref. All others don't resolve to a "name." This includes
1609 // handling all sorts of rvalues passed to a unary operator.
1610 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Ted Kremenek06de2762007-08-17 16:46:58 +00001612 if (U->getOpcode() == UnaryOperator::Deref)
1613 return EvalAddr(U->getSubExpr());
1614
1615 return NULL;
1616 }
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Ted Kremenek06de2762007-08-17 16:46:58 +00001618 case Stmt::ArraySubscriptExprClass: {
1619 // Array subscripts are potential references to data on the stack. We
1620 // retrieve the DeclRefExpr* for the array variable if it indeed
1621 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001622 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001623 }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Ted Kremenek06de2762007-08-17 16:46:58 +00001625 case Stmt::ConditionalOperatorClass: {
1626 // For conditional operators we need to see if either the LHS or RHS are
1627 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1628 ConditionalOperator *C = cast<ConditionalOperator>(E);
1629
Anders Carlsson39073232007-11-30 19:04:31 +00001630 // Handle the GNU extension for missing LHS.
1631 if (Expr *lhsExpr = C->getLHS())
1632 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1633 return LHS;
1634
1635 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001636 }
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Ted Kremenek06de2762007-08-17 16:46:58 +00001638 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001639 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001640 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Ted Kremenek06de2762007-08-17 16:46:58 +00001642 // Check for indirect access. We only want direct field accesses.
1643 if (!M->isArrow())
1644 return EvalVal(M->getBase());
1645 else
1646 return NULL;
1647 }
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Ted Kremenek06de2762007-08-17 16:46:58 +00001649 // Everything else: we simply don't reason about them.
1650 default:
1651 return NULL;
1652 }
1653}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001654
1655//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1656
1657/// Check for comparisons of floating point operands using != and ==.
1658/// Issue a warning if these are no self-comparisons, as they are not likely
1659/// to do what the programmer intended.
1660void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1661 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001663 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001664 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001665
1666 // Special case: check for x == x (which is OK).
1667 // Do not emit warnings for such cases.
1668 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1669 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1670 if (DRL->getDecl() == DRR->getDecl())
1671 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001672
1673
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001674 // Special case: check for comparisons against literals that can be exactly
1675 // represented by APFloat. In such cases, do not emit a warning. This
1676 // is a heuristic: often comparison against such literals are used to
1677 // detect if a value in a variable has not changed. This clearly can
1678 // lead to false negatives.
1679 if (EmitWarning) {
1680 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1681 if (FLL->isExact())
1682 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001683 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001684 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1685 if (FLR->isExact())
1686 EmitWarning = false;
1687 }
1688 }
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001690 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001691 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001692 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001693 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001694 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Sebastian Redl0eb23302009-01-19 00:08:26 +00001696 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001697 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001698 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001699 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001701 // Emit the diagnostic.
1702 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001703 Diag(loc, diag::warn_floatingpoint_eq)
1704 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001705}
John McCallba26e582010-01-04 23:21:16 +00001706
John McCallf2370c92010-01-06 05:24:50 +00001707//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1708//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00001709
John McCallf2370c92010-01-06 05:24:50 +00001710namespace {
John McCallba26e582010-01-04 23:21:16 +00001711
John McCallf2370c92010-01-06 05:24:50 +00001712/// Structure recording the 'active' range of an integer-valued
1713/// expression.
1714struct IntRange {
1715 /// The number of bits active in the int.
1716 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00001717
John McCallf2370c92010-01-06 05:24:50 +00001718 /// True if the int is known not to have negative values.
1719 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00001720
John McCallf2370c92010-01-06 05:24:50 +00001721 IntRange() {}
1722 IntRange(unsigned Width, bool NonNegative)
1723 : Width(Width), NonNegative(NonNegative)
1724 {}
John McCallba26e582010-01-04 23:21:16 +00001725
John McCallf2370c92010-01-06 05:24:50 +00001726 // Returns the range of the bool type.
1727 static IntRange forBoolType() {
1728 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00001729 }
1730
John McCallf2370c92010-01-06 05:24:50 +00001731 // Returns the range of an integral type.
1732 static IntRange forType(ASTContext &C, QualType T) {
1733 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00001734 }
1735
John McCallf2370c92010-01-06 05:24:50 +00001736 // Returns the range of an integeral type based on its canonical
1737 // representation.
1738 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1739 assert(T->isCanonicalUnqualified());
1740
1741 if (const VectorType *VT = dyn_cast<VectorType>(T))
1742 T = VT->getElementType().getTypePtr();
1743 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1744 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00001745
1746 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
1747 EnumDecl *Enum = ET->getDecl();
1748 unsigned NumPositive = Enum->getNumPositiveBits();
1749 unsigned NumNegative = Enum->getNumNegativeBits();
1750
1751 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
1752 }
John McCallf2370c92010-01-06 05:24:50 +00001753
1754 const BuiltinType *BT = cast<BuiltinType>(T);
1755 assert(BT->isInteger());
1756
1757 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1758 }
1759
1760 // Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001761 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00001762 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00001763 L.NonNegative && R.NonNegative);
1764 }
1765
1766 // Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001767 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00001768 return IntRange(std::min(L.Width, R.Width),
1769 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00001770 }
1771};
1772
1773IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1774 if (value.isSigned() && value.isNegative())
1775 return IntRange(value.getMinSignedBits(), false);
1776
1777 if (value.getBitWidth() > MaxWidth)
1778 value.trunc(MaxWidth);
1779
1780 // isNonNegative() just checks the sign bit without considering
1781 // signedness.
1782 return IntRange(value.getActiveBits(), true);
1783}
1784
John McCall0acc3112010-01-06 22:57:21 +00001785IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00001786 unsigned MaxWidth) {
1787 if (result.isInt())
1788 return GetValueRange(C, result.getInt(), MaxWidth);
1789
1790 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00001791 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1792 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1793 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1794 R = IntRange::join(R, El);
1795 }
John McCallf2370c92010-01-06 05:24:50 +00001796 return R;
1797 }
1798
1799 if (result.isComplexInt()) {
1800 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1801 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1802 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00001803 }
1804
1805 // This can happen with lossless casts to intptr_t of "based" lvalues.
1806 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00001807 // FIXME: The only reason we need to pass the type in here is to get
1808 // the sign right on this one case. It would be nice if APValue
1809 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00001810 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00001811 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00001812}
John McCallf2370c92010-01-06 05:24:50 +00001813
1814/// Pseudo-evaluate the given integer expression, estimating the
1815/// range of values it might take.
1816///
1817/// \param MaxWidth - the width to which the value will be truncated
1818IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1819 E = E->IgnoreParens();
1820
1821 // Try a full evaluation first.
1822 Expr::EvalResult result;
1823 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00001824 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00001825
1826 // I think we only want to look through implicit casts here; if the
1827 // user has an explicit widening cast, we should treat the value as
1828 // being of the new, wider type.
1829 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1830 if (CE->getCastKind() == CastExpr::CK_NoOp)
1831 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1832
1833 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1834
John McCall60fad452010-01-06 22:07:33 +00001835 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1836 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1837 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1838
John McCallf2370c92010-01-06 05:24:50 +00001839 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00001840 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00001841 return OutputTypeRange;
1842
1843 IntRange SubRange
1844 = GetExprRange(C, CE->getSubExpr(),
1845 std::min(MaxWidth, OutputTypeRange.Width));
1846
1847 // Bail out if the subexpr's range is as wide as the cast type.
1848 if (SubRange.Width >= OutputTypeRange.Width)
1849 return OutputTypeRange;
1850
1851 // Otherwise, we take the smaller width, and we're non-negative if
1852 // either the output type or the subexpr is.
1853 return IntRange(SubRange.Width,
1854 SubRange.NonNegative || OutputTypeRange.NonNegative);
1855 }
1856
1857 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1858 // If we can fold the condition, just take that operand.
1859 bool CondResult;
1860 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1861 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1862 : CO->getFalseExpr(),
1863 MaxWidth);
1864
1865 // Otherwise, conservatively merge.
1866 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1867 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1868 return IntRange::join(L, R);
1869 }
1870
1871 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1872 switch (BO->getOpcode()) {
1873
1874 // Boolean-valued operations are single-bit and positive.
1875 case BinaryOperator::LAnd:
1876 case BinaryOperator::LOr:
1877 case BinaryOperator::LT:
1878 case BinaryOperator::GT:
1879 case BinaryOperator::LE:
1880 case BinaryOperator::GE:
1881 case BinaryOperator::EQ:
1882 case BinaryOperator::NE:
1883 return IntRange::forBoolType();
1884
John McCallc0cd21d2010-02-23 19:22:29 +00001885 // The type of these compound assignments is the type of the LHS,
1886 // so the RHS is not necessarily an integer.
1887 case BinaryOperator::MulAssign:
1888 case BinaryOperator::DivAssign:
1889 case BinaryOperator::RemAssign:
1890 case BinaryOperator::AddAssign:
1891 case BinaryOperator::SubAssign:
1892 return IntRange::forType(C, E->getType());
1893
John McCallf2370c92010-01-06 05:24:50 +00001894 // Operations with opaque sources are black-listed.
1895 case BinaryOperator::PtrMemD:
1896 case BinaryOperator::PtrMemI:
1897 return IntRange::forType(C, E->getType());
1898
John McCall60fad452010-01-06 22:07:33 +00001899 // Bitwise-and uses the *infinum* of the two source ranges.
1900 case BinaryOperator::And:
John McCallc0cd21d2010-02-23 19:22:29 +00001901 case BinaryOperator::AndAssign:
John McCall60fad452010-01-06 22:07:33 +00001902 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1903 GetExprRange(C, BO->getRHS(), MaxWidth));
1904
John McCallf2370c92010-01-06 05:24:50 +00001905 // Left shift gets black-listed based on a judgement call.
1906 case BinaryOperator::Shl:
John McCall3aae6092010-04-07 01:14:35 +00001907 // ...except that we want to treat '1 << (blah)' as logically
1908 // positive. It's an important idiom.
1909 if (IntegerLiteral *I
1910 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
1911 if (I->getValue() == 1) {
1912 IntRange R = IntRange::forType(C, E->getType());
1913 return IntRange(R.Width, /*NonNegative*/ true);
1914 }
1915 }
1916 // fallthrough
1917
John McCallc0cd21d2010-02-23 19:22:29 +00001918 case BinaryOperator::ShlAssign:
John McCallf2370c92010-01-06 05:24:50 +00001919 return IntRange::forType(C, E->getType());
1920
John McCall60fad452010-01-06 22:07:33 +00001921 // Right shift by a constant can narrow its left argument.
John McCallc0cd21d2010-02-23 19:22:29 +00001922 case BinaryOperator::Shr:
1923 case BinaryOperator::ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00001924 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1925
1926 // If the shift amount is a positive constant, drop the width by
1927 // that much.
1928 llvm::APSInt shift;
1929 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1930 shift.isNonNegative()) {
1931 unsigned zext = shift.getZExtValue();
1932 if (zext >= L.Width)
1933 L.Width = (L.NonNegative ? 0 : 1);
1934 else
1935 L.Width -= zext;
1936 }
1937
1938 return L;
1939 }
1940
1941 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00001942 case BinaryOperator::Comma:
1943 return GetExprRange(C, BO->getRHS(), MaxWidth);
1944
John McCall60fad452010-01-06 22:07:33 +00001945 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00001946 case BinaryOperator::Sub:
1947 if (BO->getLHS()->getType()->isPointerType())
1948 return IntRange::forType(C, E->getType());
1949 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001950
John McCallf2370c92010-01-06 05:24:50 +00001951 default:
1952 break;
1953 }
1954
1955 // Treat every other operator as if it were closed on the
1956 // narrowest type that encompasses both operands.
1957 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1958 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1959 return IntRange::join(L, R);
1960 }
1961
1962 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1963 switch (UO->getOpcode()) {
1964 // Boolean-valued operations are white-listed.
1965 case UnaryOperator::LNot:
1966 return IntRange::forBoolType();
1967
1968 // Operations with opaque sources are black-listed.
1969 case UnaryOperator::Deref:
1970 case UnaryOperator::AddrOf: // should be impossible
1971 case UnaryOperator::OffsetOf:
1972 return IntRange::forType(C, E->getType());
1973
1974 default:
1975 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1976 }
1977 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001978
1979 if (dyn_cast<OffsetOfExpr>(E)) {
1980 IntRange::forType(C, E->getType());
1981 }
John McCallf2370c92010-01-06 05:24:50 +00001982
1983 FieldDecl *BitField = E->getBitField();
1984 if (BitField) {
1985 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1986 unsigned BitWidth = BitWidthAP.getZExtValue();
1987
1988 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1989 }
1990
1991 return IntRange::forType(C, E->getType());
1992}
John McCall51313c32010-01-04 23:31:57 +00001993
John McCall323ed742010-05-06 08:58:33 +00001994IntRange GetExprRange(ASTContext &C, Expr *E) {
1995 return GetExprRange(C, E, C.getIntWidth(E->getType()));
1996}
1997
John McCall51313c32010-01-04 23:31:57 +00001998/// Checks whether the given value, which currently has the given
1999/// source semantics, has the same value when coerced through the
2000/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002001bool IsSameFloatAfterCast(const llvm::APFloat &value,
2002 const llvm::fltSemantics &Src,
2003 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002004 llvm::APFloat truncated = value;
2005
2006 bool ignored;
2007 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2008 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2009
2010 return truncated.bitwiseIsEqual(value);
2011}
2012
2013/// Checks whether the given value, which currently has the given
2014/// source semantics, has the same value when coerced through the
2015/// target semantics.
2016///
2017/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002018bool IsSameFloatAfterCast(const APValue &value,
2019 const llvm::fltSemantics &Src,
2020 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002021 if (value.isFloat())
2022 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2023
2024 if (value.isVector()) {
2025 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2026 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2027 return false;
2028 return true;
2029 }
2030
2031 assert(value.isComplexFloat());
2032 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2033 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2034}
2035
John McCall323ed742010-05-06 08:58:33 +00002036void AnalyzeImplicitConversions(Sema &S, Expr *E);
2037
2038bool IsZero(Sema &S, Expr *E) {
2039 llvm::APSInt Value;
2040 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2041}
2042
2043void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
2044 BinaryOperator::Opcode op = E->getOpcode();
2045 if (op == BinaryOperator::LT && IsZero(S, E->getRHS())) {
2046 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2047 << "< 0" << "false"
2048 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2049 } else if (op == BinaryOperator::GE && IsZero(S, E->getRHS())) {
2050 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2051 << ">= 0" << "true"
2052 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2053 } else if (op == BinaryOperator::GT && IsZero(S, E->getLHS())) {
2054 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2055 << "0 >" << "false"
2056 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2057 } else if (op == BinaryOperator::LE && IsZero(S, E->getLHS())) {
2058 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2059 << "0 <=" << "true"
2060 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2061 }
2062}
2063
2064/// Analyze the operands of the given comparison. Implements the
2065/// fallback case from AnalyzeComparison.
2066void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
2067 AnalyzeImplicitConversions(S, E->getLHS());
2068 AnalyzeImplicitConversions(S, E->getRHS());
2069}
John McCall51313c32010-01-04 23:31:57 +00002070
John McCallba26e582010-01-04 23:21:16 +00002071/// \brief Implements -Wsign-compare.
2072///
2073/// \param lex the left-hand expression
2074/// \param rex the right-hand expression
2075/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002076/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002077void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2078 // The type the comparison is being performed in.
2079 QualType T = E->getLHS()->getType();
2080 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2081 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002082
John McCall323ed742010-05-06 08:58:33 +00002083 // We don't do anything special if this isn't an unsigned integral
2084 // comparison: we're only interested in integral comparisons, and
2085 // signed comparisons only happen in cases we don't care to warn about.
2086 if (!T->isUnsignedIntegerType())
2087 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002088
John McCall323ed742010-05-06 08:58:33 +00002089 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2090 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002091
John McCall323ed742010-05-06 08:58:33 +00002092 // Check to see if one of the (unmodified) operands is of different
2093 // signedness.
2094 Expr *signedOperand, *unsignedOperand;
2095 if (lex->getType()->isSignedIntegerType()) {
2096 assert(!rex->getType()->isSignedIntegerType() &&
2097 "unsigned comparison between two signed integer expressions?");
2098 signedOperand = lex;
2099 unsignedOperand = rex;
2100 } else if (rex->getType()->isSignedIntegerType()) {
2101 signedOperand = rex;
2102 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002103 } else {
John McCall323ed742010-05-06 08:58:33 +00002104 CheckTrivialUnsignedComparison(S, E);
2105 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002106 }
2107
John McCall323ed742010-05-06 08:58:33 +00002108 // Otherwise, calculate the effective range of the signed operand.
2109 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002110
John McCall323ed742010-05-06 08:58:33 +00002111 // Go ahead and analyze implicit conversions in the operands. Note
2112 // that we skip the implicit conversions on both sides.
2113 AnalyzeImplicitConversions(S, lex);
2114 AnalyzeImplicitConversions(S, rex);
John McCallba26e582010-01-04 23:21:16 +00002115
John McCall323ed742010-05-06 08:58:33 +00002116 // If the signed range is non-negative, -Wsign-compare won't fire,
2117 // but we should still check for comparisons which are always true
2118 // or false.
2119 if (signedRange.NonNegative)
2120 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002121
2122 // For (in)equality comparisons, if the unsigned operand is a
2123 // constant which cannot collide with a overflowed signed operand,
2124 // then reinterpreting the signed operand as unsigned will not
2125 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002126 if (E->isEqualityOp()) {
2127 unsigned comparisonWidth = S.Context.getIntWidth(T);
2128 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002129
John McCall323ed742010-05-06 08:58:33 +00002130 // We should never be unable to prove that the unsigned operand is
2131 // non-negative.
2132 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2133
2134 if (unsignedRange.Width < comparisonWidth)
2135 return;
2136 }
2137
2138 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2139 << lex->getType() << rex->getType()
2140 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002141}
2142
John McCall51313c32010-01-04 23:31:57 +00002143/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCall323ed742010-05-06 08:58:33 +00002144void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
John McCall51313c32010-01-04 23:31:57 +00002145 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2146}
2147
John McCall323ed742010-05-06 08:58:33 +00002148void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
2149 bool *ICContext = 0) {
2150 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002151
John McCall323ed742010-05-06 08:58:33 +00002152 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2153 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2154 if (Source == Target) return;
2155 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002156
2157 // Never diagnose implicit casts to bool.
2158 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2159 return;
2160
2161 // Strip vector types.
2162 if (isa<VectorType>(Source)) {
2163 if (!isa<VectorType>(Target))
John McCall323ed742010-05-06 08:58:33 +00002164 return DiagnoseImpCast(S, E, T, diag::warn_impcast_vector_scalar);
John McCall51313c32010-01-04 23:31:57 +00002165
2166 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2167 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2168 }
2169
2170 // Strip complex types.
2171 if (isa<ComplexType>(Source)) {
2172 if (!isa<ComplexType>(Target))
John McCall323ed742010-05-06 08:58:33 +00002173 return DiagnoseImpCast(S, E, T, diag::warn_impcast_complex_scalar);
John McCall51313c32010-01-04 23:31:57 +00002174
2175 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2176 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2177 }
2178
2179 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2180 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2181
2182 // If the source is floating point...
2183 if (SourceBT && SourceBT->isFloatingPoint()) {
2184 // ...and the target is floating point...
2185 if (TargetBT && TargetBT->isFloatingPoint()) {
2186 // ...then warn if we're dropping FP rank.
2187
2188 // Builtin FP kinds are ordered by increasing FP rank.
2189 if (SourceBT->getKind() > TargetBT->getKind()) {
2190 // Don't warn about float constants that are precisely
2191 // representable in the target type.
2192 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002193 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002194 // Value might be a float, a float vector, or a float complex.
2195 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002196 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2197 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002198 return;
2199 }
2200
John McCall323ed742010-05-06 08:58:33 +00002201 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002202 }
2203 return;
2204 }
2205
2206 // If the target is integral, always warn.
2207 if ((TargetBT && TargetBT->isInteger()))
2208 // TODO: don't warn for integer values?
John McCall323ed742010-05-06 08:58:33 +00002209 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_integer);
John McCall51313c32010-01-04 23:31:57 +00002210
2211 return;
2212 }
2213
John McCallf2370c92010-01-06 05:24:50 +00002214 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002215 return;
2216
John McCall323ed742010-05-06 08:58:33 +00002217 IntRange SourceRange = GetExprRange(S.Context, E);
2218 IntRange TargetRange = IntRange::forCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002219
2220 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002221 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2222 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002223 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall323ed742010-05-06 08:58:33 +00002224 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_64_32);
2225 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_precision);
2226 }
2227
2228 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2229 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2230 SourceRange.Width == TargetRange.Width)) {
2231 unsigned DiagID = diag::warn_impcast_integer_sign;
2232
2233 // Traditionally, gcc has warned about this under -Wsign-compare.
2234 // We also want to warn about it in -Wconversion.
2235 // So if -Wconversion is off, use a completely identical diagnostic
2236 // in the sign-compare group.
2237 // The conditional-checking code will
2238 if (ICContext) {
2239 DiagID = diag::warn_impcast_integer_sign_conditional;
2240 *ICContext = true;
2241 }
2242
2243 return DiagnoseImpCast(S, E, T, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002244 }
2245
2246 return;
2247}
2248
John McCall323ed742010-05-06 08:58:33 +00002249void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2250
2251void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
2252 bool &ICContext) {
2253 E = E->IgnoreParenImpCasts();
2254
2255 if (isa<ConditionalOperator>(E))
2256 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2257
2258 AnalyzeImplicitConversions(S, E);
2259 if (E->getType() != T)
2260 return CheckImplicitConversion(S, E, T, &ICContext);
2261 return;
2262}
2263
2264void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
2265 AnalyzeImplicitConversions(S, E->getCond());
2266
2267 bool Suspicious = false;
2268 CheckConditionalOperand(S, E->getTrueExpr(), T, Suspicious);
2269 CheckConditionalOperand(S, E->getFalseExpr(), T, Suspicious);
2270
2271 // If -Wconversion would have warned about either of the candidates
2272 // for a signedness conversion to the context type...
2273 if (!Suspicious) return;
2274
2275 // ...but it's currently ignored...
2276 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional))
2277 return;
2278
2279 // ...and -Wsign-compare isn't...
2280 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional))
2281 return;
2282
2283 // ...then check whether it would have warned about either of the
2284 // candidates for a signedness conversion to the condition type.
2285 if (E->getType() != T) {
2286 Suspicious = false;
2287 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
2288 E->getType(), &Suspicious);
2289 if (!Suspicious)
2290 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
2291 E->getType(), &Suspicious);
2292 if (!Suspicious)
2293 return;
2294 }
2295
2296 // If so, emit a diagnostic under -Wsign-compare.
2297 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2298 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2299 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2300 << lex->getType() << rex->getType()
2301 << lex->getSourceRange() << rex->getSourceRange();
2302}
2303
2304/// AnalyzeImplicitConversions - Find and report any interesting
2305/// implicit conversions in the given expression. There are a couple
2306/// of competing diagnostics here, -Wconversion and -Wsign-compare.
2307void AnalyzeImplicitConversions(Sema &S, Expr *OrigE) {
2308 QualType T = OrigE->getType();
2309 Expr *E = OrigE->IgnoreParenImpCasts();
2310
2311 // For conditional operators, we analyze the arguments as if they
2312 // were being fed directly into the output.
2313 if (isa<ConditionalOperator>(E)) {
2314 ConditionalOperator *CO = cast<ConditionalOperator>(E);
2315 CheckConditionalOperator(S, CO, T);
2316 return;
2317 }
2318
2319 // Go ahead and check any implicit conversions we might have skipped.
2320 // The non-canonical typecheck is just an optimization;
2321 // CheckImplicitConversion will filter out dead implicit conversions.
2322 if (E->getType() != T)
2323 CheckImplicitConversion(S, E, T);
2324
2325 // Now continue drilling into this expression.
2326
2327 // Skip past explicit casts.
2328 if (isa<ExplicitCastExpr>(E)) {
2329 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
2330 return AnalyzeImplicitConversions(S, E);
2331 }
2332
2333 // Do a somewhat different check with comparison operators.
2334 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isComparisonOp())
2335 return AnalyzeComparison(S, cast<BinaryOperator>(E));
2336
2337 // These break the otherwise-useful invariant below. Fortunately,
2338 // we don't really need to recurse into them, because any internal
2339 // expressions should have been analyzed already when they were
2340 // built into statements.
2341 if (isa<StmtExpr>(E)) return;
2342
2343 // Don't descend into unevaluated contexts.
2344 if (isa<SizeOfAlignOfExpr>(E)) return;
2345
2346 // Now just recurse over the expression's children.
2347 for (Stmt::child_iterator I = E->child_begin(), IE = E->child_end();
2348 I != IE; ++I)
2349 AnalyzeImplicitConversions(S, cast<Expr>(*I));
2350}
2351
2352} // end anonymous namespace
2353
2354/// Diagnoses "dangerous" implicit conversions within the given
2355/// expression (which is a full expression). Implements -Wconversion
2356/// and -Wsign-compare.
2357void Sema::CheckImplicitConversions(Expr *E) {
2358 // Don't diagnose in unevaluated contexts.
2359 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2360 return;
2361
2362 // Don't diagnose for value- or type-dependent expressions.
2363 if (E->isTypeDependent() || E->isValueDependent())
2364 return;
2365
2366 AnalyzeImplicitConversions(*this, E);
2367}
2368
Mike Stumpf8c49212010-01-21 03:59:47 +00002369/// CheckParmsForFunctionDef - Check that the parameters of the given
2370/// function are appropriate for the definition of a function. This
2371/// takes care of any checks that cannot be performed on the
2372/// declaration itself, e.g., that the types of each of the function
2373/// parameters are complete.
2374bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2375 bool HasInvalidParm = false;
2376 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2377 ParmVarDecl *Param = FD->getParamDecl(p);
2378
2379 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2380 // function declarator that is part of a function definition of
2381 // that function shall not have incomplete type.
2382 //
2383 // This is also C++ [dcl.fct]p6.
2384 if (!Param->isInvalidDecl() &&
2385 RequireCompleteType(Param->getLocation(), Param->getType(),
2386 diag::err_typecheck_decl_incomplete_type)) {
2387 Param->setInvalidDecl();
2388 HasInvalidParm = true;
2389 }
2390
2391 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2392 // declaration of each parameter shall include an identifier.
2393 if (Param->getIdentifier() == 0 &&
2394 !Param->isImplicit() &&
2395 !getLangOptions().CPlusPlus)
2396 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002397
2398 // C99 6.7.5.3p12:
2399 // If the function declarator is not part of a definition of that
2400 // function, parameters may have incomplete type and may use the [*]
2401 // notation in their sequences of declarator specifiers to specify
2402 // variable length array types.
2403 QualType PType = Param->getOriginalType();
2404 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2405 if (AT->getSizeModifier() == ArrayType::Star) {
2406 // FIXME: This diagnosic should point the the '[*]' if source-location
2407 // information is added for it.
2408 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2409 }
2410 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002411 }
2412
2413 return HasInvalidParm;
2414}