blob: 3617f546e0891892d2f5dfed03cd24640b169314 [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"
Mike Stumpf8c49212010-01-21 03:59:47 +000016#include "clang/Analysis/CFG.h"
Ted Kremenek1309f9a2010-01-25 04:41:41 +000017#include "clang/Analysis/AnalysisContext.h"
Ted Kremeneke0e53132010-01-28 23:39:18 +000018#include "clang/Analysis/Analyses/PrintfFormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000019#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000020#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/DeclObjC.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000027#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000028#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000029#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/STLExtras.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000031#include <limits>
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include <queue>
Chris Lattner59907c42007-08-10 20:18:51 +000033using namespace clang;
34
Chris Lattner60800082009-02-18 17:49:48 +000035/// getLocationOfStringLiteralByte - Return a source location that points to the
36/// specified byte of the specified string literal.
37///
38/// Strings are amazingly complex. They can be formed from multiple tokens and
39/// can have escape sequences in them in addition to the usual trigraph and
40/// escaped newline business. This routine handles this complexity.
41///
42SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
44 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000045
Chris Lattner60800082009-02-18 17:49:48 +000046 // Loop over all of the tokens in this string until we find the one that
47 // contains the byte we're looking for.
48 unsigned TokNo = 0;
49 while (1) {
50 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
51 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000052
Chris Lattner60800082009-02-18 17:49:48 +000053 // Get the spelling of the string so that we can get the data that makes up
54 // the string literal, not the identifier for the macro it is potentially
55 // expanded through.
56 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
57
58 // Re-lex the token to get its length and original spelling.
59 std::pair<FileID, unsigned> LocInfo =
60 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
61 std::pair<const char *,const char *> Buffer =
62 SourceMgr.getBufferData(LocInfo.first);
63 const char *StrData = Buffer.first+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000064
Chris Lattner60800082009-02-18 17:49:48 +000065 // Create a langops struct and enable trigraphs. This is sufficient for
66 // relexing tokens.
67 LangOptions LangOpts;
68 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner60800082009-02-18 17:49:48 +000070 // Create a lexer starting at the beginning of this token.
71 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
72 Buffer.second);
73 Token TheTok;
74 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner443e53c2009-02-18 19:26:42 +000076 // Use the StringLiteralParser to compute the length of the string in bytes.
77 StringLiteralParser SLP(&TheTok, 1, PP);
78 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000079
Chris Lattner2197c962009-02-18 18:52:52 +000080 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000081 if (ByteNo < TokNumBytes ||
82 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000083 unsigned Offset =
Chris Lattner719e6152009-02-18 19:21:10 +000084 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
Mike Stump1eb44332009-09-09 15:08:12 +000085
Chris Lattner719e6152009-02-18 19:21:10 +000086 // Now that we know the offset of the token in the spelling, use the
87 // preprocessor to get the offset in the original source.
88 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000089 }
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattner60800082009-02-18 17:49:48 +000091 // Move to the next string token.
92 ++TokNo;
93 ByteNo -= TokNumBytes;
94 }
95}
96
Ryan Flynn4403a5e2009-08-06 03:00:50 +000097/// CheckablePrintfAttr - does a function call have a "printf" attribute
98/// and arguments that merit checking?
99bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
100 if (Format->getType() == "printf") return true;
101 if (Format->getType() == "printf0") {
102 // printf0 allows null "format" string; if so don't check format/args
103 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000104 // Does the index refer to the implicit object argument?
105 if (isa<CXXMemberCallExpr>(TheCall)) {
106 if (format_idx == 0)
107 return false;
108 --format_idx;
109 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000110 if (format_idx < TheCall->getNumArgs()) {
111 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Douglas Gregorce940492009-09-25 04:25:58 +0000112 if (!Format->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000113 return true;
114 }
115 }
116 return false;
117}
Chris Lattner60800082009-02-18 17:49:48 +0000118
Sebastian Redl0eb23302009-01-19 00:08:26 +0000119Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000120Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000121 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000122
Anders Carlssond406bf02009-08-16 01:56:34 +0000123 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000124 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000125 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000126 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000127 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000128 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000129 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000130 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000131 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 if (SemaBuiltinVAStart(TheCall))
133 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000134 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000135 case Builtin::BI__builtin_isgreater:
136 case Builtin::BI__builtin_isgreaterequal:
137 case Builtin::BI__builtin_isless:
138 case Builtin::BI__builtin_islessequal:
139 case Builtin::BI__builtin_islessgreater:
140 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000141 if (SemaBuiltinUnorderedCompare(TheCall))
142 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000143 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000144 case Builtin::BI__builtin_fpclassify:
145 if (SemaBuiltinFPClassification(TheCall, 6))
146 return ExprError();
147 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000148 case Builtin::BI__builtin_isfinite:
149 case Builtin::BI__builtin_isinf:
150 case Builtin::BI__builtin_isinf_sign:
151 case Builtin::BI__builtin_isnan:
152 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000153 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000154 return ExprError();
155 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000156 case Builtin::BI__builtin_return_address:
157 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000158 if (SemaBuiltinStackAddress(TheCall))
159 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000160 break;
Chris Lattner21fb98e2009-09-23 06:06:36 +0000161 case Builtin::BI__builtin_eh_return_data_regno:
162 if (SemaBuiltinEHReturnDataRegNo(TheCall))
163 return ExprError();
164 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000165 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000166 return SemaBuiltinShuffleVector(TheCall);
167 // TheCall will be freed by the smart pointer here, but that's fine, since
168 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000169 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 if (SemaBuiltinPrefetch(TheCall))
171 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000172 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000173 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000174 if (SemaBuiltinObjectSize(TheCall))
175 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000176 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000177 case Builtin::BI__builtin_longjmp:
178 if (SemaBuiltinLongjmp(TheCall))
179 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000180 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000181 case Builtin::BI__sync_fetch_and_add:
182 case Builtin::BI__sync_fetch_and_sub:
183 case Builtin::BI__sync_fetch_and_or:
184 case Builtin::BI__sync_fetch_and_and:
185 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000186 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000187 case Builtin::BI__sync_add_and_fetch:
188 case Builtin::BI__sync_sub_and_fetch:
189 case Builtin::BI__sync_and_and_fetch:
190 case Builtin::BI__sync_or_and_fetch:
191 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000192 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000193 case Builtin::BI__sync_val_compare_and_swap:
194 case Builtin::BI__sync_bool_compare_and_swap:
195 case Builtin::BI__sync_lock_test_and_set:
196 case Builtin::BI__sync_lock_release:
197 if (SemaBuiltinAtomicOverloaded(TheCall))
198 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000199 break;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000200 }
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Anders Carlssond406bf02009-08-16 01:56:34 +0000202 return move(TheCallResult);
203}
Daniel Dunbarde454282008-10-02 18:44:07 +0000204
Anders Carlssond406bf02009-08-16 01:56:34 +0000205/// CheckFunctionCall - Check a direct function call for various correctness
206/// and safety properties not strictly enforced by the C type system.
207bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
208 // Get the IdentifierInfo* for the called function.
209 IdentifierInfo *FnInfo = FDecl->getIdentifier();
210
211 // None of the checks below are needed for functions that don't have
212 // simple names (e.g., C++ conversion functions).
213 if (!FnInfo)
214 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000215
Daniel Dunbarde454282008-10-02 18:44:07 +0000216 // FIXME: This mechanism should be abstracted to be less fragile and
217 // more efficient. For example, just map function ids to custom
218 // handlers.
219
Chris Lattner59907c42007-08-10 20:18:51 +0000220 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000221 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000222 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000223 bool HasVAListArg = Format->getFirstArg() == 0;
224 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000225 if (const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +0000226 = FDecl->getType()->getAs<FunctionProtoType>())
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000227 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000228 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000229 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000230 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000231 }
Chris Lattner59907c42007-08-10 20:18:51 +0000232 }
Mike Stump1eb44332009-09-09 15:08:12 +0000233
234 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000235 NonNull = NonNull->getNext<NonNullAttr>())
236 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000237
Anders Carlssond406bf02009-08-16 01:56:34 +0000238 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000239}
240
Anders Carlssond406bf02009-08-16 01:56:34 +0000241bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000242 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000243 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000244 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000245 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000247 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
248 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000249 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000251 QualType Ty = V->getType();
252 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000253 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Anders Carlssond406bf02009-08-16 01:56:34 +0000255 if (!CheckablePrintfAttr(Format, TheCall))
256 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Anders Carlssond406bf02009-08-16 01:56:34 +0000258 bool HasVAListArg = Format->getFirstArg() == 0;
259 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000260 const FunctionType *FT =
John McCall183700f2009-09-21 23:43:11 +0000261 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Anders Carlssond406bf02009-08-16 01:56:34 +0000262 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
263 HasVAListArg = !Proto->isVariadic();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000264 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000265 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
266 HasVAListArg ? 0 : Format->getFirstArg() - 1);
267
268 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000269}
270
Chris Lattner5caa3702009-05-08 06:58:22 +0000271/// SemaBuiltinAtomicOverloaded - We have a call to a function like
272/// __sync_fetch_and_add, which is an overloaded function based on the pointer
273/// type of its first argument. The main ActOnCallExpr routines have already
274/// promoted the types of arguments because all of these calls are prototyped as
275/// void(...).
276///
277/// This function goes through and does final semantic checking for these
278/// builtins,
279bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
280 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
281 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
282
283 // Ensure that we have at least one argument to do type inference from.
284 if (TheCall->getNumArgs() < 1)
285 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
286 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Chris Lattner5caa3702009-05-08 06:58:22 +0000288 // Inspect the first argument of the atomic builtin. This should always be
289 // a pointer type, whose element is an integral scalar or pointer type.
290 // Because it is a pointer type, we don't have to worry about any implicit
291 // casts here.
292 Expr *FirstArg = TheCall->getArg(0);
293 if (!FirstArg->getType()->isPointerType())
294 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
295 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Ted Kremenek6217b802009-07-29 21:53:49 +0000297 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000298 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000299 !ValType->isBlockPointerType())
300 return Diag(DRE->getLocStart(),
301 diag::err_atomic_builtin_must_be_pointer_intptr)
302 << FirstArg->getType() << FirstArg->getSourceRange();
303
304 // We need to figure out which concrete builtin this maps onto. For example,
305 // __sync_fetch_and_add with a 2 byte object turns into
306 // __sync_fetch_and_add_2.
307#define BUILTIN_ROW(x) \
308 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
309 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Chris Lattner5caa3702009-05-08 06:58:22 +0000311 static const unsigned BuiltinIndices[][5] = {
312 BUILTIN_ROW(__sync_fetch_and_add),
313 BUILTIN_ROW(__sync_fetch_and_sub),
314 BUILTIN_ROW(__sync_fetch_and_or),
315 BUILTIN_ROW(__sync_fetch_and_and),
316 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000317 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chris Lattner5caa3702009-05-08 06:58:22 +0000319 BUILTIN_ROW(__sync_add_and_fetch),
320 BUILTIN_ROW(__sync_sub_and_fetch),
321 BUILTIN_ROW(__sync_and_and_fetch),
322 BUILTIN_ROW(__sync_or_and_fetch),
323 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000324 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Chris Lattner5caa3702009-05-08 06:58:22 +0000326 BUILTIN_ROW(__sync_val_compare_and_swap),
327 BUILTIN_ROW(__sync_bool_compare_and_swap),
328 BUILTIN_ROW(__sync_lock_test_and_set),
329 BUILTIN_ROW(__sync_lock_release)
330 };
Mike Stump1eb44332009-09-09 15:08:12 +0000331#undef BUILTIN_ROW
332
Chris Lattner5caa3702009-05-08 06:58:22 +0000333 // Determine the index of the size.
334 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000335 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000336 case 1: SizeIndex = 0; break;
337 case 2: SizeIndex = 1; break;
338 case 4: SizeIndex = 2; break;
339 case 8: SizeIndex = 3; break;
340 case 16: SizeIndex = 4; break;
341 default:
342 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
343 << FirstArg->getType() << FirstArg->getSourceRange();
344 }
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Chris Lattner5caa3702009-05-08 06:58:22 +0000346 // Each of these builtins has one pointer argument, followed by some number of
347 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
348 // that we ignore. Find out which row of BuiltinIndices to read from as well
349 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000350 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000351 unsigned BuiltinIndex, NumFixed = 1;
352 switch (BuiltinID) {
353 default: assert(0 && "Unknown overloaded atomic builtin!");
354 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
355 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
356 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
357 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
358 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000359 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Chris Lattnereebd9d22009-05-13 04:37:52 +0000361 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
362 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
363 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
364 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
365 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
366 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Chris Lattner5caa3702009-05-08 06:58:22 +0000368 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000369 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000370 NumFixed = 2;
371 break;
372 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000373 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000374 NumFixed = 2;
375 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000376 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000377 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000378 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000379 NumFixed = 0;
380 break;
381 }
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Chris Lattner5caa3702009-05-08 06:58:22 +0000383 // Now that we know how many fixed arguments we expect, first check that we
384 // have at least that many.
385 if (TheCall->getNumArgs() < 1+NumFixed)
386 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
387 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000388
389
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000390 // Get the decl for the concrete builtin from this, we can tell what the
391 // concrete integer type we should convert to is.
392 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
393 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
394 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000395 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000396 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
397 TUScope, false, DRE->getLocStart()));
398 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000399 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000400 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000402 // If the first type needs to be converted (e.g. void** -> int*), do it now.
403 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000404 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000405 TheCall->setArg(0, FirstArg);
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner5caa3702009-05-08 06:58:22 +0000408 // Next, walk the valid ones promoting to the right type.
409 for (unsigned i = 0; i != NumFixed; ++i) {
410 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Chris Lattner5caa3702009-05-08 06:58:22 +0000412 // If the argument is an implicit cast, then there was a promotion due to
413 // "...", just remove it now.
414 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
415 Arg = ICE->getSubExpr();
416 ICE->setSubExpr(0);
417 ICE->Destroy(Context);
418 TheCall->setArg(i+1, Arg);
419 }
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Chris Lattner5caa3702009-05-08 06:58:22 +0000421 // GCC does an implicit conversion to the pointer or integer ValType. This
422 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000423 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000424 CXXMethodDecl *ConversionDecl = 0;
425 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
426 ConversionDecl))
Chris Lattner5caa3702009-05-08 06:58:22 +0000427 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Chris Lattner5caa3702009-05-08 06:58:22 +0000429 // Okay, we have something that *can* be converted to the right type. Check
430 // to see if there is a potentially weird extension going on here. This can
431 // happen when you do an atomic operation on something like an char* and
432 // pass in 42. The 42 gets converted to char. This is even more strange
433 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000434 // FIXME: Do this check.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000435 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000436 TheCall->setArg(i+1, Arg);
437 }
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattner5caa3702009-05-08 06:58:22 +0000439 // Switch the DeclRefExpr to refer to the new decl.
440 DRE->setDecl(NewBuiltinDecl);
441 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Chris Lattner5caa3702009-05-08 06:58:22 +0000443 // Set the callee in the CallExpr.
444 // FIXME: This leaks the original parens and implicit casts.
445 Expr *PromotedCall = DRE;
446 UsualUnaryConversions(PromotedCall);
447 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Chris Lattner5caa3702009-05-08 06:58:22 +0000449
450 // Change the result type of the call to match the result type of the decl.
451 TheCall->setType(NewBuiltinDecl->getResultType());
452 return false;
453}
454
455
Chris Lattner69039812009-02-18 06:01:06 +0000456/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000457/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000458/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000459/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000460/// belong to the input codeset UTF-8"
461/// Note: It might also make sense to do the UTF-16 conversion here (would
462/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000463bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000464 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000465 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
466
467 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000468 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
469 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000470 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Daniel Dunbarf015b032009-09-22 10:03:52 +0000473 const char *Data = Literal->getStrData();
474 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Daniel Dunbarf015b032009-09-22 10:03:52 +0000476 for (unsigned i = 0; i < Length; ++i) {
477 if (!Data[i]) {
478 Diag(getLocationOfStringLiteralByte(Literal, i),
479 diag::warn_cfstring_literal_contains_nul_character)
480 << Arg->getSourceRange();
481 break;
482 }
483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000485 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000486}
487
Chris Lattnerc27c6652007-12-20 00:05:45 +0000488/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
489/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000490bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
491 Expr *Fn = TheCall->getCallee();
492 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000493 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000494 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000495 << 0 /*function call*/ << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000496 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000497 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000498 return true;
499 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000500
501 if (TheCall->getNumArgs() < 2) {
502 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
503 << 0 /*function call*/;
504 }
505
Chris Lattnerc27c6652007-12-20 00:05:45 +0000506 // Determine whether the current function is variadic or not.
507 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000508 if (CurBlock)
509 isVariadic = CurBlock->isVariadic;
510 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000511 if (FunctionProtoType* FTP =
512 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000513 isVariadic = FTP->isVariadic();
514 else
515 isVariadic = false;
516 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000517 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000518 }
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)
556 << 0 /*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)
Chris Lattner2c21a072008-11-21 18:44:24 +0000560 << 0 /*function call*/
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)
598 << 0 /*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)
602 << 0 /*function call*/
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
611 // This operation requires a floating-point number
612 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
Eli Friedman9ac6f622009-08-31 20:06:00 +0000617 return false;
618}
619
Eli Friedman6cfda232008-05-20 08:23:37 +0000620bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
621 // The signature for these builtins is exact; the only thing we need
622 // to check is that the argument is a constant.
623 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000624 if (!TheCall->getArg(0)->isTypeDependent() &&
625 !TheCall->getArg(0)->isValueDependent() &&
626 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000627 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000628
Eli Friedman6cfda232008-05-20 08:23:37 +0000629 return false;
630}
631
Eli Friedmand38617c2008-05-14 19:38:39 +0000632/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
633// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000634Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000635 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000636 return ExprError(Diag(TheCall->getLocEnd(),
637 diag::err_typecheck_call_too_few_args)
638 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000639
Douglas Gregorcde01732009-05-19 22:10:17 +0000640 unsigned numElements = std::numeric_limits<unsigned>::max();
641 if (!TheCall->getArg(0)->isTypeDependent() &&
642 !TheCall->getArg(1)->isTypeDependent()) {
643 QualType FAType = TheCall->getArg(0)->getType();
644 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000645
Douglas Gregorcde01732009-05-19 22:10:17 +0000646 if (!FAType->isVectorType() || !SAType->isVectorType()) {
647 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000648 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000649 TheCall->getArg(1)->getLocEnd());
650 return ExprError();
651 }
Mike Stump1eb44332009-09-09 15:08:12 +0000652
Douglas Gregora4923eb2009-11-16 21:35:15 +0000653 if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000654 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000655 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000656 TheCall->getArg(1)->getLocEnd());
657 return ExprError();
658 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000659
John McCall183700f2009-09-21 23:43:11 +0000660 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorcde01732009-05-19 22:10:17 +0000661 if (TheCall->getNumArgs() != numElements+2) {
662 if (TheCall->getNumArgs() < numElements+2)
663 return ExprError(Diag(TheCall->getLocEnd(),
664 diag::err_typecheck_call_too_few_args)
665 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000666 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000667 diag::err_typecheck_call_too_many_args)
668 << 0 /*function call*/ << TheCall->getSourceRange());
669 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000670 }
671
672 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000673 if (TheCall->getArg(i)->isTypeDependent() ||
674 TheCall->getArg(i)->isValueDependent())
675 continue;
676
Eli Friedmand38617c2008-05-14 19:38:39 +0000677 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000678 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000679 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000680 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000681 << TheCall->getArg(i)->getSourceRange());
682
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000683 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000684 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000685 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000686 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000687 }
688
689 llvm::SmallVector<Expr*, 32> exprs;
690
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000691 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000692 exprs.push_back(TheCall->getArg(i));
693 TheCall->setArg(i, 0);
694 }
695
Nate Begemana88dc302009-08-12 02:10:25 +0000696 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
697 exprs.size(), exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000698 TheCall->getCallee()->getLocStart(),
699 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000700}
Chris Lattner30ce3442007-12-19 23:59:04 +0000701
Daniel Dunbar4493f792008-07-21 22:59:13 +0000702/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
703// This is declared to take (const void*, ...) and can take two
704// optional constant int args.
705bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000706 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000707
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000708 if (NumArgs > 3)
709 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000710 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000711
712 // Argument 0 is checked for us and the remaining arguments must be
713 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000714 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000715 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000716 if (Arg->isTypeDependent())
717 continue;
718
Eli Friedman9aef7262009-12-04 00:30:06 +0000719 if (!Arg->getType()->isIntegralType())
720 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000721 << Arg->getSourceRange();
Douglas Gregorcde01732009-05-19 22:10:17 +0000722
Eli Friedman9aef7262009-12-04 00:30:06 +0000723 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast);
724 TheCall->setArg(i, Arg);
725
Douglas Gregorcde01732009-05-19 22:10:17 +0000726 if (Arg->isValueDependent())
727 continue;
728
Eli Friedman9aef7262009-12-04 00:30:06 +0000729 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000730 if (!Arg->isIntegerConstantExpr(Result, Context))
Eli Friedman9aef7262009-12-04 00:30:06 +0000731 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice)
Douglas Gregorcde01732009-05-19 22:10:17 +0000732 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Daniel Dunbar4493f792008-07-21 22:59:13 +0000734 // FIXME: gcc issues a warning and rewrites these to 0. These
735 // seems especially odd for the third argument since the default
736 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000737 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000738 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000739 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000740 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000741 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000742 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000743 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000744 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000745 }
746 }
747
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000748 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000749}
750
Chris Lattner21fb98e2009-09-23 06:06:36 +0000751/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
752/// operand must be an integer constant.
753bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
754 llvm::APSInt Result;
755 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
756 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
757 << TheCall->getArg(0)->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000758
Chris Lattner21fb98e2009-09-23 06:06:36 +0000759 return false;
760}
761
762
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000763/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
764/// int type). This simply type checks that type is one of the defined
765/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000766// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000767bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
768 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000769 if (Arg->isTypeDependent())
770 return false;
771
Mike Stump1eb44332009-09-09 15:08:12 +0000772 QualType ArgType = Arg->getType();
John McCall183700f2009-09-21 23:43:11 +0000773 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000774 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000775 if (!BT || BT->getKind() != BuiltinType::Int)
776 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
777 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
778
779 if (Arg->isValueDependent())
780 return false;
781
782 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000783 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
784 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000785 }
786
787 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000788 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
789 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000790 }
791
792 return false;
793}
794
Eli Friedman586d6a82009-05-03 06:04:26 +0000795/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000796/// This checks that val is a constant 1.
797bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
798 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000799 if (Arg->isTypeDependent() || Arg->isValueDependent())
800 return false;
801
Eli Friedmand875fed2009-05-03 04:46:36 +0000802 llvm::APSInt Result(32);
803 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
804 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
805 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
806
807 return false;
808}
809
Ted Kremenekd30ef872009-01-12 23:09:09 +0000810// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000811bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
812 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000813 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000814 if (E->isTypeDependent() || E->isValueDependent())
815 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000816
817 switch (E->getStmtClass()) {
818 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000819 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000820 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000821 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000822 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000823 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000824 }
825
826 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000827 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000828 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000829 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000830 }
831
832 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000833 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000834 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000835 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000836 }
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Ted Kremenek082d9362009-03-20 21:35:28 +0000838 case Stmt::DeclRefExprClass: {
839 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Ted Kremenek082d9362009-03-20 21:35:28 +0000841 // As an exception, do not flag errors for variables binding to
842 // const string literals.
843 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
844 bool isConstant = false;
845 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000846
Ted Kremenek082d9362009-03-20 21:35:28 +0000847 if (const ArrayType *AT = Context.getAsArrayType(T)) {
848 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000849 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000850 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000851 PT->getPointeeType().isConstant(Context);
852 }
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Ted Kremenek082d9362009-03-20 21:35:28 +0000854 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000855 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000856 return SemaCheckStringLiteral(Init, TheCall,
857 HasVAListArg, format_idx, firstDataArg);
858 }
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Anders Carlssond966a552009-06-28 19:55:58 +0000860 // For vprintf* functions (i.e., HasVAListArg==true), we add a
861 // special check to see if the format string is a function parameter
862 // of the function calling the printf function. If the function
863 // has an attribute indicating it is a printf-like function, then we
864 // should suppress warnings concerning non-literals being used in a call
865 // to a vprintf function. For example:
866 //
867 // void
868 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
869 // va_list ap;
870 // va_start(ap, fmt);
871 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
872 // ...
873 //
874 //
875 // FIXME: We don't have full attribute support yet, so just check to see
876 // if the argument is a DeclRefExpr that references a parameter. We'll
877 // add proper support for checking the attribute later.
878 if (HasVAListArg)
879 if (isa<ParmVarDecl>(VD))
880 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000881 }
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Ted Kremenek082d9362009-03-20 21:35:28 +0000883 return false;
884 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000885
Anders Carlsson8f031b32009-06-27 04:05:33 +0000886 case Stmt::CallExprClass: {
887 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000888 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000889 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
890 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
891 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000892 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000893 unsigned ArgIndex = FA->getFormatIdx();
894 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000895
896 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000897 format_idx, firstDataArg);
898 }
899 }
900 }
901 }
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Anders Carlsson8f031b32009-06-27 04:05:33 +0000903 return false;
904 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000905 case Stmt::ObjCStringLiteralClass:
906 case Stmt::StringLiteralClass: {
907 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Ted Kremenek082d9362009-03-20 21:35:28 +0000909 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000910 StrE = ObjCFExpr->getString();
911 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000912 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Ted Kremenekd30ef872009-01-12 23:09:09 +0000914 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000915 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000916 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000917 return true;
918 }
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Ted Kremenekd30ef872009-01-12 23:09:09 +0000920 return false;
921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Ted Kremenek082d9362009-03-20 21:35:28 +0000923 default:
924 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000925 }
926}
927
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000928void
Mike Stump1eb44332009-09-09 15:08:12 +0000929Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
930 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000931 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
932 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000933 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000934 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +0000935 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000936 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
937 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000938 }
939}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000940
Chris Lattner59907c42007-08-10 20:18:51 +0000941/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000942/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000943///
944/// HasVAListArg - A predicate indicating whether the printf-like
945/// function is passed an explicit va_arg argument (e.g., vprintf)
946///
947/// format_idx - The index into Args for the format string.
948///
949/// Improper format strings to functions in the printf family can be
950/// the source of bizarre bugs and very serious security holes. A
951/// good source of information is available in the following paper
952/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000953///
954/// FormatGuard: Automatic Protection From printf Format String
955/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000956///
957/// Functionality implemented:
958///
959/// We can statically check the following properties for string
960/// literal format strings for non v.*printf functions (where the
961/// arguments are passed directly):
962//
963/// (1) Are the number of format conversions equal to the number of
964/// data arguments?
965///
966/// (2) Does each format conversion correctly match the type of the
967/// corresponding data argument? (TODO)
968///
969/// Moreover, for all printf functions we can:
970///
971/// (3) Check for a missing format string (when not caught by type checking).
972///
973/// (4) Check for no-operation flags; e.g. using "#" with format
974/// conversion 'c' (TODO)
975///
976/// (5) Check the use of '%n', a major source of security holes.
977///
978/// (6) Check for malformed format conversions that don't specify anything.
979///
980/// (7) Check for empty format strings. e.g: printf("");
981///
982/// (8) Check that the format string is a wide literal.
983///
984/// All of these checks can be done by parsing the format string.
985///
986/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000987void
Mike Stump1eb44332009-09-09 15:08:12 +0000988Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000989 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000990 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000991
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000992 // The way the format attribute works in GCC, the implicit this argument
993 // of member functions is counted. However, it doesn't appear in our own
994 // lists, so decrement format_idx in that case.
995 if (isa<CXXMemberCallExpr>(TheCall)) {
996 // Catch a format attribute mistakenly referring to the object argument.
997 if (format_idx == 0)
998 return;
999 --format_idx;
1000 if(firstDataArg != 0)
1001 --firstDataArg;
1002 }
1003
Mike Stump1eb44332009-09-09 15:08:12 +00001004 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001005 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001006 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1007 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001008 return;
1009 }
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Ted Kremenek082d9362009-03-20 21:35:28 +00001011 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Chris Lattner59907c42007-08-10 20:18:51 +00001013 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001014 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001015 // Dynamically generated format strings are difficult to
1016 // automatically vet at compile time. Requiring that format strings
1017 // are string literals: (1) permits the checking of format strings by
1018 // the compiler and thereby (2) can practically remove the source of
1019 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001020
Mike Stump1eb44332009-09-09 15:08:12 +00001021 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001022 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001023 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001024 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001025 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1026 firstDataArg))
1027 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001028
Chris Lattner655f1412009-04-29 04:59:47 +00001029 // If there are no arguments specified, warn with -Wformat-security, otherwise
1030 // warn only with -Wformat-nonliteral.
1031 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001032 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001033 diag::warn_printf_nonliteral_noargs)
1034 << OrigFormatExpr->getSourceRange();
1035 else
Mike Stump1eb44332009-09-09 15:08:12 +00001036 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001037 diag::warn_printf_nonliteral)
1038 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001039}
Ted Kremenek71895b92007-08-14 17:39:48 +00001040
Ted Kremeneke0e53132010-01-28 23:39:18 +00001041namespace {
Ted Kremenek74d56a12010-02-04 20:46:58 +00001042class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001043 Sema &S;
1044 const StringLiteral *FExpr;
1045 const Expr *OrigFormatExpr;
1046 unsigned NumConversions;
1047 const unsigned NumDataArgs;
1048 const bool IsObjCLiteral;
1049 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001050 const bool HasVAListArg;
1051 const CallExpr *TheCall;
1052 unsigned FormatIdx;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001053public:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001054 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1055 const Expr *origFormatExpr,
1056 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001057 const char *beg, bool hasVAListArg,
1058 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001059 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1060 NumConversions(0), NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001061 IsObjCLiteral(isObjCLiteral), Beg(beg),
1062 HasVAListArg(hasVAListArg),
1063 TheCall(theCall), FormatIdx(formatIdx) {}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001064
Ted Kremenek07d161f2010-01-29 01:50:07 +00001065 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001066
Ted Kremenek808015a2010-01-29 03:16:21 +00001067 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1068 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001069
Ted Kremenek74d56a12010-02-04 20:46:58 +00001070 void
1071 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1072 const char *startSpecifier,
1073 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001074
Ted Kremeneke0e53132010-01-28 23:39:18 +00001075 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001076
Ted Kremeneke0e53132010-01-28 23:39:18 +00001077 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1078 const char *startSpecifier,
1079 unsigned specifierLen);
1080private:
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001081 SourceRange getFormatStringRange();
1082 SourceRange getFormatSpecifierRange(const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001083 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001084 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001085
Ted Kremenek0d277352010-01-29 01:06:55 +00001086 bool HandleAmount(const analyze_printf::OptionalAmount &Amt,
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001087 unsigned MissingArgDiag, unsigned BadTypeDiag,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001088 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001089 void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1090 llvm::StringRef flag, llvm::StringRef cspec,
1091 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001092
Ted Kremenek0d277352010-01-29 01:06:55 +00001093 const Expr *getDataArg(unsigned i) const;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001094};
1095}
1096
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001097SourceRange CheckPrintfHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001098 return OrigFormatExpr->getSourceRange();
1099}
1100
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001101SourceRange CheckPrintfHandler::
1102getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1103 return SourceRange(getLocationOfByte(startSpecifier),
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001104 getLocationOfByte(startSpecifier+specifierLen-1));
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001105}
1106
Ted Kremeneke0e53132010-01-28 23:39:18 +00001107SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001108 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001109}
1110
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001111void CheckPrintfHandler::
Ted Kremenek808015a2010-01-29 03:16:21 +00001112HandleIncompleteFormatSpecifier(const char *startSpecifier,
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001113 unsigned specifierLen) {
Ted Kremenek808015a2010-01-29 03:16:21 +00001114 SourceLocation Loc = getLocationOfByte(startSpecifier);
1115 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001116 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001117}
1118
1119void CheckPrintfHandler::
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001120HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1121 const char *startSpecifier,
1122 unsigned specifierLen) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001123
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001124 ++NumConversions;
Ted Kremenek808015a2010-01-29 03:16:21 +00001125 const analyze_printf::ConversionSpecifier &CS =
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001126 FS.getConversionSpecifier();
Ted Kremenek808015a2010-01-29 03:16:21 +00001127 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001128 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenek808015a2010-01-29 03:16:21 +00001129 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001130 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001131}
1132
Ted Kremeneke0e53132010-01-28 23:39:18 +00001133void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1134 // The presence of a null character is likely an error.
1135 S.Diag(getLocationOfByte(nullCharacter),
1136 diag::warn_printf_format_string_contains_null_char)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001137 << getFormatStringRange();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001138}
1139
Ted Kremenek0d277352010-01-29 01:06:55 +00001140const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001141 return TheCall->getArg(FormatIdx + i);
Ted Kremenek0d277352010-01-29 01:06:55 +00001142}
1143
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001144
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001145
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001146void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1147 llvm::StringRef flag,
1148 llvm::StringRef cspec,
1149 const char *startSpecifier,
1150 unsigned specifierLen) {
1151 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1152 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1153 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1154}
1155
Ted Kremenek0d277352010-01-29 01:06:55 +00001156bool
1157CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
1158 unsigned MissingArgDiag,
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001159 unsigned BadTypeDiag,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001160 const char *startSpecifier,
1161 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001162
1163 if (Amt.hasDataArgument()) {
1164 ++NumConversions;
1165 if (!HasVAListArg) {
1166 if (NumConversions > NumDataArgs) {
1167 S.Diag(getLocationOfByte(Amt.getStart()), MissingArgDiag)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001168 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001169 // Don't do any more checking. We will just emit
1170 // spurious errors.
1171 return false;
1172 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001173
Ted Kremenek0d277352010-01-29 01:06:55 +00001174 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001175 // Although not in conformance with C99, we also allow the argument to be
1176 // an 'unsigned int' as that is a reasonably safe case. GCC also
1177 // doesn't emit a warning for that case.
Ted Kremenek0d277352010-01-29 01:06:55 +00001178 const Expr *Arg = getDataArg(NumConversions);
1179 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001180
1181 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1182 assert(ATR.isValid());
1183
1184 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001185 S.Diag(getLocationOfByte(Amt.getStart()), BadTypeDiag)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001186 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001187 << getFormatSpecifierRange(startSpecifier, specifierLen)
1188 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001189 // Don't do any more checking. We will just emit
1190 // spurious errors.
1191 return false;
1192 }
1193 }
1194 }
1195 return true;
1196}
Ted Kremenek0d277352010-01-29 01:06:55 +00001197
Ted Kremeneke0e53132010-01-28 23:39:18 +00001198bool
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001199CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1200 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001201 const char *startSpecifier,
1202 unsigned specifierLen) {
1203
1204 using namespace analyze_printf;
1205 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1206
Ted Kremenek0d277352010-01-29 01:06:55 +00001207 // First check if the field width, precision, and conversion specifier
1208 // have matching data arguments.
1209 if (!HandleAmount(FS.getFieldWidth(),
1210 diag::warn_printf_asterisk_width_missing_arg,
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001211 diag::warn_printf_asterisk_width_wrong_type,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001212 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001213 return false;
1214 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001215
Ted Kremenek0d277352010-01-29 01:06:55 +00001216 if (!HandleAmount(FS.getPrecision(),
1217 diag::warn_printf_asterisk_precision_missing_arg,
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001218 diag::warn_printf_asterisk_precision_wrong_type,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001219 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001220 return false;
1221 }
1222
Ted Kremeneke0e53132010-01-28 23:39:18 +00001223 // Check for using an Objective-C specific conversion specifier
1224 // in a non-ObjC literal.
1225 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001226 HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001227
Ted Kremeneke0e53132010-01-28 23:39:18 +00001228 // Continue checking the other format specifiers.
1229 return true;
1230 }
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001231
1232 if (!CS.consumesDataArgument()) {
1233 // FIXME: Technically specifying a precision or field width here
1234 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001235 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001236 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001237
1238 ++NumConversions;
1239
Ted Kremeneke82d8042010-01-29 01:35:25 +00001240 // Are we using '%n'? Issue a warning about this being
1241 // a possible security issue.
1242 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1243 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001244 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001245 // Continue checking the other format specifiers.
1246 return true;
1247 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001248
1249 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1250 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001251 S.Diag(getLocationOfByte(CS.getStart()),
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001252 diag::warn_printf_nonsensical_precision)
1253 << CS.getCharacters()
1254 << getFormatSpecifierRange(startSpecifier, specifierLen);
1255 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001256 if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1257 CS.getKind() == ConversionSpecifier::CStrArg) {
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001258 // FIXME: Instead of using "0", "+", etc., eventually get them from
1259 // the FormatSpecifier.
1260 if (FS.hasLeadingZeros())
1261 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1262 if (FS.hasPlusPrefix())
1263 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1264 if (FS.hasSpacePrefix())
1265 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001266 }
1267
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001268 // The remaining checks depend on the data arguments.
1269 if (HasVAListArg)
1270 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001271
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001272 if (NumConversions > NumDataArgs) {
1273 S.Diag(getLocationOfByte(CS.getStart()),
1274 diag::warn_printf_insufficient_data_args)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001275 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001276 // Don't do any more checking.
1277 return false;
1278 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001279
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001280 // Now type check the data expression that matches the
1281 // format specifier.
1282 const Expr *Ex = getDataArg(NumConversions);
1283 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001284 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1285 // Check if we didn't match because of an implicit cast from a 'char'
1286 // or 'short' to an 'int'. This is done because printf is a varargs
1287 // function.
1288 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1289 if (ICE->getType() == S.Context.IntTy)
1290 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1291 return true;
Ted Kremenek105d41c2010-02-01 19:38:10 +00001292
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001293 S.Diag(getLocationOfByte(CS.getStart()),
1294 diag::warn_printf_conversion_argument_type_mismatch)
1295 << ATR.getRepresentativeType(S.Context) << Ex->getType()
Ted Kremenek1497bff2010-02-11 19:37:25 +00001296 << getFormatSpecifierRange(startSpecifier, specifierLen)
1297 << Ex->getSourceRange();
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001298 }
Ted Kremeneke0e53132010-01-28 23:39:18 +00001299
1300 return true;
1301}
1302
Ted Kremenek07d161f2010-01-29 01:50:07 +00001303void CheckPrintfHandler::DoneProcessing() {
1304 // Does the number of data arguments exceed the number of
1305 // format conversions in the format string?
1306 if (!HasVAListArg && NumConversions < NumDataArgs)
1307 S.Diag(getDataArg(NumConversions+1)->getLocStart(),
1308 diag::warn_printf_too_many_data_args)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001309 << getFormatStringRange();
Ted Kremenek07d161f2010-01-29 01:50:07 +00001310}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001311
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001312void Sema::CheckPrintfString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001313 const Expr *OrigFormatExpr,
1314 const CallExpr *TheCall, bool HasVAListArg,
1315 unsigned format_idx, unsigned firstDataArg) {
1316
Ted Kremeneke0e53132010-01-28 23:39:18 +00001317 // CHECK: is the format string a wide literal?
1318 if (FExpr->isWide()) {
1319 Diag(FExpr->getLocStart(),
1320 diag::warn_printf_format_string_is_wide_literal)
1321 << OrigFormatExpr->getSourceRange();
1322 return;
1323 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001324
Ted Kremeneke0e53132010-01-28 23:39:18 +00001325 // Str - The format string. NOTE: this is NOT null-terminated!
1326 const char *Str = FExpr->getStrData();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001327
Ted Kremeneke0e53132010-01-28 23:39:18 +00001328 // CHECK: empty format string?
1329 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001330
Ted Kremeneke0e53132010-01-28 23:39:18 +00001331 if (StrLen == 0) {
1332 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1333 << OrigFormatExpr->getSourceRange();
1334 return;
1335 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001336
Ted Kremeneke0e53132010-01-28 23:39:18 +00001337 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr,
1338 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek0d277352010-01-29 01:06:55 +00001339 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1340 HasVAListArg, TheCall, format_idx);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001341
Ted Kremenek74d56a12010-02-04 20:46:58 +00001342 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
Ted Kremenek808015a2010-01-29 03:16:21 +00001343 H.DoneProcessing();
Ted Kremenekce7024e2010-01-28 01:18:22 +00001344}
1345
Ted Kremenek06de2762007-08-17 16:46:58 +00001346//===--- CHECK: Return Address of Stack Variable --------------------------===//
1347
1348static DeclRefExpr* EvalVal(Expr *E);
1349static DeclRefExpr* EvalAddr(Expr* E);
1350
1351/// CheckReturnStackAddr - Check if a return statement returns the address
1352/// of a stack variable.
1353void
1354Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1355 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001356
Ted Kremenek06de2762007-08-17 16:46:58 +00001357 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001358 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001359 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001360 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001361 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Steve Naroffc50a4a52008-09-16 22:25:10 +00001363 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001364 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001365
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001366 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001367 if (C->hasBlockDeclRefExprs())
1368 Diag(C->getLocStart(), diag::err_ret_local_block)
1369 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001370
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001371 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1372 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1373 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001374
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001375 } else if (lhsType->isReferenceType()) {
1376 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001377 // Check for a reference to the stack
1378 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001379 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001380 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001381 }
1382}
1383
1384/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1385/// check if the expression in a return statement evaluates to an address
1386/// to a location on the stack. The recursion is used to traverse the
1387/// AST of the return expression, with recursion backtracking when we
1388/// encounter a subexpression that (1) clearly does not lead to the address
1389/// of a stack variable or (2) is something we cannot determine leads to
1390/// the address of a stack variable based on such local checking.
1391///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001392/// EvalAddr processes expressions that are pointers that are used as
1393/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001394/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001395/// the refers to a stack variable.
1396///
1397/// This implementation handles:
1398///
1399/// * pointer-to-pointer casts
1400/// * implicit conversions from array references to pointers
1401/// * taking the address of fields
1402/// * arbitrary interplay between "&" and "*" operators
1403/// * pointer arithmetic from an address of a stack variable
1404/// * taking the address of an array element where the array is on the stack
1405static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001406 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001407 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001408 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001409 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001410 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Ted Kremenek06de2762007-08-17 16:46:58 +00001412 // Our "symbolic interpreter" is just a dispatch off the currently
1413 // viewed AST node. We then recursively traverse the AST by calling
1414 // EvalAddr and EvalVal appropriately.
1415 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001416 case Stmt::ParenExprClass:
1417 // Ignore parentheses.
1418 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001419
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001420 case Stmt::UnaryOperatorClass: {
1421 // The only unary operator that make sense to handle here
1422 // is AddrOf. All others don't make sense as pointers.
1423 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001425 if (U->getOpcode() == UnaryOperator::AddrOf)
1426 return EvalVal(U->getSubExpr());
1427 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001428 return NULL;
1429 }
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001431 case Stmt::BinaryOperatorClass: {
1432 // Handle pointer arithmetic. All other binary operators are not valid
1433 // in this context.
1434 BinaryOperator *B = cast<BinaryOperator>(E);
1435 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001437 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1438 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001440 Expr *Base = B->getLHS();
1441
1442 // Determine which argument is the real pointer base. It could be
1443 // the RHS argument instead of the LHS.
1444 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001446 assert (Base->getType()->isPointerType());
1447 return EvalAddr(Base);
1448 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001449
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001450 // For conditional operators we need to see if either the LHS or RHS are
1451 // valid DeclRefExpr*s. If one of them is valid, we return it.
1452 case Stmt::ConditionalOperatorClass: {
1453 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001455 // Handle the GNU extension for missing LHS.
1456 if (Expr *lhsExpr = C->getLHS())
1457 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1458 return LHS;
1459
1460 return EvalAddr(C->getRHS());
1461 }
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Ted Kremenek54b52742008-08-07 00:49:01 +00001463 // For casts, we need to handle conversions from arrays to
1464 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001465 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001466 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001467 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001468 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001469 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Steve Naroffdd972f22008-09-05 22:11:13 +00001471 if (SubExpr->getType()->isPointerType() ||
1472 SubExpr->getType()->isBlockPointerType() ||
1473 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001474 return EvalAddr(SubExpr);
1475 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001476 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001477 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001478 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001479 }
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001481 // C++ casts. For dynamic casts, static casts, and const casts, we
1482 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001483 // through the cast. In the case the dynamic cast doesn't fail (and
1484 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001485 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001486 // FIXME: The comment about is wrong; we're not always converting
1487 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001488 // handle references to objects.
1489 case Stmt::CXXStaticCastExprClass:
1490 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001491 case Stmt::CXXConstCastExprClass:
1492 case Stmt::CXXReinterpretCastExprClass: {
1493 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001494 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001495 return EvalAddr(S);
1496 else
1497 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001498 }
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001500 // Everything else: we simply don't reason about them.
1501 default:
1502 return NULL;
1503 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001504}
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Ted Kremenek06de2762007-08-17 16:46:58 +00001506
1507/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1508/// See the comments for EvalAddr for more details.
1509static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001511 // We should only be called for evaluating non-pointer expressions, or
1512 // expressions with a pointer type that are not used as references but instead
1513 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Ted Kremenek06de2762007-08-17 16:46:58 +00001515 // Our "symbolic interpreter" is just a dispatch off the currently
1516 // viewed AST node. We then recursively traverse the AST by calling
1517 // EvalAddr and EvalVal appropriately.
1518 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001519 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001520 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1521 // at code that refers to a variable's name. We check if it has local
1522 // storage within the function, and if so, return the expression.
1523 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Ted Kremenek06de2762007-08-17 16:46:58 +00001525 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001526 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1527
Ted Kremenek06de2762007-08-17 16:46:58 +00001528 return NULL;
1529 }
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Ted Kremenek06de2762007-08-17 16:46:58 +00001531 case Stmt::ParenExprClass:
1532 // Ignore parentheses.
1533 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Ted Kremenek06de2762007-08-17 16:46:58 +00001535 case Stmt::UnaryOperatorClass: {
1536 // The only unary operator that make sense to handle here
1537 // is Deref. All others don't resolve to a "name." This includes
1538 // handling all sorts of rvalues passed to a unary operator.
1539 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001540
Ted Kremenek06de2762007-08-17 16:46:58 +00001541 if (U->getOpcode() == UnaryOperator::Deref)
1542 return EvalAddr(U->getSubExpr());
1543
1544 return NULL;
1545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Ted Kremenek06de2762007-08-17 16:46:58 +00001547 case Stmt::ArraySubscriptExprClass: {
1548 // Array subscripts are potential references to data on the stack. We
1549 // retrieve the DeclRefExpr* for the array variable if it indeed
1550 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001551 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001552 }
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Ted Kremenek06de2762007-08-17 16:46:58 +00001554 case Stmt::ConditionalOperatorClass: {
1555 // For conditional operators we need to see if either the LHS or RHS are
1556 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1557 ConditionalOperator *C = cast<ConditionalOperator>(E);
1558
Anders Carlsson39073232007-11-30 19:04:31 +00001559 // Handle the GNU extension for missing LHS.
1560 if (Expr *lhsExpr = C->getLHS())
1561 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1562 return LHS;
1563
1564 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001565 }
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Ted Kremenek06de2762007-08-17 16:46:58 +00001567 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001568 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001569 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Ted Kremenek06de2762007-08-17 16:46:58 +00001571 // Check for indirect access. We only want direct field accesses.
1572 if (!M->isArrow())
1573 return EvalVal(M->getBase());
1574 else
1575 return NULL;
1576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Ted Kremenek06de2762007-08-17 16:46:58 +00001578 // Everything else: we simply don't reason about them.
1579 default:
1580 return NULL;
1581 }
1582}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001583
1584//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1585
1586/// Check for comparisons of floating point operands using != and ==.
1587/// Issue a warning if these are no self-comparisons, as they are not likely
1588/// to do what the programmer intended.
1589void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1590 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001592 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001593 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001594
1595 // Special case: check for x == x (which is OK).
1596 // Do not emit warnings for such cases.
1597 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1598 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1599 if (DRL->getDecl() == DRR->getDecl())
1600 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001601
1602
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001603 // Special case: check for comparisons against literals that can be exactly
1604 // represented by APFloat. In such cases, do not emit a warning. This
1605 // is a heuristic: often comparison against such literals are used to
1606 // detect if a value in a variable has not changed. This clearly can
1607 // lead to false negatives.
1608 if (EmitWarning) {
1609 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1610 if (FLL->isExact())
1611 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001612 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001613 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1614 if (FLR->isExact())
1615 EmitWarning = false;
1616 }
1617 }
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001619 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001620 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001621 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001622 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001623 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Sebastian Redl0eb23302009-01-19 00:08:26 +00001625 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001626 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001627 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001628 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001630 // Emit the diagnostic.
1631 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001632 Diag(loc, diag::warn_floatingpoint_eq)
1633 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001634}
John McCallba26e582010-01-04 23:21:16 +00001635
John McCallf2370c92010-01-06 05:24:50 +00001636//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1637//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00001638
John McCallf2370c92010-01-06 05:24:50 +00001639namespace {
John McCallba26e582010-01-04 23:21:16 +00001640
John McCallf2370c92010-01-06 05:24:50 +00001641/// Structure recording the 'active' range of an integer-valued
1642/// expression.
1643struct IntRange {
1644 /// The number of bits active in the int.
1645 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00001646
John McCallf2370c92010-01-06 05:24:50 +00001647 /// True if the int is known not to have negative values.
1648 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00001649
John McCallf2370c92010-01-06 05:24:50 +00001650 IntRange() {}
1651 IntRange(unsigned Width, bool NonNegative)
1652 : Width(Width), NonNegative(NonNegative)
1653 {}
John McCallba26e582010-01-04 23:21:16 +00001654
John McCallf2370c92010-01-06 05:24:50 +00001655 // Returns the range of the bool type.
1656 static IntRange forBoolType() {
1657 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00001658 }
1659
John McCallf2370c92010-01-06 05:24:50 +00001660 // Returns the range of an integral type.
1661 static IntRange forType(ASTContext &C, QualType T) {
1662 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00001663 }
1664
John McCallf2370c92010-01-06 05:24:50 +00001665 // Returns the range of an integeral type based on its canonical
1666 // representation.
1667 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1668 assert(T->isCanonicalUnqualified());
1669
1670 if (const VectorType *VT = dyn_cast<VectorType>(T))
1671 T = VT->getElementType().getTypePtr();
1672 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1673 T = CT->getElementType().getTypePtr();
1674 if (const EnumType *ET = dyn_cast<EnumType>(T))
1675 T = ET->getDecl()->getIntegerType().getTypePtr();
1676
1677 const BuiltinType *BT = cast<BuiltinType>(T);
1678 assert(BT->isInteger());
1679
1680 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1681 }
1682
1683 // Returns the supremum of two ranges: i.e. their conservative merge.
1684 static IntRange join(const IntRange &L, const IntRange &R) {
1685 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00001686 L.NonNegative && R.NonNegative);
1687 }
1688
1689 // Returns the infinum of two ranges: i.e. their aggressive merge.
1690 static IntRange meet(const IntRange &L, const IntRange &R) {
1691 return IntRange(std::min(L.Width, R.Width),
1692 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00001693 }
1694};
1695
1696IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1697 if (value.isSigned() && value.isNegative())
1698 return IntRange(value.getMinSignedBits(), false);
1699
1700 if (value.getBitWidth() > MaxWidth)
1701 value.trunc(MaxWidth);
1702
1703 // isNonNegative() just checks the sign bit without considering
1704 // signedness.
1705 return IntRange(value.getActiveBits(), true);
1706}
1707
John McCall0acc3112010-01-06 22:57:21 +00001708IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00001709 unsigned MaxWidth) {
1710 if (result.isInt())
1711 return GetValueRange(C, result.getInt(), MaxWidth);
1712
1713 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00001714 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1715 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1716 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1717 R = IntRange::join(R, El);
1718 }
John McCallf2370c92010-01-06 05:24:50 +00001719 return R;
1720 }
1721
1722 if (result.isComplexInt()) {
1723 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1724 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1725 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00001726 }
1727
1728 // This can happen with lossless casts to intptr_t of "based" lvalues.
1729 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00001730 // FIXME: The only reason we need to pass the type in here is to get
1731 // the sign right on this one case. It would be nice if APValue
1732 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00001733 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00001734 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00001735}
John McCallf2370c92010-01-06 05:24:50 +00001736
1737/// Pseudo-evaluate the given integer expression, estimating the
1738/// range of values it might take.
1739///
1740/// \param MaxWidth - the width to which the value will be truncated
1741IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1742 E = E->IgnoreParens();
1743
1744 // Try a full evaluation first.
1745 Expr::EvalResult result;
1746 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00001747 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00001748
1749 // I think we only want to look through implicit casts here; if the
1750 // user has an explicit widening cast, we should treat the value as
1751 // being of the new, wider type.
1752 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1753 if (CE->getCastKind() == CastExpr::CK_NoOp)
1754 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1755
1756 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1757
John McCall60fad452010-01-06 22:07:33 +00001758 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1759 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1760 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1761
John McCallf2370c92010-01-06 05:24:50 +00001762 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00001763 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00001764 return OutputTypeRange;
1765
1766 IntRange SubRange
1767 = GetExprRange(C, CE->getSubExpr(),
1768 std::min(MaxWidth, OutputTypeRange.Width));
1769
1770 // Bail out if the subexpr's range is as wide as the cast type.
1771 if (SubRange.Width >= OutputTypeRange.Width)
1772 return OutputTypeRange;
1773
1774 // Otherwise, we take the smaller width, and we're non-negative if
1775 // either the output type or the subexpr is.
1776 return IntRange(SubRange.Width,
1777 SubRange.NonNegative || OutputTypeRange.NonNegative);
1778 }
1779
1780 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1781 // If we can fold the condition, just take that operand.
1782 bool CondResult;
1783 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1784 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1785 : CO->getFalseExpr(),
1786 MaxWidth);
1787
1788 // Otherwise, conservatively merge.
1789 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1790 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1791 return IntRange::join(L, R);
1792 }
1793
1794 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1795 switch (BO->getOpcode()) {
1796
1797 // Boolean-valued operations are single-bit and positive.
1798 case BinaryOperator::LAnd:
1799 case BinaryOperator::LOr:
1800 case BinaryOperator::LT:
1801 case BinaryOperator::GT:
1802 case BinaryOperator::LE:
1803 case BinaryOperator::GE:
1804 case BinaryOperator::EQ:
1805 case BinaryOperator::NE:
1806 return IntRange::forBoolType();
1807
1808 // Operations with opaque sources are black-listed.
1809 case BinaryOperator::PtrMemD:
1810 case BinaryOperator::PtrMemI:
1811 return IntRange::forType(C, E->getType());
1812
John McCall60fad452010-01-06 22:07:33 +00001813 // Bitwise-and uses the *infinum* of the two source ranges.
1814 case BinaryOperator::And:
1815 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1816 GetExprRange(C, BO->getRHS(), MaxWidth));
1817
John McCallf2370c92010-01-06 05:24:50 +00001818 // Left shift gets black-listed based on a judgement call.
1819 case BinaryOperator::Shl:
1820 return IntRange::forType(C, E->getType());
1821
John McCall60fad452010-01-06 22:07:33 +00001822 // Right shift by a constant can narrow its left argument.
1823 case BinaryOperator::Shr: {
1824 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1825
1826 // If the shift amount is a positive constant, drop the width by
1827 // that much.
1828 llvm::APSInt shift;
1829 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1830 shift.isNonNegative()) {
1831 unsigned zext = shift.getZExtValue();
1832 if (zext >= L.Width)
1833 L.Width = (L.NonNegative ? 0 : 1);
1834 else
1835 L.Width -= zext;
1836 }
1837
1838 return L;
1839 }
1840
1841 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00001842 case BinaryOperator::Comma:
1843 return GetExprRange(C, BO->getRHS(), MaxWidth);
1844
John McCall60fad452010-01-06 22:07:33 +00001845 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00001846 case BinaryOperator::Sub:
1847 if (BO->getLHS()->getType()->isPointerType())
1848 return IntRange::forType(C, E->getType());
1849 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001850
John McCallf2370c92010-01-06 05:24:50 +00001851 default:
1852 break;
1853 }
1854
1855 // Treat every other operator as if it were closed on the
1856 // narrowest type that encompasses both operands.
1857 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1858 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1859 return IntRange::join(L, R);
1860 }
1861
1862 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1863 switch (UO->getOpcode()) {
1864 // Boolean-valued operations are white-listed.
1865 case UnaryOperator::LNot:
1866 return IntRange::forBoolType();
1867
1868 // Operations with opaque sources are black-listed.
1869 case UnaryOperator::Deref:
1870 case UnaryOperator::AddrOf: // should be impossible
1871 case UnaryOperator::OffsetOf:
1872 return IntRange::forType(C, E->getType());
1873
1874 default:
1875 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1876 }
1877 }
1878
1879 FieldDecl *BitField = E->getBitField();
1880 if (BitField) {
1881 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1882 unsigned BitWidth = BitWidthAP.getZExtValue();
1883
1884 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1885 }
1886
1887 return IntRange::forType(C, E->getType());
1888}
John McCall51313c32010-01-04 23:31:57 +00001889
1890/// Checks whether the given value, which currently has the given
1891/// source semantics, has the same value when coerced through the
1892/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00001893bool IsSameFloatAfterCast(const llvm::APFloat &value,
1894 const llvm::fltSemantics &Src,
1895 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001896 llvm::APFloat truncated = value;
1897
1898 bool ignored;
1899 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
1900 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
1901
1902 return truncated.bitwiseIsEqual(value);
1903}
1904
1905/// Checks whether the given value, which currently has the given
1906/// source semantics, has the same value when coerced through the
1907/// target semantics.
1908///
1909/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00001910bool IsSameFloatAfterCast(const APValue &value,
1911 const llvm::fltSemantics &Src,
1912 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001913 if (value.isFloat())
1914 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
1915
1916 if (value.isVector()) {
1917 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
1918 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
1919 return false;
1920 return true;
1921 }
1922
1923 assert(value.isComplexFloat());
1924 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
1925 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
1926}
1927
John McCallf2370c92010-01-06 05:24:50 +00001928} // end anonymous namespace
John McCall51313c32010-01-04 23:31:57 +00001929
John McCallba26e582010-01-04 23:21:16 +00001930/// \brief Implements -Wsign-compare.
1931///
1932/// \param lex the left-hand expression
1933/// \param rex the right-hand expression
1934/// \param OpLoc the location of the joining operator
1935/// \param Equality whether this is an "equality-like" join, which
1936/// suppresses the warning in some cases
1937void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
1938 const PartialDiagnostic &PD, bool Equality) {
1939 // Don't warn if we're in an unevaluated context.
1940 if (ExprEvalContexts.back().Context == Unevaluated)
1941 return;
1942
John McCallf2370c92010-01-06 05:24:50 +00001943 // If either expression is value-dependent, don't warn. We'll get another
1944 // chance at instantiation time.
1945 if (lex->isValueDependent() || rex->isValueDependent())
1946 return;
1947
John McCallba26e582010-01-04 23:21:16 +00001948 QualType lt = lex->getType(), rt = rex->getType();
1949
1950 // Only warn if both operands are integral.
1951 if (!lt->isIntegerType() || !rt->isIntegerType())
1952 return;
1953
John McCallf2370c92010-01-06 05:24:50 +00001954 // In C, the width of a bitfield determines its type, and the
1955 // declared type only contributes the signedness. This duplicates
1956 // the work that will later be done by UsualUnaryConversions.
1957 // Eventually, this check will be reorganized in a way that avoids
1958 // this duplication.
1959 if (!getLangOptions().CPlusPlus) {
1960 QualType tmp;
1961 tmp = Context.isPromotableBitField(lex);
1962 if (!tmp.isNull()) lt = tmp;
1963 tmp = Context.isPromotableBitField(rex);
1964 if (!tmp.isNull()) rt = tmp;
1965 }
John McCallba26e582010-01-04 23:21:16 +00001966
1967 // The rule is that the signed operand becomes unsigned, so isolate the
1968 // signed operand.
John McCallf2370c92010-01-06 05:24:50 +00001969 Expr *signedOperand = lex, *unsignedOperand = rex;
1970 QualType signedType = lt, unsignedType = rt;
John McCallba26e582010-01-04 23:21:16 +00001971 if (lt->isSignedIntegerType()) {
1972 if (rt->isSignedIntegerType()) return;
John McCallba26e582010-01-04 23:21:16 +00001973 } else {
1974 if (!rt->isSignedIntegerType()) return;
John McCallf2370c92010-01-06 05:24:50 +00001975 std::swap(signedOperand, unsignedOperand);
1976 std::swap(signedType, unsignedType);
John McCallba26e582010-01-04 23:21:16 +00001977 }
1978
John McCallf2370c92010-01-06 05:24:50 +00001979 unsigned unsignedWidth = Context.getIntWidth(unsignedType);
1980 unsigned signedWidth = Context.getIntWidth(signedType);
1981
John McCallba26e582010-01-04 23:21:16 +00001982 // If the unsigned type is strictly smaller than the signed type,
1983 // then (1) the result type will be signed and (2) the unsigned
1984 // value will fit fully within the signed type, and thus the result
1985 // of the comparison will be exact.
John McCallf2370c92010-01-06 05:24:50 +00001986 if (signedWidth > unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00001987 return;
1988
John McCallf2370c92010-01-06 05:24:50 +00001989 // Otherwise, calculate the effective ranges.
1990 IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth);
1991 IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth);
1992
1993 // We should never be unable to prove that the unsigned operand is
1994 // non-negative.
1995 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
1996
1997 // If the signed operand is non-negative, then the signed->unsigned
1998 // conversion won't change it.
1999 if (signedRange.NonNegative)
John McCallba26e582010-01-04 23:21:16 +00002000 return;
2001
2002 // For (in)equality comparisons, if the unsigned operand is a
2003 // constant which cannot collide with a overflowed signed operand,
2004 // then reinterpreting the signed operand as unsigned will not
2005 // change the result of the comparison.
John McCallf2370c92010-01-06 05:24:50 +00002006 if (Equality && unsignedRange.Width < unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002007 return;
2008
2009 Diag(OpLoc, PD)
John McCallf2370c92010-01-06 05:24:50 +00002010 << lt << rt << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002011}
2012
John McCall51313c32010-01-04 23:31:57 +00002013/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2014static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
2015 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2016}
2017
2018/// Implements -Wconversion.
2019void Sema::CheckImplicitConversion(Expr *E, QualType T) {
2020 // Don't diagnose in unevaluated contexts.
2021 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2022 return;
2023
2024 // Don't diagnose for value-dependent expressions.
2025 if (E->isValueDependent())
2026 return;
2027
2028 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
2029 const Type *Target = Context.getCanonicalType(T).getTypePtr();
2030
2031 // Never diagnose implicit casts to bool.
2032 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2033 return;
2034
2035 // Strip vector types.
2036 if (isa<VectorType>(Source)) {
2037 if (!isa<VectorType>(Target))
2038 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar);
2039
2040 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2041 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2042 }
2043
2044 // Strip complex types.
2045 if (isa<ComplexType>(Source)) {
2046 if (!isa<ComplexType>(Target))
2047 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar);
2048
2049 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2050 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2051 }
2052
2053 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2054 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2055
2056 // If the source is floating point...
2057 if (SourceBT && SourceBT->isFloatingPoint()) {
2058 // ...and the target is floating point...
2059 if (TargetBT && TargetBT->isFloatingPoint()) {
2060 // ...then warn if we're dropping FP rank.
2061
2062 // Builtin FP kinds are ordered by increasing FP rank.
2063 if (SourceBT->getKind() > TargetBT->getKind()) {
2064 // Don't warn about float constants that are precisely
2065 // representable in the target type.
2066 Expr::EvalResult result;
2067 if (E->Evaluate(result, Context)) {
2068 // Value might be a float, a float vector, or a float complex.
2069 if (IsSameFloatAfterCast(result.Val,
2070 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2071 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2072 return;
2073 }
2074
2075 DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision);
2076 }
2077 return;
2078 }
2079
2080 // If the target is integral, always warn.
2081 if ((TargetBT && TargetBT->isInteger()))
2082 // TODO: don't warn for integer values?
2083 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer);
2084
2085 return;
2086 }
2087
John McCallf2370c92010-01-06 05:24:50 +00002088 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002089 return;
2090
John McCallf2370c92010-01-06 05:24:50 +00002091 IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType()));
2092 IntRange TargetRange = IntRange::forCanonicalType(Context, Target);
John McCall51313c32010-01-04 23:31:57 +00002093
John McCallf2370c92010-01-06 05:24:50 +00002094 // FIXME: also signed<->unsigned?
2095
2096 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002097 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2098 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002099 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall51313c32010-01-04 23:31:57 +00002100 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32);
2101 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision);
2102 }
2103
2104 return;
2105}
2106
Mike Stumpf8c49212010-01-21 03:59:47 +00002107// MarkLive - Mark all the blocks reachable from e as live. Returns the total
2108// number of blocks just marked live.
2109static unsigned MarkLive(CFGBlock *e, llvm::BitVector &live) {
2110 unsigned count = 0;
2111 std::queue<CFGBlock*> workq;
2112 // Prep work queue
2113 live.set(e->getBlockID());
2114 ++count;
2115 workq.push(e);
2116 // Solve
2117 while (!workq.empty()) {
2118 CFGBlock *item = workq.front();
2119 workq.pop();
2120 for (CFGBlock::succ_iterator I=item->succ_begin(),
2121 E=item->succ_end();
2122 I != E;
2123 ++I) {
2124 if ((*I) && !live[(*I)->getBlockID()]) {
2125 live.set((*I)->getBlockID());
2126 ++count;
2127 workq.push(*I);
2128 }
2129 }
2130 }
2131 return count;
2132}
2133
Mike Stump55f988e2010-01-21 17:21:23 +00002134static SourceLocation GetUnreachableLoc(CFGBlock &b, SourceRange &R1,
2135 SourceRange &R2) {
Mike Stumpf8c49212010-01-21 03:59:47 +00002136 Stmt *S;
Mike Stumpe5fba702010-01-21 19:44:04 +00002137 unsigned sn = 0;
2138 R1 = R2 = SourceRange();
2139
2140 top:
2141 if (sn < b.size())
2142 S = b[sn].getStmt();
Mike Stumpf8c49212010-01-21 03:59:47 +00002143 else if (b.getTerminator())
2144 S = b.getTerminator();
2145 else
2146 return SourceLocation();
2147
2148 switch (S->getStmtClass()) {
2149 case Expr::BinaryOperatorClass: {
Mike Stump55f988e2010-01-21 17:21:23 +00002150 BinaryOperator *BO = cast<BinaryOperator>(S);
2151 if (BO->getOpcode() == BinaryOperator::Comma) {
Mike Stumpe5fba702010-01-21 19:44:04 +00002152 if (sn+1 < b.size())
2153 return b[sn+1].getStmt()->getLocStart();
Mike Stumpf8c49212010-01-21 03:59:47 +00002154 CFGBlock *n = &b;
2155 while (1) {
2156 if (n->getTerminator())
2157 return n->getTerminator()->getLocStart();
2158 if (n->succ_size() != 1)
2159 return SourceLocation();
2160 n = n[0].succ_begin()[0];
2161 if (n->pred_size() != 1)
2162 return SourceLocation();
2163 if (!n->empty())
2164 return n[0][0].getStmt()->getLocStart();
2165 }
2166 }
Mike Stump55f988e2010-01-21 17:21:23 +00002167 R1 = BO->getLHS()->getSourceRange();
2168 R2 = BO->getRHS()->getSourceRange();
2169 return BO->getOperatorLoc();
2170 }
2171 case Expr::UnaryOperatorClass: {
2172 const UnaryOperator *UO = cast<UnaryOperator>(S);
2173 R1 = UO->getSubExpr()->getSourceRange();
2174 return UO->getOperatorLoc();
Mike Stumpf8c49212010-01-21 03:59:47 +00002175 }
Mike Stump45db90d2010-01-21 17:31:41 +00002176 case Expr::CompoundAssignOperatorClass: {
2177 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(S);
2178 R1 = CAO->getLHS()->getSourceRange();
2179 R2 = CAO->getRHS()->getSourceRange();
2180 return CAO->getOperatorLoc();
2181 }
Mike Stumpe5fba702010-01-21 19:44:04 +00002182 case Expr::ConditionalOperatorClass: {
2183 const ConditionalOperator *CO = cast<ConditionalOperator>(S);
2184 return CO->getQuestionLoc();
2185 }
Mike Stumpb5c77552010-01-21 23:15:53 +00002186 case Expr::MemberExprClass: {
2187 const MemberExpr *ME = cast<MemberExpr>(S);
2188 R1 = ME->getSourceRange();
2189 return ME->getMemberLoc();
2190 }
2191 case Expr::ArraySubscriptExprClass: {
2192 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(S);
2193 R1 = ASE->getLHS()->getSourceRange();
2194 R2 = ASE->getRHS()->getSourceRange();
2195 return ASE->getRBracketLoc();
2196 }
Mike Stump44582302010-01-21 19:51:34 +00002197 case Expr::CStyleCastExprClass: {
2198 const CStyleCastExpr *CSC = cast<CStyleCastExpr>(S);
2199 R1 = CSC->getSubExpr()->getSourceRange();
2200 return CSC->getLParenLoc();
2201 }
Mike Stump2d6ceab2010-01-21 22:12:18 +00002202 case Expr::CXXFunctionalCastExprClass: {
2203 const CXXFunctionalCastExpr *CE = cast <CXXFunctionalCastExpr>(S);
2204 R1 = CE->getSubExpr()->getSourceRange();
2205 return CE->getTypeBeginLoc();
2206 }
Mike Stumpe5fba702010-01-21 19:44:04 +00002207 case Expr::ImplicitCastExprClass:
2208 ++sn;
2209 goto top;
Mike Stump4c45aa12010-01-21 15:20:48 +00002210 case Stmt::CXXTryStmtClass: {
2211 return cast<CXXTryStmt>(S)->getHandler(0)->getCatchLoc();
2212 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002213 default: ;
2214 }
Mike Stumpb5c77552010-01-21 23:15:53 +00002215 R1 = S->getSourceRange();
Mike Stumpf8c49212010-01-21 03:59:47 +00002216 return S->getLocStart();
2217}
2218
2219static SourceLocation MarkLiveTop(CFGBlock *e, llvm::BitVector &live,
2220 SourceManager &SM) {
2221 std::queue<CFGBlock*> workq;
2222 // Prep work queue
2223 workq.push(e);
Mike Stump55f988e2010-01-21 17:21:23 +00002224 SourceRange R1, R2;
2225 SourceLocation top = GetUnreachableLoc(*e, R1, R2);
Mike Stumpf8c49212010-01-21 03:59:47 +00002226 bool FromMainFile = false;
2227 bool FromSystemHeader = false;
2228 bool TopValid = false;
2229 if (top.isValid()) {
2230 FromMainFile = SM.isFromMainFile(top);
2231 FromSystemHeader = SM.isInSystemHeader(top);
2232 TopValid = true;
2233 }
2234 // Solve
2235 while (!workq.empty()) {
2236 CFGBlock *item = workq.front();
2237 workq.pop();
Mike Stump55f988e2010-01-21 17:21:23 +00002238 SourceLocation c = GetUnreachableLoc(*item, R1, R2);
Mike Stumpf8c49212010-01-21 03:59:47 +00002239 if (c.isValid()
2240 && (!TopValid
2241 || (SM.isFromMainFile(c) && !FromMainFile)
2242 || (FromSystemHeader && !SM.isInSystemHeader(c))
2243 || SM.isBeforeInTranslationUnit(c, top))) {
2244 top = c;
2245 FromMainFile = SM.isFromMainFile(top);
2246 FromSystemHeader = SM.isInSystemHeader(top);
2247 }
2248 live.set(item->getBlockID());
2249 for (CFGBlock::succ_iterator I=item->succ_begin(),
2250 E=item->succ_end();
2251 I != E;
2252 ++I) {
2253 if ((*I) && !live[(*I)->getBlockID()]) {
2254 live.set((*I)->getBlockID());
2255 workq.push(*I);
2256 }
2257 }
2258 }
2259 return top;
2260}
2261
2262static int LineCmp(const void *p1, const void *p2) {
2263 SourceLocation *Line1 = (SourceLocation *)p1;
2264 SourceLocation *Line2 = (SourceLocation *)p2;
2265 return !(*Line1 < *Line2);
2266}
2267
Mike Stump4a415672010-01-21 23:49:01 +00002268namespace {
2269 struct ErrLoc {
2270 SourceLocation Loc;
2271 SourceRange R1;
2272 SourceRange R2;
2273 ErrLoc(SourceLocation l, SourceRange r1, SourceRange r2)
2274 : Loc(l), R1(r1), R2(r2) { }
2275 };
2276}
2277
Mike Stumpf8c49212010-01-21 03:59:47 +00002278/// CheckUnreachable - Check for unreachable code.
2279void Sema::CheckUnreachable(AnalysisContext &AC) {
2280 unsigned count;
2281 // We avoid checking when there are errors, as the CFG won't faithfully match
2282 // the user's code.
2283 if (getDiagnostics().hasErrorOccurred())
2284 return;
2285 if (Diags.getDiagnosticLevel(diag::warn_unreachable) == Diagnostic::Ignored)
2286 return;
2287
2288 CFG *cfg = AC.getCFG();
2289 if (cfg == 0)
2290 return;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002291
Mike Stumpf8c49212010-01-21 03:59:47 +00002292 llvm::BitVector live(cfg->getNumBlockIDs());
2293 // Mark all live things first.
2294 count = MarkLive(&cfg->getEntry(), live);
2295
2296 if (count == cfg->getNumBlockIDs())
2297 // If there are no dead blocks, we're done.
2298 return;
2299
Mike Stump55f988e2010-01-21 17:21:23 +00002300 SourceRange R1, R2;
2301
Mike Stump4a415672010-01-21 23:49:01 +00002302 llvm::SmallVector<ErrLoc, 24> lines;
Mike Stump4c45aa12010-01-21 15:20:48 +00002303 bool AddEHEdges = AC.getAddEHEdges();
Mike Stumpf8c49212010-01-21 03:59:47 +00002304 // First, give warnings for blocks with no predecessors, as they
2305 // can't be part of a loop.
2306 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2307 CFGBlock &b = **I;
2308 if (!live[b.getBlockID()]) {
2309 if (b.pred_begin() == b.pred_end()) {
Mike Stump4c45aa12010-01-21 15:20:48 +00002310 if (!AddEHEdges && b.getTerminator()
2311 && isa<CXXTryStmt>(b.getTerminator())) {
2312 // When not adding EH edges from calls, catch clauses
2313 // can otherwise seem dead. Avoid noting them as dead.
2314 count += MarkLive(&b, live);
2315 continue;
2316 }
Mike Stump55f988e2010-01-21 17:21:23 +00002317 SourceLocation c = GetUnreachableLoc(b, R1, R2);
Mike Stumpf8c49212010-01-21 03:59:47 +00002318 if (!c.isValid()) {
2319 // Blocks without a location can't produce a warning, so don't mark
2320 // reachable blocks from here as live.
2321 live.set(b.getBlockID());
2322 ++count;
2323 continue;
2324 }
Mike Stump4a415672010-01-21 23:49:01 +00002325 lines.push_back(ErrLoc(c, R1, R2));
Mike Stumpf8c49212010-01-21 03:59:47 +00002326 // Avoid excessive errors by marking everything reachable from here
2327 count += MarkLive(&b, live);
2328 }
2329 }
2330 }
2331
2332 if (count < cfg->getNumBlockIDs()) {
2333 // And then give warnings for the tops of loops.
2334 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2335 CFGBlock &b = **I;
2336 if (!live[b.getBlockID()])
2337 // Avoid excessive errors by marking everything reachable from here
Ted Kremenek8acc9f62010-01-28 01:04:48 +00002338 lines.push_back(ErrLoc(MarkLiveTop(&b, live,
2339 Context.getSourceManager()),
2340 SourceRange(), SourceRange()));
Mike Stumpf8c49212010-01-21 03:59:47 +00002341 }
2342 }
2343
2344 llvm::array_pod_sort(lines.begin(), lines.end(), LineCmp);
Mike Stump4a415672010-01-21 23:49:01 +00002345 for (llvm::SmallVector<ErrLoc, 24>::iterator I = lines.begin(),
Mike Stumpf8c49212010-01-21 03:59:47 +00002346 E = lines.end();
2347 I != E;
2348 ++I)
Mike Stump4a415672010-01-21 23:49:01 +00002349 if (I->Loc.isValid())
2350 Diag(I->Loc, diag::warn_unreachable) << I->R1 << I->R2;
Mike Stumpf8c49212010-01-21 03:59:47 +00002351}
2352
2353/// CheckFallThrough - Check that we don't fall off the end of a
2354/// Statement that should return a value.
2355///
2356/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
2357/// MaybeFallThrough iff we might or might not fall off the end,
2358/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
2359/// return. We assume NeverFallThrough iff we never fall off the end of the
2360/// statement but we may return. We assume that functions not marked noreturn
2361/// will return.
2362Sema::ControlFlowKind Sema::CheckFallThrough(AnalysisContext &AC) {
2363 CFG *cfg = AC.getCFG();
2364 if (cfg == 0)
2365 // FIXME: This should be NeverFallThrough
2366 return NeverFallThroughOrReturn;
2367
Mike Stump4c45aa12010-01-21 15:20:48 +00002368 // The CFG leaves in dead things, and we don't want the dead code paths to
Mike Stumpf8c49212010-01-21 03:59:47 +00002369 // confuse us, so we mark all live things first.
2370 std::queue<CFGBlock*> workq;
2371 llvm::BitVector live(cfg->getNumBlockIDs());
Mike Stump4c45aa12010-01-21 15:20:48 +00002372 unsigned count = MarkLive(&cfg->getEntry(), live);
2373
2374 bool AddEHEdges = AC.getAddEHEdges();
2375 if (!AddEHEdges && count != cfg->getNumBlockIDs())
2376 // When there are things remaining dead, and we didn't add EH edges
2377 // from CallExprs to the catch clauses, we have to go back and
2378 // mark them as live.
2379 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2380 CFGBlock &b = **I;
2381 if (!live[b.getBlockID()]) {
2382 if (b.pred_begin() == b.pred_end()) {
2383 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
2384 // When not adding EH edges from calls, catch clauses
2385 // can otherwise seem dead. Avoid noting them as dead.
2386 count += MarkLive(&b, live);
2387 continue;
2388 }
2389 }
2390 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002391
2392 // Now we know what is live, we check the live precessors of the exit block
2393 // and look for fall through paths, being careful to ignore normal returns,
2394 // and exceptional paths.
2395 bool HasLiveReturn = false;
2396 bool HasFakeEdge = false;
2397 bool HasPlainEdge = false;
2398 bool HasAbnormalEdge = false;
2399 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
2400 E = cfg->getExit().pred_end();
2401 I != E;
2402 ++I) {
2403 CFGBlock& B = **I;
2404 if (!live[B.getBlockID()])
2405 continue;
2406 if (B.size() == 0) {
Mike Stump4c45aa12010-01-21 15:20:48 +00002407 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
2408 HasAbnormalEdge = true;
2409 continue;
2410 }
2411
Mike Stumpf8c49212010-01-21 03:59:47 +00002412 // A labeled empty statement, or the entry block...
2413 HasPlainEdge = true;
2414 continue;
2415 }
2416 Stmt *S = B[B.size()-1];
2417 if (isa<ReturnStmt>(S)) {
2418 HasLiveReturn = true;
2419 continue;
2420 }
2421 if (isa<ObjCAtThrowStmt>(S)) {
2422 HasFakeEdge = true;
2423 continue;
2424 }
2425 if (isa<CXXThrowExpr>(S)) {
2426 HasFakeEdge = true;
2427 continue;
2428 }
2429 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
2430 if (AS->isMSAsm()) {
2431 HasFakeEdge = true;
2432 HasLiveReturn = true;
2433 continue;
2434 }
2435 }
2436 if (isa<CXXTryStmt>(S)) {
2437 HasAbnormalEdge = true;
2438 continue;
2439 }
2440
2441 bool NoReturnEdge = false;
2442 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
2443 if (B.succ_begin()[0] != &cfg->getExit()) {
2444 HasAbnormalEdge = true;
2445 continue;
2446 }
2447 Expr *CEE = C->getCallee()->IgnoreParenCasts();
2448 if (CEE->getType().getNoReturnAttr()) {
2449 NoReturnEdge = true;
2450 HasFakeEdge = true;
2451 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
2452 ValueDecl *VD = DRE->getDecl();
2453 if (VD->hasAttr<NoReturnAttr>()) {
2454 NoReturnEdge = true;
2455 HasFakeEdge = true;
2456 }
2457 }
2458 }
2459 // FIXME: Add noreturn message sends.
2460 if (NoReturnEdge == false)
2461 HasPlainEdge = true;
2462 }
2463 if (!HasPlainEdge) {
2464 if (HasLiveReturn)
2465 return NeverFallThrough;
2466 return NeverFallThroughOrReturn;
2467 }
2468 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
2469 return MaybeFallThrough;
2470 // This says AlwaysFallThrough for calls to functions that are not marked
2471 // noreturn, that don't return. If people would like this warning to be more
2472 // accurate, such functions should be marked as noreturn.
2473 return AlwaysFallThrough;
2474}
2475
2476/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
2477/// function that should return a value. Check that we don't fall off the end
2478/// of a noreturn function. We assume that functions and blocks not marked
2479/// noreturn will return.
2480void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body,
2481 AnalysisContext &AC) {
2482 // FIXME: Would be nice if we had a better way to control cascading errors,
2483 // but for now, avoid them. The problem is that when Parse sees:
2484 // int foo() { return a; }
2485 // The return is eaten and the Sema code sees just:
2486 // int foo() { }
2487 // which this code would then warn about.
2488 if (getDiagnostics().hasErrorOccurred())
2489 return;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002490
Mike Stumpf8c49212010-01-21 03:59:47 +00002491 bool ReturnsVoid = false;
2492 bool HasNoReturn = false;
2493 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anders Carlsson4855a522010-02-06 05:31:15 +00002494 // For function templates, class templates and member function templates
2495 // we'll do the analysis at instantiation time.
2496 if (FD->isDependentContext())
Mike Stumpf8c49212010-01-21 03:59:47 +00002497 return;
Anders Carlsson4855a522010-02-06 05:31:15 +00002498
Mike Stumpf8c49212010-01-21 03:59:47 +00002499 if (FD->getResultType()->isVoidType())
2500 ReturnsVoid = true;
John McCall04a67a62010-02-05 21:31:56 +00002501 if (FD->hasAttr<NoReturnAttr>() ||
2502 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
Mike Stumpf8c49212010-01-21 03:59:47 +00002503 HasNoReturn = true;
2504 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2505 if (MD->getResultType()->isVoidType())
2506 ReturnsVoid = true;
2507 if (MD->hasAttr<NoReturnAttr>())
2508 HasNoReturn = true;
2509 }
2510
2511 // Short circuit for compilation speed.
2512 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
2513 == Diagnostic::Ignored || ReturnsVoid)
2514 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
2515 == Diagnostic::Ignored || !HasNoReturn)
2516 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
2517 == Diagnostic::Ignored || !ReturnsVoid))
2518 return;
2519 // FIXME: Function try block
2520 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
2521 switch (CheckFallThrough(AC)) {
2522 case MaybeFallThrough:
2523 if (HasNoReturn)
2524 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
2525 else if (!ReturnsVoid)
2526 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
2527 break;
2528 case AlwaysFallThrough:
2529 if (HasNoReturn)
2530 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
2531 else if (!ReturnsVoid)
2532 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
2533 break;
2534 case NeverFallThroughOrReturn:
2535 if (ReturnsVoid && !HasNoReturn)
2536 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
2537 break;
2538 case NeverFallThrough:
2539 break;
2540 }
2541 }
2542}
2543
2544/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
2545/// that should return a value. Check that we don't fall off the end of a
2546/// noreturn block. We assume that functions and blocks not marked noreturn
2547/// will return.
2548void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body,
2549 AnalysisContext &AC) {
2550 // FIXME: Would be nice if we had a better way to control cascading errors,
2551 // but for now, avoid them. The problem is that when Parse sees:
2552 // int foo() { return a; }
2553 // The return is eaten and the Sema code sees just:
2554 // int foo() { }
2555 // which this code would then warn about.
2556 if (getDiagnostics().hasErrorOccurred())
2557 return;
2558 bool ReturnsVoid = false;
2559 bool HasNoReturn = false;
2560 if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
2561 if (FT->getResultType()->isVoidType())
2562 ReturnsVoid = true;
2563 if (FT->getNoReturnAttr())
2564 HasNoReturn = true;
2565 }
2566
2567 // Short circuit for compilation speed.
2568 if (ReturnsVoid
2569 && !HasNoReturn
2570 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
2571 == Diagnostic::Ignored || !ReturnsVoid))
2572 return;
2573 // FIXME: Funtion try block
2574 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
2575 switch (CheckFallThrough(AC)) {
2576 case MaybeFallThrough:
2577 if (HasNoReturn)
2578 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
2579 else if (!ReturnsVoid)
2580 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
2581 break;
2582 case AlwaysFallThrough:
2583 if (HasNoReturn)
2584 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
2585 else if (!ReturnsVoid)
2586 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
2587 break;
2588 case NeverFallThroughOrReturn:
2589 if (ReturnsVoid)
2590 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
2591 break;
2592 case NeverFallThrough:
2593 break;
2594 }
2595 }
2596}
2597
2598/// CheckParmsForFunctionDef - Check that the parameters of the given
2599/// function are appropriate for the definition of a function. This
2600/// takes care of any checks that cannot be performed on the
2601/// declaration itself, e.g., that the types of each of the function
2602/// parameters are complete.
2603bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2604 bool HasInvalidParm = false;
2605 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2606 ParmVarDecl *Param = FD->getParamDecl(p);
2607
2608 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2609 // function declarator that is part of a function definition of
2610 // that function shall not have incomplete type.
2611 //
2612 // This is also C++ [dcl.fct]p6.
2613 if (!Param->isInvalidDecl() &&
2614 RequireCompleteType(Param->getLocation(), Param->getType(),
2615 diag::err_typecheck_decl_incomplete_type)) {
2616 Param->setInvalidDecl();
2617 HasInvalidParm = true;
2618 }
2619
2620 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2621 // declaration of each parameter shall include an identifier.
2622 if (Param->getIdentifier() == 0 &&
2623 !Param->isImplicit() &&
2624 !getLangOptions().CPlusPlus)
2625 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002626
2627 // C99 6.7.5.3p12:
2628 // If the function declarator is not part of a definition of that
2629 // function, parameters may have incomplete type and may use the [*]
2630 // notation in their sequences of declarator specifiers to specify
2631 // variable length array types.
2632 QualType PType = Param->getOriginalType();
2633 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2634 if (AT->getSizeModifier() == ArrayType::Star) {
2635 // FIXME: This diagnosic should point the the '[*]' if source-location
2636 // information is added for it.
2637 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2638 }
2639 }
John McCall4f9506a2010-02-02 08:45:54 +00002640
John McCall68c6c9a2010-02-02 09:10:11 +00002641 if (getLangOptions().CPlusPlus)
2642 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
2643 FinalizeVarWithDestructor(Param, RT);
Mike Stumpf8c49212010-01-21 03:59:47 +00002644 }
2645
2646 return HasInvalidParm;
2647}