blob: 6e54dab113be7c26f49596adc26d980ac8db29c2 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
Ted Kremeneke0e53132010-01-28 23:39:18 +000016#include "clang/Analysis/Analyses/PrintfFormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000017#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000018#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000020#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000021#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000022#include "clang/AST/DeclObjC.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/AST/StmtObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000025#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000026#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000027#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/STLExtras.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000031#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000032using namespace clang;
33
Chris Lattner60800082009-02-18 17:49:48 +000034/// getLocationOfStringLiteralByte - Return a source location that points to the
35/// specified byte of the specified string literal.
36///
37/// Strings are amazingly complex. They can be formed from multiple tokens and
38/// can have escape sequences in them in addition to the usual trigraph and
39/// escaped newline business. This routine handles this complexity.
40///
41SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
42 unsigned ByteNo) const {
43 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045 // Loop over all of the tokens in this string until we find the one that
46 // contains the byte we're looking for.
47 unsigned TokNo = 0;
48 while (1) {
49 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
50 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000051
Chris Lattner60800082009-02-18 17:49:48 +000052 // Get the spelling of the string so that we can get the data that makes up
53 // the string literal, not the identifier for the macro it is potentially
54 // expanded through.
55 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
56
57 // Re-lex the token to get its length and original spelling.
58 std::pair<FileID, unsigned> LocInfo =
59 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
Douglas Gregorf715ca12010-03-16 00:06:06 +000060 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000061 llvm::StringRef Buffer = SourceMgr.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +000062 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +000063 return StrTokSpellingLoc;
64
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000065 const char *StrData = Buffer.data()+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattner60800082009-02-18 17:49:48 +000067 // Create a langops struct and enable trigraphs. This is sufficient for
68 // relexing tokens.
69 LangOptions LangOpts;
70 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner60800082009-02-18 17:49:48 +000072 // Create a lexer starting at the beginning of this token.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000073 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.begin(), StrData,
74 Buffer.end());
Chris Lattner60800082009-02-18 17:49:48 +000075 Token TheTok;
76 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Chris Lattner443e53c2009-02-18 19:26:42 +000078 // Use the StringLiteralParser to compute the length of the string in bytes.
Douglas Gregorb90f4b32010-05-26 05:35:51 +000079 StringLiteralParser SLP(&TheTok, 1, PP, /*Complain=*/false);
Chris Lattner443e53c2009-02-18 19:26:42 +000080 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000081
Chris Lattner2197c962009-02-18 18:52:52 +000082 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000083 if (ByteNo < TokNumBytes ||
84 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000085 unsigned Offset =
Douglas Gregorb90f4b32010-05-26 05:35:51 +000086 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP,
87 /*Complain=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +000088
Chris Lattner719e6152009-02-18 19:21:10 +000089 // Now that we know the offset of the token in the spelling, use the
90 // preprocessor to get the offset in the original source.
91 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000092 }
Mike Stump1eb44332009-09-09 15:08:12 +000093
Chris Lattner60800082009-02-18 17:49:48 +000094 // Move to the next string token.
95 ++TokNo;
96 ByteNo -= TokNumBytes;
97 }
98}
99
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000100/// CheckablePrintfAttr - does a function call have a "printf" attribute
101/// and arguments that merit checking?
102bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
103 if (Format->getType() == "printf") return true;
104 if (Format->getType() == "printf0") {
105 // printf0 allows null "format" string; if so don't check format/args
106 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000107 // Does the index refer to the implicit object argument?
108 if (isa<CXXMemberCallExpr>(TheCall)) {
109 if (format_idx == 0)
110 return false;
111 --format_idx;
112 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000113 if (format_idx < TheCall->getNumArgs()) {
114 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +0000115 if (!Format->isNullPointerConstant(Context,
116 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000117 return true;
118 }
119 }
120 return false;
121}
Chris Lattner60800082009-02-18 17:49:48 +0000122
Sebastian Redl0eb23302009-01-19 00:08:26 +0000123Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000124Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000126
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000129 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000130 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000131 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000134 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000135 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinVAStart(TheCall))
137 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000138 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 case Builtin::BI__builtin_isgreater:
140 case Builtin::BI__builtin_isgreaterequal:
141 case Builtin::BI__builtin_isless:
142 case Builtin::BI__builtin_islessequal:
143 case Builtin::BI__builtin_islessgreater:
144 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinUnorderedCompare(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000148 case Builtin::BI__builtin_fpclassify:
149 if (SemaBuiltinFPClassification(TheCall, 6))
150 return ExprError();
151 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 case Builtin::BI__builtin_isfinite:
153 case Builtin::BI__builtin_isinf:
154 case Builtin::BI__builtin_isinf_sign:
155 case Builtin::BI__builtin_isnan:
156 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000157 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000158 return ExprError();
159 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000160 case Builtin::BI__builtin_return_address:
Eric Christopher691ebc32010-04-17 02:26:23 +0000161 case Builtin::BI__builtin_frame_address: {
162 llvm::APSInt Result;
163 if (SemaBuiltinConstantArg(TheCall, 0, Result))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000164 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000165 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000166 }
167 case Builtin::BI__builtin_eh_return_data_regno: {
168 llvm::APSInt Result;
169 if (SemaBuiltinConstantArg(TheCall, 0, Result))
Chris Lattner21fb98e2009-09-23 06:06:36 +0000170 return ExprError();
171 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000172 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000173 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000174 return SemaBuiltinShuffleVector(TheCall);
175 // TheCall will be freed by the smart pointer here, but that's fine, since
176 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000177 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000178 if (SemaBuiltinPrefetch(TheCall))
179 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000180 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000181 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000182 if (SemaBuiltinObjectSize(TheCall))
183 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000184 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000185 case Builtin::BI__builtin_longjmp:
186 if (SemaBuiltinLongjmp(TheCall))
187 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000188 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000189 case Builtin::BI__sync_fetch_and_add:
190 case Builtin::BI__sync_fetch_and_sub:
191 case Builtin::BI__sync_fetch_and_or:
192 case Builtin::BI__sync_fetch_and_and:
193 case Builtin::BI__sync_fetch_and_xor:
194 case Builtin::BI__sync_add_and_fetch:
195 case Builtin::BI__sync_sub_and_fetch:
196 case Builtin::BI__sync_and_and_fetch:
197 case Builtin::BI__sync_or_and_fetch:
198 case Builtin::BI__sync_xor_and_fetch:
199 case Builtin::BI__sync_val_compare_and_swap:
200 case Builtin::BI__sync_bool_compare_and_swap:
201 case Builtin::BI__sync_lock_test_and_set:
202 case Builtin::BI__sync_lock_release:
203 if (SemaBuiltinAtomicOverloaded(TheCall))
204 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000205 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000206 }
207
208 // Since the target specific builtins for each arch overlap, only check those
209 // of the arch we are compiling for.
210 if (BuiltinID >= Builtin::FirstTSBuiltin) {
211 switch (Context.Target.getTriple().getArch()) {
212 case llvm::Triple::arm:
213 case llvm::Triple::thumb:
214 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
215 return ExprError();
216 break;
217 case llvm::Triple::x86:
218 case llvm::Triple::x86_64:
219 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
220 return ExprError();
221 break;
222 default:
223 break;
224 }
225 }
226
227 return move(TheCallResult);
228}
229
230bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
231 switch (BuiltinID) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000232 case X86::BI__builtin_ia32_palignr128:
233 case X86::BI__builtin_ia32_palignr: {
234 llvm::APSInt Result;
235 if (SemaBuiltinConstantArg(TheCall, 2, Result))
Nate Begeman26a31422010-06-08 02:47:44 +0000236 return true;
Eric Christopher691ebc32010-04-17 02:26:23 +0000237 break;
238 }
Anders Carlsson71993dd2007-08-17 05:31:46 +0000239 }
Nate Begeman26a31422010-06-08 02:47:44 +0000240 return false;
241}
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Nate Begeman26a31422010-06-08 02:47:44 +0000243bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000244 llvm::APSInt Result;
245
246 switch (BuiltinID) {
247 case ARM::BI__builtin_neon_vget_lane_i8:
248 case ARM::BI__builtin_neon_vget_lane_i16:
249 case ARM::BI__builtin_neon_vget_lane_i32:
250 case ARM::BI__builtin_neon_vget_lane_f32:
251 case ARM::BI__builtin_neon_vget_lane_i64:
252 case ARM::BI__builtin_neon_vgetq_lane_i8:
253 case ARM::BI__builtin_neon_vgetq_lane_i16:
254 case ARM::BI__builtin_neon_vgetq_lane_i32:
255 case ARM::BI__builtin_neon_vgetq_lane_f32:
256 case ARM::BI__builtin_neon_vgetq_lane_i64:
257 // Check constant-ness first.
258 if (SemaBuiltinConstantArg(TheCall, 1, Result))
259 return true;
260 break;
261 }
262
263 // Now, range check values.
264 //unsigned lower = 0, upper = 0;
265
Nate Begeman26a31422010-06-08 02:47:44 +0000266 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000267}
Daniel Dunbarde454282008-10-02 18:44:07 +0000268
Anders Carlssond406bf02009-08-16 01:56:34 +0000269/// CheckFunctionCall - Check a direct function call for various correctness
270/// and safety properties not strictly enforced by the C type system.
271bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
272 // Get the IdentifierInfo* for the called function.
273 IdentifierInfo *FnInfo = FDecl->getIdentifier();
274
275 // None of the checks below are needed for functions that don't have
276 // simple names (e.g., C++ conversion functions).
277 if (!FnInfo)
278 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Daniel Dunbarde454282008-10-02 18:44:07 +0000280 // FIXME: This mechanism should be abstracted to be less fragile and
281 // more efficient. For example, just map function ids to custom
282 // handlers.
283
Chris Lattner59907c42007-08-10 20:18:51 +0000284 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000285 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000286 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000287 bool HasVAListArg = Format->getFirstArg() == 0;
Douglas Gregor3c385e52009-02-14 18:57:46 +0000288 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000289 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000290 }
Chris Lattner59907c42007-08-10 20:18:51 +0000291 }
Mike Stump1eb44332009-09-09 15:08:12 +0000292
293 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000294 NonNull = NonNull->getNext<NonNullAttr>())
295 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000296
Anders Carlssond406bf02009-08-16 01:56:34 +0000297 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000298}
299
Anders Carlssond406bf02009-08-16 01:56:34 +0000300bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000301 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000302 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000303 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000304 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000306 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
307 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000308 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000310 QualType Ty = V->getType();
311 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000312 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Anders Carlssond406bf02009-08-16 01:56:34 +0000314 if (!CheckablePrintfAttr(Format, TheCall))
315 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Anders Carlssond406bf02009-08-16 01:56:34 +0000317 bool HasVAListArg = Format->getFirstArg() == 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000318 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
319 HasVAListArg ? 0 : Format->getFirstArg() - 1);
320
321 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000322}
323
Chris Lattner5caa3702009-05-08 06:58:22 +0000324/// SemaBuiltinAtomicOverloaded - We have a call to a function like
325/// __sync_fetch_and_add, which is an overloaded function based on the pointer
326/// type of its first argument. The main ActOnCallExpr routines have already
327/// promoted the types of arguments because all of these calls are prototyped as
328/// void(...).
329///
330/// This function goes through and does final semantic checking for these
331/// builtins,
332bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
333 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
334 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
335
336 // Ensure that we have at least one argument to do type inference from.
337 if (TheCall->getNumArgs() < 1)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000338 return Diag(TheCall->getLocEnd(),
339 diag::err_typecheck_call_too_few_args_at_least)
340 << 0 << 1 << TheCall->getNumArgs()
341 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Chris Lattner5caa3702009-05-08 06:58:22 +0000343 // Inspect the first argument of the atomic builtin. This should always be
344 // a pointer type, whose element is an integral scalar or pointer type.
345 // Because it is a pointer type, we don't have to worry about any implicit
346 // casts here.
347 Expr *FirstArg = TheCall->getArg(0);
348 if (!FirstArg->getType()->isPointerType())
349 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
350 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Ted Kremenek6217b802009-07-29 21:53:49 +0000352 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000353 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000354 !ValType->isBlockPointerType())
355 return Diag(DRE->getLocStart(),
356 diag::err_atomic_builtin_must_be_pointer_intptr)
357 << FirstArg->getType() << FirstArg->getSourceRange();
358
359 // We need to figure out which concrete builtin this maps onto. For example,
360 // __sync_fetch_and_add with a 2 byte object turns into
361 // __sync_fetch_and_add_2.
362#define BUILTIN_ROW(x) \
363 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
364 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Chris Lattner5caa3702009-05-08 06:58:22 +0000366 static const unsigned BuiltinIndices[][5] = {
367 BUILTIN_ROW(__sync_fetch_and_add),
368 BUILTIN_ROW(__sync_fetch_and_sub),
369 BUILTIN_ROW(__sync_fetch_and_or),
370 BUILTIN_ROW(__sync_fetch_and_and),
371 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Chris Lattner5caa3702009-05-08 06:58:22 +0000373 BUILTIN_ROW(__sync_add_and_fetch),
374 BUILTIN_ROW(__sync_sub_and_fetch),
375 BUILTIN_ROW(__sync_and_and_fetch),
376 BUILTIN_ROW(__sync_or_and_fetch),
377 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Chris Lattner5caa3702009-05-08 06:58:22 +0000379 BUILTIN_ROW(__sync_val_compare_and_swap),
380 BUILTIN_ROW(__sync_bool_compare_and_swap),
381 BUILTIN_ROW(__sync_lock_test_and_set),
382 BUILTIN_ROW(__sync_lock_release)
383 };
Mike Stump1eb44332009-09-09 15:08:12 +0000384#undef BUILTIN_ROW
385
Chris Lattner5caa3702009-05-08 06:58:22 +0000386 // Determine the index of the size.
387 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000388 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000389 case 1: SizeIndex = 0; break;
390 case 2: SizeIndex = 1; break;
391 case 4: SizeIndex = 2; break;
392 case 8: SizeIndex = 3; break;
393 case 16: SizeIndex = 4; break;
394 default:
395 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
396 << FirstArg->getType() << FirstArg->getSourceRange();
397 }
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Chris Lattner5caa3702009-05-08 06:58:22 +0000399 // Each of these builtins has one pointer argument, followed by some number of
400 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
401 // that we ignore. Find out which row of BuiltinIndices to read from as well
402 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000403 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000404 unsigned BuiltinIndex, NumFixed = 1;
405 switch (BuiltinID) {
406 default: assert(0 && "Unknown overloaded atomic builtin!");
407 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
408 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
409 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
410 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
411 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000413 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
414 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
415 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
416 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
417 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattner5caa3702009-05-08 06:58:22 +0000419 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000420 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000421 NumFixed = 2;
422 break;
423 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000424 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000425 NumFixed = 2;
426 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000427 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000428 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000429 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000430 NumFixed = 0;
431 break;
432 }
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattner5caa3702009-05-08 06:58:22 +0000434 // Now that we know how many fixed arguments we expect, first check that we
435 // have at least that many.
436 if (TheCall->getNumArgs() < 1+NumFixed)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000437 return Diag(TheCall->getLocEnd(),
438 diag::err_typecheck_call_too_few_args_at_least)
439 << 0 << 1+NumFixed << TheCall->getNumArgs()
440 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000441
442
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000443 // Get the decl for the concrete builtin from this, we can tell what the
444 // concrete integer type we should convert to is.
445 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
446 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
447 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000448 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000449 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
450 TUScope, false, DRE->getLocStart()));
451 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000452 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000453 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000455 // If the first type needs to be converted (e.g. void** -> int*), do it now.
456 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000457 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000458 TheCall->setArg(0, FirstArg);
459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattner5caa3702009-05-08 06:58:22 +0000461 // Next, walk the valid ones promoting to the right type.
462 for (unsigned i = 0; i != NumFixed; ++i) {
463 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Chris Lattner5caa3702009-05-08 06:58:22 +0000465 // If the argument is an implicit cast, then there was a promotion due to
466 // "...", just remove it now.
467 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
468 Arg = ICE->getSubExpr();
469 ICE->setSubExpr(0);
470 ICE->Destroy(Context);
471 TheCall->setArg(i+1, Arg);
472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Chris Lattner5caa3702009-05-08 06:58:22 +0000474 // GCC does an implicit conversion to the pointer or integer ValType. This
475 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000476 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000477 CXXBaseSpecifierArray BasePath;
478 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, BasePath))
Chris Lattner5caa3702009-05-08 06:58:22 +0000479 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattner5caa3702009-05-08 06:58:22 +0000481 // Okay, we have something that *can* be converted to the right type. Check
482 // to see if there is a potentially weird extension going on here. This can
483 // happen when you do an atomic operation on something like an char* and
484 // pass in 42. The 42 gets converted to char. This is even more strange
485 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000486 // FIXME: Do this check.
Anders Carlsson80971bd2010-04-24 16:36:20 +0000487 ImpCastExprToType(Arg, ValType, Kind);
Chris Lattner5caa3702009-05-08 06:58:22 +0000488 TheCall->setArg(i+1, Arg);
489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Chris Lattner5caa3702009-05-08 06:58:22 +0000491 // Switch the DeclRefExpr to refer to the new decl.
492 DRE->setDecl(NewBuiltinDecl);
493 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Chris Lattner5caa3702009-05-08 06:58:22 +0000495 // Set the callee in the CallExpr.
496 // FIXME: This leaks the original parens and implicit casts.
497 Expr *PromotedCall = DRE;
498 UsualUnaryConversions(PromotedCall);
499 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Chris Lattner5caa3702009-05-08 06:58:22 +0000501
502 // Change the result type of the call to match the result type of the decl.
503 TheCall->setType(NewBuiltinDecl->getResultType());
504 return false;
505}
506
507
Chris Lattner69039812009-02-18 06:01:06 +0000508/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000509/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000510/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000511/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000512/// belong to the input codeset UTF-8"
513/// Note: It might also make sense to do the UTF-16 conversion here (would
514/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000515bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000516 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000517 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
518
519 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000520 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
521 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000522 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000523 }
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Daniel Dunbarf015b032009-09-22 10:03:52 +0000525 const char *Data = Literal->getStrData();
526 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Daniel Dunbarf015b032009-09-22 10:03:52 +0000528 for (unsigned i = 0; i < Length; ++i) {
529 if (!Data[i]) {
530 Diag(getLocationOfStringLiteralByte(Literal, i),
531 diag::warn_cfstring_literal_contains_nul_character)
532 << Arg->getSourceRange();
533 break;
534 }
535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000537 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000538}
539
Chris Lattnerc27c6652007-12-20 00:05:45 +0000540/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
541/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000542bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
543 Expr *Fn = TheCall->getCallee();
544 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000545 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000546 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000547 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
548 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000549 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000550 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000551 return true;
552 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000553
554 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000555 return Diag(TheCall->getLocEnd(),
556 diag::err_typecheck_call_too_few_args_at_least)
557 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000558 }
559
Chris Lattnerc27c6652007-12-20 00:05:45 +0000560 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000561 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000562 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000563 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000564 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000565 else if (FunctionDecl *FD = getCurFunctionDecl())
566 isVariadic = FD->isVariadic();
567 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000568 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattnerc27c6652007-12-20 00:05:45 +0000570 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000571 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
572 return true;
573 }
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Chris Lattner30ce3442007-12-19 23:59:04 +0000575 // Verify that the second argument to the builtin is the last argument of the
576 // current function or method.
577 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000578 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Anders Carlsson88cf2262008-02-11 04:20:54 +0000580 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
581 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000582 // FIXME: This isn't correct for methods (results in bogus warning).
583 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000584 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000585 if (CurBlock)
586 LastArg = *(CurBlock->TheDecl->param_end()-1);
587 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000588 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000589 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000590 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000591 SecondArgIsLastNamedArgument = PV == LastArg;
592 }
593 }
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Chris Lattner30ce3442007-12-19 23:59:04 +0000595 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000596 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000597 diag::warn_second_parameter_of_va_start_not_last_named_argument);
598 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000599}
Chris Lattner30ce3442007-12-19 23:59:04 +0000600
Chris Lattner1b9a0792007-12-20 00:26:33 +0000601/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
602/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000603bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
604 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000605 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000606 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000607 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000608 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000609 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000610 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000611 << SourceRange(TheCall->getArg(2)->getLocStart(),
612 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Chris Lattner925e60d2007-12-28 05:29:59 +0000614 Expr *OrigArg0 = TheCall->getArg(0);
615 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000616
Chris Lattner1b9a0792007-12-20 00:26:33 +0000617 // Do standard promotions between the two arguments, returning their common
618 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000619 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000620
621 // Make sure any conversions are pushed back into the call; this is
622 // type safe since unordered compare builtins are declared as "_Bool
623 // foo(...)".
624 TheCall->setArg(0, OrigArg0);
625 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Douglas Gregorcde01732009-05-19 22:10:17 +0000627 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
628 return false;
629
Chris Lattner1b9a0792007-12-20 00:26:33 +0000630 // If the common type isn't a real floating type, then the arguments were
631 // invalid for this operation.
632 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000633 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000634 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000635 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000636 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattner1b9a0792007-12-20 00:26:33 +0000638 return false;
639}
640
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000641/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
642/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000643/// to check everything. We expect the last argument to be a floating point
644/// value.
645bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
646 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000647 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000648 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000649 if (TheCall->getNumArgs() > NumArgs)
650 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000651 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000652 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000653 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000654 (*(TheCall->arg_end()-1))->getLocEnd());
655
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000656 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Eli Friedman9ac6f622009-08-31 20:06:00 +0000658 if (OrigArg->isTypeDependent())
659 return false;
660
Chris Lattner81368fb2010-05-06 05:50:07 +0000661 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000662 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000663 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000664 diag::err_typecheck_call_invalid_unary_fp)
665 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattner81368fb2010-05-06 05:50:07 +0000667 // If this is an implicit conversion from float -> double, remove it.
668 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
669 Expr *CastArg = Cast->getSubExpr();
670 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
671 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
672 "promotion from float to double is the only expected cast here");
673 Cast->setSubExpr(0);
674 Cast->Destroy(Context);
675 TheCall->setArg(NumArgs-1, CastArg);
676 OrigArg = CastArg;
677 }
678 }
679
Eli Friedman9ac6f622009-08-31 20:06:00 +0000680 return false;
681}
682
Eli Friedmand38617c2008-05-14 19:38:39 +0000683/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
684// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000685Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000686 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000687 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000688 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000689 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000690 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000691
Nate Begeman37b6a572010-06-08 00:16:34 +0000692 // Determine which of the following types of shufflevector we're checking:
693 // 1) unary, vector mask: (lhs, mask)
694 // 2) binary, vector mask: (lhs, rhs, mask)
695 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
696 QualType resType = TheCall->getArg(0)->getType();
697 unsigned numElements = 0;
698
Douglas Gregorcde01732009-05-19 22:10:17 +0000699 if (!TheCall->getArg(0)->isTypeDependent() &&
700 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000701 QualType LHSType = TheCall->getArg(0)->getType();
702 QualType RHSType = TheCall->getArg(1)->getType();
703
704 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000705 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000706 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000707 TheCall->getArg(1)->getLocEnd());
708 return ExprError();
709 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000710
711 numElements = LHSType->getAs<VectorType>()->getNumElements();
712 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Nate Begeman37b6a572010-06-08 00:16:34 +0000714 // Check to see if we have a call with 2 vector arguments, the unary shuffle
715 // with mask. If so, verify that RHS is an integer vector type with the
716 // same number of elts as lhs.
717 if (TheCall->getNumArgs() == 2) {
718 if (!RHSType->isIntegerType() ||
719 RHSType->getAs<VectorType>()->getNumElements() != numElements)
720 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
721 << SourceRange(TheCall->getArg(1)->getLocStart(),
722 TheCall->getArg(1)->getLocEnd());
723 numResElements = numElements;
724 }
725 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000726 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000727 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000728 TheCall->getArg(1)->getLocEnd());
729 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000730 } else if (numElements != numResElements) {
731 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
732 resType = Context.getVectorType(eltType, numResElements, false, false);
Douglas Gregorcde01732009-05-19 22:10:17 +0000733 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000734 }
735
736 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000737 if (TheCall->getArg(i)->isTypeDependent() ||
738 TheCall->getArg(i)->isValueDependent())
739 continue;
740
Nate Begeman37b6a572010-06-08 00:16:34 +0000741 llvm::APSInt Result(32);
742 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
743 return ExprError(Diag(TheCall->getLocStart(),
744 diag::err_shufflevector_nonconstant_argument)
745 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000746
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000747 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000748 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000749 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000750 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000751 }
752
753 llvm::SmallVector<Expr*, 32> exprs;
754
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000755 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000756 exprs.push_back(TheCall->getArg(i));
757 TheCall->setArg(i, 0);
758 }
759
Nate Begemana88dc302009-08-12 02:10:25 +0000760 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000761 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000762 TheCall->getCallee()->getLocStart(),
763 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000764}
Chris Lattner30ce3442007-12-19 23:59:04 +0000765
Daniel Dunbar4493f792008-07-21 22:59:13 +0000766/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
767// This is declared to take (const void*, ...) and can take two
768// optional constant int args.
769bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000770 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000771
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000772 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000773 return Diag(TheCall->getLocEnd(),
774 diag::err_typecheck_call_too_many_args_at_most)
775 << 0 /*function call*/ << 3 << NumArgs
776 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000777
778 // Argument 0 is checked for us and the remaining arguments must be
779 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000780 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000781 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000782
Eli Friedman9aef7262009-12-04 00:30:06 +0000783 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000784 if (SemaBuiltinConstantArg(TheCall, i, Result))
785 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Daniel Dunbar4493f792008-07-21 22:59:13 +0000787 // FIXME: gcc issues a warning and rewrites these to 0. These
788 // seems especially odd for the third argument since the default
789 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000790 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000791 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000792 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000793 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000794 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000795 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000796 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000797 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000798 }
799 }
800
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000801 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000802}
803
Eric Christopher691ebc32010-04-17 02:26:23 +0000804/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
805/// TheCall is a constant expression.
806bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
807 llvm::APSInt &Result) {
808 Expr *Arg = TheCall->getArg(ArgNum);
809 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
810 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
811
812 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
813
814 if (!Arg->isIntegerConstantExpr(Result, Context))
815 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000816 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000817
Chris Lattner21fb98e2009-09-23 06:06:36 +0000818 return false;
819}
820
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000821/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
822/// int type). This simply type checks that type is one of the defined
823/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000824// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000825bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000826 llvm::APSInt Result;
827
828 // Check constant-ness first.
829 if (SemaBuiltinConstantArg(TheCall, 1, Result))
830 return true;
831
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000832 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000833 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000834 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
835 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000836 }
837
838 return false;
839}
840
Eli Friedman586d6a82009-05-03 06:04:26 +0000841/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000842/// This checks that val is a constant 1.
843bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
844 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000845 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000846
Eric Christopher691ebc32010-04-17 02:26:23 +0000847 // TODO: This is less than ideal. Overload this to take a value.
848 if (SemaBuiltinConstantArg(TheCall, 1, Result))
849 return true;
850
851 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000852 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
853 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
854
855 return false;
856}
857
Ted Kremenekd30ef872009-01-12 23:09:09 +0000858// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000859bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
860 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000861 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000862 if (E->isTypeDependent() || E->isValueDependent())
863 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000864
865 switch (E->getStmtClass()) {
866 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000867 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000868 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000869 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000870 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000871 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000872 }
873
874 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000875 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000876 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000877 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000878 }
879
880 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000881 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000882 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000883 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000884 }
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Ted Kremenek082d9362009-03-20 21:35:28 +0000886 case Stmt::DeclRefExprClass: {
887 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Ted Kremenek082d9362009-03-20 21:35:28 +0000889 // As an exception, do not flag errors for variables binding to
890 // const string literals.
891 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
892 bool isConstant = false;
893 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000894
Ted Kremenek082d9362009-03-20 21:35:28 +0000895 if (const ArrayType *AT = Context.getAsArrayType(T)) {
896 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000897 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000898 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000899 PT->getPointeeType().isConstant(Context);
900 }
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Ted Kremenek082d9362009-03-20 21:35:28 +0000902 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000903 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000904 return SemaCheckStringLiteral(Init, TheCall,
905 HasVAListArg, format_idx, firstDataArg);
906 }
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Anders Carlssond966a552009-06-28 19:55:58 +0000908 // For vprintf* functions (i.e., HasVAListArg==true), we add a
909 // special check to see if the format string is a function parameter
910 // of the function calling the printf function. If the function
911 // has an attribute indicating it is a printf-like function, then we
912 // should suppress warnings concerning non-literals being used in a call
913 // to a vprintf function. For example:
914 //
915 // void
916 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
917 // va_list ap;
918 // va_start(ap, fmt);
919 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
920 // ...
921 //
922 //
923 // FIXME: We don't have full attribute support yet, so just check to see
924 // if the argument is a DeclRefExpr that references a parameter. We'll
925 // add proper support for checking the attribute later.
926 if (HasVAListArg)
927 if (isa<ParmVarDecl>(VD))
928 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000929 }
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Ted Kremenek082d9362009-03-20 21:35:28 +0000931 return false;
932 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000933
Anders Carlsson8f031b32009-06-27 04:05:33 +0000934 case Stmt::CallExprClass: {
935 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000936 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000937 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
938 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
939 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000940 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000941 unsigned ArgIndex = FA->getFormatIdx();
942 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000943
944 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000945 format_idx, firstDataArg);
946 }
947 }
948 }
949 }
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Anders Carlsson8f031b32009-06-27 04:05:33 +0000951 return false;
952 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000953 case Stmt::ObjCStringLiteralClass:
954 case Stmt::StringLiteralClass: {
955 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Ted Kremenek082d9362009-03-20 21:35:28 +0000957 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000958 StrE = ObjCFExpr->getString();
959 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000960 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Ted Kremenekd30ef872009-01-12 23:09:09 +0000962 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000963 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000964 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000965 return true;
966 }
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Ted Kremenekd30ef872009-01-12 23:09:09 +0000968 return false;
969 }
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Ted Kremenek082d9362009-03-20 21:35:28 +0000971 default:
972 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000973 }
974}
975
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000976void
Mike Stump1eb44332009-09-09 15:08:12 +0000977Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
978 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000979 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
980 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000981 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000982 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +0000983 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000984 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
985 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000986 }
987}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000988
Chris Lattner59907c42007-08-10 20:18:51 +0000989/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000990/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000991///
992/// HasVAListArg - A predicate indicating whether the printf-like
993/// function is passed an explicit va_arg argument (e.g., vprintf)
994///
995/// format_idx - The index into Args for the format string.
996///
997/// Improper format strings to functions in the printf family can be
998/// the source of bizarre bugs and very serious security holes. A
999/// good source of information is available in the following paper
1000/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +00001001///
1002/// FormatGuard: Automatic Protection From printf Format String
1003/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +00001004///
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001005/// TODO:
Ted Kremenek71895b92007-08-14 17:39:48 +00001006/// Functionality implemented:
1007///
1008/// We can statically check the following properties for string
1009/// literal format strings for non v.*printf functions (where the
1010/// arguments are passed directly):
1011//
1012/// (1) Are the number of format conversions equal to the number of
1013/// data arguments?
1014///
1015/// (2) Does each format conversion correctly match the type of the
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001016/// corresponding data argument?
Ted Kremenek71895b92007-08-14 17:39:48 +00001017///
1018/// Moreover, for all printf functions we can:
1019///
1020/// (3) Check for a missing format string (when not caught by type checking).
1021///
1022/// (4) Check for no-operation flags; e.g. using "#" with format
1023/// conversion 'c' (TODO)
1024///
1025/// (5) Check the use of '%n', a major source of security holes.
1026///
1027/// (6) Check for malformed format conversions that don't specify anything.
1028///
1029/// (7) Check for empty format strings. e.g: printf("");
1030///
1031/// (8) Check that the format string is a wide literal.
1032///
1033/// All of these checks can be done by parsing the format string.
1034///
Chris Lattner59907c42007-08-10 20:18:51 +00001035void
Mike Stump1eb44332009-09-09 15:08:12 +00001036Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +00001037 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +00001038 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001039
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001040 // The way the format attribute works in GCC, the implicit this argument
1041 // of member functions is counted. However, it doesn't appear in our own
1042 // lists, so decrement format_idx in that case.
1043 if (isa<CXXMemberCallExpr>(TheCall)) {
1044 // Catch a format attribute mistakenly referring to the object argument.
1045 if (format_idx == 0)
1046 return;
1047 --format_idx;
1048 if(firstDataArg != 0)
1049 --firstDataArg;
1050 }
1051
Mike Stump1eb44332009-09-09 15:08:12 +00001052 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001053 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001054 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1055 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001056 return;
1057 }
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Ted Kremenek082d9362009-03-20 21:35:28 +00001059 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001060
Chris Lattner59907c42007-08-10 20:18:51 +00001061 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001062 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001063 // Dynamically generated format strings are difficult to
1064 // automatically vet at compile time. Requiring that format strings
1065 // are string literals: (1) permits the checking of format strings by
1066 // the compiler and thereby (2) can practically remove the source of
1067 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001068
Mike Stump1eb44332009-09-09 15:08:12 +00001069 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001070 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001071 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001072 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001073 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1074 firstDataArg))
1075 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001076
Chris Lattner655f1412009-04-29 04:59:47 +00001077 // If there are no arguments specified, warn with -Wformat-security, otherwise
1078 // warn only with -Wformat-nonliteral.
1079 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001080 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001081 diag::warn_printf_nonliteral_noargs)
1082 << OrigFormatExpr->getSourceRange();
1083 else
Mike Stump1eb44332009-09-09 15:08:12 +00001084 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001085 diag::warn_printf_nonliteral)
1086 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001087}
Ted Kremenek71895b92007-08-14 17:39:48 +00001088
Ted Kremeneke0e53132010-01-28 23:39:18 +00001089namespace {
Ted Kremenek74d56a12010-02-04 20:46:58 +00001090class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001091 Sema &S;
1092 const StringLiteral *FExpr;
1093 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001094 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001095 const unsigned NumDataArgs;
1096 const bool IsObjCLiteral;
1097 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001098 const bool HasVAListArg;
1099 const CallExpr *TheCall;
1100 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001101 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001102 bool usesPositionalArgs;
1103 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001104public:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001105 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001106 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001107 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001108 const char *beg, bool hasVAListArg,
1109 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001110 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001111 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001112 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001113 IsObjCLiteral(isObjCLiteral), Beg(beg),
1114 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001115 TheCall(theCall), FormatIdx(formatIdx),
1116 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001117 CoveredArgs.resize(numDataArgs);
1118 CoveredArgs.reset();
1119 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001120
Ted Kremenek07d161f2010-01-29 01:50:07 +00001121 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001122
Ted Kremenek808015a2010-01-29 03:16:21 +00001123 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1124 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001125
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001126 bool
Ted Kremenek74d56a12010-02-04 20:46:58 +00001127 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1128 const char *startSpecifier,
1129 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001130
Ted Kremenekefaff192010-02-27 01:41:03 +00001131 virtual void HandleInvalidPosition(const char *startSpecifier,
1132 unsigned specifierLen,
1133 analyze_printf::PositionContext p);
1134
1135 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1136
Ted Kremeneke0e53132010-01-28 23:39:18 +00001137 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001138
Ted Kremeneke0e53132010-01-28 23:39:18 +00001139 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1140 const char *startSpecifier,
1141 unsigned specifierLen);
1142private:
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001143 SourceRange getFormatStringRange();
1144 SourceRange getFormatSpecifierRange(const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001145 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001146 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001147
Ted Kremenekefaff192010-02-27 01:41:03 +00001148 bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k,
1149 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001150 void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1151 llvm::StringRef flag, llvm::StringRef cspec,
1152 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001153
Ted Kremenek0d277352010-01-29 01:06:55 +00001154 const Expr *getDataArg(unsigned i) const;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001155};
1156}
1157
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001158SourceRange CheckPrintfHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001159 return OrigFormatExpr->getSourceRange();
1160}
1161
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001162SourceRange CheckPrintfHandler::
1163getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1164 return SourceRange(getLocationOfByte(startSpecifier),
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001165 getLocationOfByte(startSpecifier+specifierLen-1));
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001166}
1167
Ted Kremeneke0e53132010-01-28 23:39:18 +00001168SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001169 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001170}
1171
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001172void CheckPrintfHandler::
Ted Kremenek808015a2010-01-29 03:16:21 +00001173HandleIncompleteFormatSpecifier(const char *startSpecifier,
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001174 unsigned specifierLen) {
Ted Kremenek808015a2010-01-29 03:16:21 +00001175 SourceLocation Loc = getLocationOfByte(startSpecifier);
1176 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001177 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001178}
1179
Ted Kremenekefaff192010-02-27 01:41:03 +00001180void
1181CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1182 analyze_printf::PositionContext p) {
1183 SourceLocation Loc = getLocationOfByte(startPos);
1184 S.Diag(Loc, diag::warn_printf_invalid_positional_specifier)
1185 << (unsigned) p << getFormatSpecifierRange(startPos, posLen);
1186}
1187
1188void CheckPrintfHandler::HandleZeroPosition(const char *startPos,
1189 unsigned posLen) {
1190 SourceLocation Loc = getLocationOfByte(startPos);
1191 S.Diag(Loc, diag::warn_printf_zero_positional_specifier)
1192 << getFormatSpecifierRange(startPos, posLen);
1193}
1194
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001195bool CheckPrintfHandler::
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001196HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1197 const char *startSpecifier,
1198 unsigned specifierLen) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001199
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001200 unsigned argIndex = FS.getArgIndex();
1201 bool keepGoing = true;
1202 if (argIndex < NumDataArgs) {
1203 // Consider the argument coverered, even though the specifier doesn't
1204 // make sense.
1205 CoveredArgs.set(argIndex);
1206 }
1207 else {
1208 // If argIndex exceeds the number of data arguments we
1209 // don't issue a warning because that is just a cascade of warnings (and
1210 // they may have intended '%%' anyway). We don't want to continue processing
1211 // the format string after this point, however, as we will like just get
1212 // gibberish when trying to match arguments.
1213 keepGoing = false;
1214 }
1215
Ted Kremenek808015a2010-01-29 03:16:21 +00001216 const analyze_printf::ConversionSpecifier &CS =
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001217 FS.getConversionSpecifier();
Ted Kremenek808015a2010-01-29 03:16:21 +00001218 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001219 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenek808015a2010-01-29 03:16:21 +00001220 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001221 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001222
1223 return keepGoing;
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001224}
1225
Ted Kremeneke0e53132010-01-28 23:39:18 +00001226void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1227 // The presence of a null character is likely an error.
1228 S.Diag(getLocationOfByte(nullCharacter),
1229 diag::warn_printf_format_string_contains_null_char)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001230 << getFormatStringRange();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001231}
1232
Ted Kremenek0d277352010-01-29 01:06:55 +00001233const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001234 return TheCall->getArg(FirstDataArg + i);
Ted Kremenek0d277352010-01-29 01:06:55 +00001235}
1236
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001237void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1238 llvm::StringRef flag,
1239 llvm::StringRef cspec,
1240 const char *startSpecifier,
1241 unsigned specifierLen) {
1242 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1243 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1244 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1245}
1246
Ted Kremenek0d277352010-01-29 01:06:55 +00001247bool
1248CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
Ted Kremenekefaff192010-02-27 01:41:03 +00001249 unsigned k, const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001250 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001251
1252 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001253 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001254 unsigned argIndex = Amt.getArgIndex();
1255 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001256 S.Diag(getLocationOfByte(Amt.getStart()),
1257 diag::warn_printf_asterisk_missing_arg)
1258 << k << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001259 // Don't do any more checking. We will just emit
1260 // spurious errors.
1261 return false;
1262 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001263
Ted Kremenek0d277352010-01-29 01:06:55 +00001264 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001265 // Although not in conformance with C99, we also allow the argument to be
1266 // an 'unsigned int' as that is a reasonably safe case. GCC also
1267 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001268 CoveredArgs.set(argIndex);
1269 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001270 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001271
1272 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1273 assert(ATR.isValid());
1274
1275 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001276 S.Diag(getLocationOfByte(Amt.getStart()),
1277 diag::warn_printf_asterisk_wrong_type)
1278 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001279 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001280 << getFormatSpecifierRange(startSpecifier, specifierLen)
1281 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001282 // Don't do any more checking. We will just emit
1283 // spurious errors.
1284 return false;
1285 }
1286 }
1287 }
1288 return true;
1289}
Ted Kremenek0d277352010-01-29 01:06:55 +00001290
Ted Kremeneke0e53132010-01-28 23:39:18 +00001291bool
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001292CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1293 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001294 const char *startSpecifier,
1295 unsigned specifierLen) {
1296
Ted Kremenekefaff192010-02-27 01:41:03 +00001297 using namespace analyze_printf;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001298 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1299
Ted Kremenekefaff192010-02-27 01:41:03 +00001300 if (atFirstArg) {
1301 atFirstArg = false;
1302 usesPositionalArgs = FS.usesPositionalArg();
1303 }
1304 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1305 // Cannot mix-and-match positional and non-positional arguments.
1306 S.Diag(getLocationOfByte(CS.getStart()),
1307 diag::warn_printf_mix_positional_nonpositional_args)
1308 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001309 return false;
1310 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001311
Ted Kremenekefaff192010-02-27 01:41:03 +00001312 // First check if the field width, precision, and conversion specifier
1313 // have matching data arguments.
1314 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1315 startSpecifier, specifierLen)) {
1316 return false;
1317 }
1318
1319 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1320 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001321 return false;
1322 }
1323
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001324 if (!CS.consumesDataArgument()) {
1325 // FIXME: Technically specifying a precision or field width here
1326 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001327 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001328 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001329
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001330 // Consume the argument.
1331 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001332 if (argIndex < NumDataArgs) {
1333 // The check to see if the argIndex is valid will come later.
1334 // We set the bit here because we may exit early from this
1335 // function if we encounter some other error.
1336 CoveredArgs.set(argIndex);
1337 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001338
1339 // Check for using an Objective-C specific conversion specifier
1340 // in a non-ObjC literal.
1341 if (!IsObjCLiteral && CS.isObjCArg()) {
1342 return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1343 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001344
Ted Kremeneke82d8042010-01-29 01:35:25 +00001345 // Are we using '%n'? Issue a warning about this being
1346 // a possible security issue.
1347 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1348 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001349 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001350 // Continue checking the other format specifiers.
1351 return true;
1352 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001353
1354 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1355 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001356 S.Diag(getLocationOfByte(CS.getStart()),
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001357 diag::warn_printf_nonsensical_precision)
1358 << CS.getCharacters()
1359 << getFormatSpecifierRange(startSpecifier, specifierLen);
1360 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001361 if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1362 CS.getKind() == ConversionSpecifier::CStrArg) {
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001363 // FIXME: Instead of using "0", "+", etc., eventually get them from
1364 // the FormatSpecifier.
1365 if (FS.hasLeadingZeros())
1366 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1367 if (FS.hasPlusPrefix())
1368 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1369 if (FS.hasSpacePrefix())
1370 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001371 }
1372
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001373 // The remaining checks depend on the data arguments.
1374 if (HasVAListArg)
1375 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001376
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001377 if (argIndex >= NumDataArgs) {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001378 if (FS.usesPositionalArg()) {
1379 S.Diag(getLocationOfByte(CS.getStart()),
1380 diag::warn_printf_positional_arg_exceeds_data_args)
1381 << (argIndex+1) << NumDataArgs
1382 << getFormatSpecifierRange(startSpecifier, specifierLen);
1383 }
1384 else {
1385 S.Diag(getLocationOfByte(CS.getStart()),
1386 diag::warn_printf_insufficient_data_args)
1387 << getFormatSpecifierRange(startSpecifier, specifierLen);
1388 }
1389
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001390 // Don't do any more checking.
1391 return false;
1392 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001393
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001394 // Now type check the data expression that matches the
1395 // format specifier.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001396 const Expr *Ex = getDataArg(argIndex);
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001397 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001398 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1399 // Check if we didn't match because of an implicit cast from a 'char'
1400 // or 'short' to an 'int'. This is done because printf is a varargs
1401 // function.
1402 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1403 if (ICE->getType() == S.Context.IntTy)
1404 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1405 return true;
Ted Kremenek105d41c2010-02-01 19:38:10 +00001406
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001407 S.Diag(getLocationOfByte(CS.getStart()),
1408 diag::warn_printf_conversion_argument_type_mismatch)
1409 << ATR.getRepresentativeType(S.Context) << Ex->getType()
Ted Kremenek1497bff2010-02-11 19:37:25 +00001410 << getFormatSpecifierRange(startSpecifier, specifierLen)
1411 << Ex->getSourceRange();
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001412 }
Ted Kremeneke0e53132010-01-28 23:39:18 +00001413
1414 return true;
1415}
1416
Ted Kremenek07d161f2010-01-29 01:50:07 +00001417void CheckPrintfHandler::DoneProcessing() {
1418 // Does the number of data arguments exceed the number of
1419 // format conversions in the format string?
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001420 if (!HasVAListArg) {
1421 // Find any arguments that weren't covered.
1422 CoveredArgs.flip();
1423 signed notCoveredArg = CoveredArgs.find_first();
1424 if (notCoveredArg >= 0) {
1425 assert((unsigned)notCoveredArg < NumDataArgs);
1426 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1427 diag::warn_printf_data_arg_not_used)
1428 << getFormatStringRange();
1429 }
1430 }
Ted Kremenek07d161f2010-01-29 01:50:07 +00001431}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001432
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001433void Sema::CheckPrintfString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001434 const Expr *OrigFormatExpr,
1435 const CallExpr *TheCall, bool HasVAListArg,
1436 unsigned format_idx, unsigned firstDataArg) {
1437
Ted Kremeneke0e53132010-01-28 23:39:18 +00001438 // CHECK: is the format string a wide literal?
1439 if (FExpr->isWide()) {
1440 Diag(FExpr->getLocStart(),
1441 diag::warn_printf_format_string_is_wide_literal)
1442 << OrigFormatExpr->getSourceRange();
1443 return;
1444 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001445
Ted Kremeneke0e53132010-01-28 23:39:18 +00001446 // Str - The format string. NOTE: this is NOT null-terminated!
1447 const char *Str = FExpr->getStrData();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001448
Ted Kremeneke0e53132010-01-28 23:39:18 +00001449 // CHECK: empty format string?
1450 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001451
Ted Kremeneke0e53132010-01-28 23:39:18 +00001452 if (StrLen == 0) {
1453 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1454 << OrigFormatExpr->getSourceRange();
1455 return;
1456 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001457
Ted Kremenek6ee76532010-03-25 03:59:12 +00001458 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001459 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek0d277352010-01-29 01:06:55 +00001460 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1461 HasVAListArg, TheCall, format_idx);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001462
Ted Kremenek74d56a12010-02-04 20:46:58 +00001463 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
Ted Kremenek808015a2010-01-29 03:16:21 +00001464 H.DoneProcessing();
Ted Kremenekce7024e2010-01-28 01:18:22 +00001465}
1466
Ted Kremenek06de2762007-08-17 16:46:58 +00001467//===--- CHECK: Return Address of Stack Variable --------------------------===//
1468
1469static DeclRefExpr* EvalVal(Expr *E);
1470static DeclRefExpr* EvalAddr(Expr* E);
1471
1472/// CheckReturnStackAddr - Check if a return statement returns the address
1473/// of a stack variable.
1474void
1475Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1476 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Ted Kremenek06de2762007-08-17 16:46:58 +00001478 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001479 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001480 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001481 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001482 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Steve Naroffc50a4a52008-09-16 22:25:10 +00001484 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001485 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001486
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001487 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001488 if (C->hasBlockDeclRefExprs())
1489 Diag(C->getLocStart(), diag::err_ret_local_block)
1490 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001491
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001492 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1493 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1494 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001495
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001496 } else if (lhsType->isReferenceType()) {
1497 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001498 // Check for a reference to the stack
1499 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001500 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001501 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001502 }
1503}
1504
1505/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1506/// check if the expression in a return statement evaluates to an address
1507/// to a location on the stack. The recursion is used to traverse the
1508/// AST of the return expression, with recursion backtracking when we
1509/// encounter a subexpression that (1) clearly does not lead to the address
1510/// of a stack variable or (2) is something we cannot determine leads to
1511/// the address of a stack variable based on such local checking.
1512///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001513/// EvalAddr processes expressions that are pointers that are used as
1514/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001515/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001516/// the refers to a stack variable.
1517///
1518/// This implementation handles:
1519///
1520/// * pointer-to-pointer casts
1521/// * implicit conversions from array references to pointers
1522/// * taking the address of fields
1523/// * arbitrary interplay between "&" and "*" operators
1524/// * pointer arithmetic from an address of a stack variable
1525/// * taking the address of an array element where the array is on the stack
1526static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001527 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001528 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001529 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001530 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001531 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Ted Kremenek06de2762007-08-17 16:46:58 +00001533 // Our "symbolic interpreter" is just a dispatch off the currently
1534 // viewed AST node. We then recursively traverse the AST by calling
1535 // EvalAddr and EvalVal appropriately.
1536 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001537 case Stmt::ParenExprClass:
1538 // Ignore parentheses.
1539 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001540
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001541 case Stmt::UnaryOperatorClass: {
1542 // The only unary operator that make sense to handle here
1543 // is AddrOf. All others don't make sense as pointers.
1544 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001546 if (U->getOpcode() == UnaryOperator::AddrOf)
1547 return EvalVal(U->getSubExpr());
1548 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001549 return NULL;
1550 }
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001552 case Stmt::BinaryOperatorClass: {
1553 // Handle pointer arithmetic. All other binary operators are not valid
1554 // in this context.
1555 BinaryOperator *B = cast<BinaryOperator>(E);
1556 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001558 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1559 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001561 Expr *Base = B->getLHS();
1562
1563 // Determine which argument is the real pointer base. It could be
1564 // the RHS argument instead of the LHS.
1565 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001567 assert (Base->getType()->isPointerType());
1568 return EvalAddr(Base);
1569 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001570
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001571 // For conditional operators we need to see if either the LHS or RHS are
1572 // valid DeclRefExpr*s. If one of them is valid, we return it.
1573 case Stmt::ConditionalOperatorClass: {
1574 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001576 // Handle the GNU extension for missing LHS.
1577 if (Expr *lhsExpr = C->getLHS())
1578 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1579 return LHS;
1580
1581 return EvalAddr(C->getRHS());
1582 }
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Ted Kremenek54b52742008-08-07 00:49:01 +00001584 // For casts, we need to handle conversions from arrays to
1585 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001586 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001587 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001588 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001589 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001590 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Steve Naroffdd972f22008-09-05 22:11:13 +00001592 if (SubExpr->getType()->isPointerType() ||
1593 SubExpr->getType()->isBlockPointerType() ||
1594 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001595 return EvalAddr(SubExpr);
1596 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001597 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001598 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001599 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001600 }
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001602 // C++ casts. For dynamic casts, static casts, and const casts, we
1603 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001604 // through the cast. In the case the dynamic cast doesn't fail (and
1605 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001606 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001607 // FIXME: The comment about is wrong; we're not always converting
1608 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001609 // handle references to objects.
1610 case Stmt::CXXStaticCastExprClass:
1611 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001612 case Stmt::CXXConstCastExprClass:
1613 case Stmt::CXXReinterpretCastExprClass: {
1614 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001615 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001616 return EvalAddr(S);
1617 else
1618 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001619 }
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001621 // Everything else: we simply don't reason about them.
1622 default:
1623 return NULL;
1624 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001625}
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Ted Kremenek06de2762007-08-17 16:46:58 +00001627
1628/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1629/// See the comments for EvalAddr for more details.
1630static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001632 // We should only be called for evaluating non-pointer expressions, or
1633 // expressions with a pointer type that are not used as references but instead
1634 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Ted Kremenek06de2762007-08-17 16:46:58 +00001636 // Our "symbolic interpreter" is just a dispatch off the currently
1637 // viewed AST node. We then recursively traverse the AST by calling
1638 // EvalAddr and EvalVal appropriately.
1639 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001640 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001641 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1642 // at code that refers to a variable's name. We check if it has local
1643 // storage within the function, and if so, return the expression.
1644 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001645
Ted Kremenek06de2762007-08-17 16:46:58 +00001646 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001647 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1648
Ted Kremenek06de2762007-08-17 16:46:58 +00001649 return NULL;
1650 }
Mike Stump1eb44332009-09-09 15:08:12 +00001651
Ted Kremenek06de2762007-08-17 16:46:58 +00001652 case Stmt::ParenExprClass:
1653 // Ignore parentheses.
1654 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Ted Kremenek06de2762007-08-17 16:46:58 +00001656 case Stmt::UnaryOperatorClass: {
1657 // The only unary operator that make sense to handle here
1658 // is Deref. All others don't resolve to a "name." This includes
1659 // handling all sorts of rvalues passed to a unary operator.
1660 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Ted Kremenek06de2762007-08-17 16:46:58 +00001662 if (U->getOpcode() == UnaryOperator::Deref)
1663 return EvalAddr(U->getSubExpr());
1664
1665 return NULL;
1666 }
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Ted Kremenek06de2762007-08-17 16:46:58 +00001668 case Stmt::ArraySubscriptExprClass: {
1669 // Array subscripts are potential references to data on the stack. We
1670 // retrieve the DeclRefExpr* for the array variable if it indeed
1671 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001672 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001673 }
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Ted Kremenek06de2762007-08-17 16:46:58 +00001675 case Stmt::ConditionalOperatorClass: {
1676 // For conditional operators we need to see if either the LHS or RHS are
1677 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1678 ConditionalOperator *C = cast<ConditionalOperator>(E);
1679
Anders Carlsson39073232007-11-30 19:04:31 +00001680 // Handle the GNU extension for missing LHS.
1681 if (Expr *lhsExpr = C->getLHS())
1682 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1683 return LHS;
1684
1685 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Ted Kremenek06de2762007-08-17 16:46:58 +00001688 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001689 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001690 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Ted Kremenek06de2762007-08-17 16:46:58 +00001692 // Check for indirect access. We only want direct field accesses.
1693 if (!M->isArrow())
1694 return EvalVal(M->getBase());
1695 else
1696 return NULL;
1697 }
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Ted Kremenek06de2762007-08-17 16:46:58 +00001699 // Everything else: we simply don't reason about them.
1700 default:
1701 return NULL;
1702 }
1703}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001704
1705//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1706
1707/// Check for comparisons of floating point operands using != and ==.
1708/// Issue a warning if these are no self-comparisons, as they are not likely
1709/// to do what the programmer intended.
1710void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1711 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001713 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001714 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001715
1716 // Special case: check for x == x (which is OK).
1717 // Do not emit warnings for such cases.
1718 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1719 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1720 if (DRL->getDecl() == DRR->getDecl())
1721 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001722
1723
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001724 // Special case: check for comparisons against literals that can be exactly
1725 // represented by APFloat. In such cases, do not emit a warning. This
1726 // is a heuristic: often comparison against such literals are used to
1727 // detect if a value in a variable has not changed. This clearly can
1728 // lead to false negatives.
1729 if (EmitWarning) {
1730 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1731 if (FLL->isExact())
1732 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001733 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001734 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1735 if (FLR->isExact())
1736 EmitWarning = false;
1737 }
1738 }
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001740 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001741 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001742 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001743 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001744 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Sebastian Redl0eb23302009-01-19 00:08:26 +00001746 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001747 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001748 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001749 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001751 // Emit the diagnostic.
1752 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001753 Diag(loc, diag::warn_floatingpoint_eq)
1754 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001755}
John McCallba26e582010-01-04 23:21:16 +00001756
John McCallf2370c92010-01-06 05:24:50 +00001757//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1758//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00001759
John McCallf2370c92010-01-06 05:24:50 +00001760namespace {
John McCallba26e582010-01-04 23:21:16 +00001761
John McCallf2370c92010-01-06 05:24:50 +00001762/// Structure recording the 'active' range of an integer-valued
1763/// expression.
1764struct IntRange {
1765 /// The number of bits active in the int.
1766 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00001767
John McCallf2370c92010-01-06 05:24:50 +00001768 /// True if the int is known not to have negative values.
1769 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00001770
John McCallf2370c92010-01-06 05:24:50 +00001771 IntRange() {}
1772 IntRange(unsigned Width, bool NonNegative)
1773 : Width(Width), NonNegative(NonNegative)
1774 {}
John McCallba26e582010-01-04 23:21:16 +00001775
John McCallf2370c92010-01-06 05:24:50 +00001776 // Returns the range of the bool type.
1777 static IntRange forBoolType() {
1778 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00001779 }
1780
John McCallf2370c92010-01-06 05:24:50 +00001781 // Returns the range of an integral type.
1782 static IntRange forType(ASTContext &C, QualType T) {
1783 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00001784 }
1785
John McCallf2370c92010-01-06 05:24:50 +00001786 // Returns the range of an integeral type based on its canonical
1787 // representation.
1788 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1789 assert(T->isCanonicalUnqualified());
1790
1791 if (const VectorType *VT = dyn_cast<VectorType>(T))
1792 T = VT->getElementType().getTypePtr();
1793 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1794 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00001795
1796 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
1797 EnumDecl *Enum = ET->getDecl();
1798 unsigned NumPositive = Enum->getNumPositiveBits();
1799 unsigned NumNegative = Enum->getNumNegativeBits();
1800
1801 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
1802 }
John McCallf2370c92010-01-06 05:24:50 +00001803
1804 const BuiltinType *BT = cast<BuiltinType>(T);
1805 assert(BT->isInteger());
1806
1807 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1808 }
1809
1810 // Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001811 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00001812 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00001813 L.NonNegative && R.NonNegative);
1814 }
1815
1816 // Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001817 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00001818 return IntRange(std::min(L.Width, R.Width),
1819 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00001820 }
1821};
1822
1823IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1824 if (value.isSigned() && value.isNegative())
1825 return IntRange(value.getMinSignedBits(), false);
1826
1827 if (value.getBitWidth() > MaxWidth)
1828 value.trunc(MaxWidth);
1829
1830 // isNonNegative() just checks the sign bit without considering
1831 // signedness.
1832 return IntRange(value.getActiveBits(), true);
1833}
1834
John McCall0acc3112010-01-06 22:57:21 +00001835IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00001836 unsigned MaxWidth) {
1837 if (result.isInt())
1838 return GetValueRange(C, result.getInt(), MaxWidth);
1839
1840 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00001841 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1842 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1843 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1844 R = IntRange::join(R, El);
1845 }
John McCallf2370c92010-01-06 05:24:50 +00001846 return R;
1847 }
1848
1849 if (result.isComplexInt()) {
1850 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1851 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1852 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00001853 }
1854
1855 // This can happen with lossless casts to intptr_t of "based" lvalues.
1856 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00001857 // FIXME: The only reason we need to pass the type in here is to get
1858 // the sign right on this one case. It would be nice if APValue
1859 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00001860 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00001861 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00001862}
John McCallf2370c92010-01-06 05:24:50 +00001863
1864/// Pseudo-evaluate the given integer expression, estimating the
1865/// range of values it might take.
1866///
1867/// \param MaxWidth - the width to which the value will be truncated
1868IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1869 E = E->IgnoreParens();
1870
1871 // Try a full evaluation first.
1872 Expr::EvalResult result;
1873 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00001874 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00001875
1876 // I think we only want to look through implicit casts here; if the
1877 // user has an explicit widening cast, we should treat the value as
1878 // being of the new, wider type.
1879 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1880 if (CE->getCastKind() == CastExpr::CK_NoOp)
1881 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1882
1883 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1884
John McCall60fad452010-01-06 22:07:33 +00001885 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1886 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1887 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1888
John McCallf2370c92010-01-06 05:24:50 +00001889 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00001890 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00001891 return OutputTypeRange;
1892
1893 IntRange SubRange
1894 = GetExprRange(C, CE->getSubExpr(),
1895 std::min(MaxWidth, OutputTypeRange.Width));
1896
1897 // Bail out if the subexpr's range is as wide as the cast type.
1898 if (SubRange.Width >= OutputTypeRange.Width)
1899 return OutputTypeRange;
1900
1901 // Otherwise, we take the smaller width, and we're non-negative if
1902 // either the output type or the subexpr is.
1903 return IntRange(SubRange.Width,
1904 SubRange.NonNegative || OutputTypeRange.NonNegative);
1905 }
1906
1907 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1908 // If we can fold the condition, just take that operand.
1909 bool CondResult;
1910 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1911 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1912 : CO->getFalseExpr(),
1913 MaxWidth);
1914
1915 // Otherwise, conservatively merge.
1916 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1917 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1918 return IntRange::join(L, R);
1919 }
1920
1921 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1922 switch (BO->getOpcode()) {
1923
1924 // Boolean-valued operations are single-bit and positive.
1925 case BinaryOperator::LAnd:
1926 case BinaryOperator::LOr:
1927 case BinaryOperator::LT:
1928 case BinaryOperator::GT:
1929 case BinaryOperator::LE:
1930 case BinaryOperator::GE:
1931 case BinaryOperator::EQ:
1932 case BinaryOperator::NE:
1933 return IntRange::forBoolType();
1934
John McCallc0cd21d2010-02-23 19:22:29 +00001935 // The type of these compound assignments is the type of the LHS,
1936 // so the RHS is not necessarily an integer.
1937 case BinaryOperator::MulAssign:
1938 case BinaryOperator::DivAssign:
1939 case BinaryOperator::RemAssign:
1940 case BinaryOperator::AddAssign:
1941 case BinaryOperator::SubAssign:
1942 return IntRange::forType(C, E->getType());
1943
John McCallf2370c92010-01-06 05:24:50 +00001944 // Operations with opaque sources are black-listed.
1945 case BinaryOperator::PtrMemD:
1946 case BinaryOperator::PtrMemI:
1947 return IntRange::forType(C, E->getType());
1948
John McCall60fad452010-01-06 22:07:33 +00001949 // Bitwise-and uses the *infinum* of the two source ranges.
1950 case BinaryOperator::And:
John McCallc0cd21d2010-02-23 19:22:29 +00001951 case BinaryOperator::AndAssign:
John McCall60fad452010-01-06 22:07:33 +00001952 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1953 GetExprRange(C, BO->getRHS(), MaxWidth));
1954
John McCallf2370c92010-01-06 05:24:50 +00001955 // Left shift gets black-listed based on a judgement call.
1956 case BinaryOperator::Shl:
John McCall3aae6092010-04-07 01:14:35 +00001957 // ...except that we want to treat '1 << (blah)' as logically
1958 // positive. It's an important idiom.
1959 if (IntegerLiteral *I
1960 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
1961 if (I->getValue() == 1) {
1962 IntRange R = IntRange::forType(C, E->getType());
1963 return IntRange(R.Width, /*NonNegative*/ true);
1964 }
1965 }
1966 // fallthrough
1967
John McCallc0cd21d2010-02-23 19:22:29 +00001968 case BinaryOperator::ShlAssign:
John McCallf2370c92010-01-06 05:24:50 +00001969 return IntRange::forType(C, E->getType());
1970
John McCall60fad452010-01-06 22:07:33 +00001971 // Right shift by a constant can narrow its left argument.
John McCallc0cd21d2010-02-23 19:22:29 +00001972 case BinaryOperator::Shr:
1973 case BinaryOperator::ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00001974 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1975
1976 // If the shift amount is a positive constant, drop the width by
1977 // that much.
1978 llvm::APSInt shift;
1979 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1980 shift.isNonNegative()) {
1981 unsigned zext = shift.getZExtValue();
1982 if (zext >= L.Width)
1983 L.Width = (L.NonNegative ? 0 : 1);
1984 else
1985 L.Width -= zext;
1986 }
1987
1988 return L;
1989 }
1990
1991 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00001992 case BinaryOperator::Comma:
1993 return GetExprRange(C, BO->getRHS(), MaxWidth);
1994
John McCall60fad452010-01-06 22:07:33 +00001995 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00001996 case BinaryOperator::Sub:
1997 if (BO->getLHS()->getType()->isPointerType())
1998 return IntRange::forType(C, E->getType());
1999 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002000
John McCallf2370c92010-01-06 05:24:50 +00002001 default:
2002 break;
2003 }
2004
2005 // Treat every other operator as if it were closed on the
2006 // narrowest type that encompasses both operands.
2007 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2008 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2009 return IntRange::join(L, R);
2010 }
2011
2012 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2013 switch (UO->getOpcode()) {
2014 // Boolean-valued operations are white-listed.
2015 case UnaryOperator::LNot:
2016 return IntRange::forBoolType();
2017
2018 // Operations with opaque sources are black-listed.
2019 case UnaryOperator::Deref:
2020 case UnaryOperator::AddrOf: // should be impossible
2021 case UnaryOperator::OffsetOf:
2022 return IntRange::forType(C, E->getType());
2023
2024 default:
2025 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2026 }
2027 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002028
2029 if (dyn_cast<OffsetOfExpr>(E)) {
2030 IntRange::forType(C, E->getType());
2031 }
John McCallf2370c92010-01-06 05:24:50 +00002032
2033 FieldDecl *BitField = E->getBitField();
2034 if (BitField) {
2035 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2036 unsigned BitWidth = BitWidthAP.getZExtValue();
2037
2038 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2039 }
2040
2041 return IntRange::forType(C, E->getType());
2042}
John McCall51313c32010-01-04 23:31:57 +00002043
John McCall323ed742010-05-06 08:58:33 +00002044IntRange GetExprRange(ASTContext &C, Expr *E) {
2045 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2046}
2047
John McCall51313c32010-01-04 23:31:57 +00002048/// Checks whether the given value, which currently has the given
2049/// source semantics, has the same value when coerced through the
2050/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002051bool IsSameFloatAfterCast(const llvm::APFloat &value,
2052 const llvm::fltSemantics &Src,
2053 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002054 llvm::APFloat truncated = value;
2055
2056 bool ignored;
2057 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2058 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2059
2060 return truncated.bitwiseIsEqual(value);
2061}
2062
2063/// Checks whether the given value, which currently has the given
2064/// source semantics, has the same value when coerced through the
2065/// target semantics.
2066///
2067/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002068bool IsSameFloatAfterCast(const APValue &value,
2069 const llvm::fltSemantics &Src,
2070 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002071 if (value.isFloat())
2072 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2073
2074 if (value.isVector()) {
2075 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2076 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2077 return false;
2078 return true;
2079 }
2080
2081 assert(value.isComplexFloat());
2082 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2083 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2084}
2085
John McCall323ed742010-05-06 08:58:33 +00002086void AnalyzeImplicitConversions(Sema &S, Expr *E);
2087
2088bool IsZero(Sema &S, Expr *E) {
2089 llvm::APSInt Value;
2090 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2091}
2092
2093void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
2094 BinaryOperator::Opcode op = E->getOpcode();
2095 if (op == BinaryOperator::LT && IsZero(S, E->getRHS())) {
2096 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2097 << "< 0" << "false"
2098 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2099 } else if (op == BinaryOperator::GE && IsZero(S, E->getRHS())) {
2100 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2101 << ">= 0" << "true"
2102 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2103 } else if (op == BinaryOperator::GT && IsZero(S, E->getLHS())) {
2104 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2105 << "0 >" << "false"
2106 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2107 } else if (op == BinaryOperator::LE && IsZero(S, E->getLHS())) {
2108 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2109 << "0 <=" << "true"
2110 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2111 }
2112}
2113
2114/// Analyze the operands of the given comparison. Implements the
2115/// fallback case from AnalyzeComparison.
2116void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
2117 AnalyzeImplicitConversions(S, E->getLHS());
2118 AnalyzeImplicitConversions(S, E->getRHS());
2119}
John McCall51313c32010-01-04 23:31:57 +00002120
John McCallba26e582010-01-04 23:21:16 +00002121/// \brief Implements -Wsign-compare.
2122///
2123/// \param lex the left-hand expression
2124/// \param rex the right-hand expression
2125/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002126/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002127void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2128 // The type the comparison is being performed in.
2129 QualType T = E->getLHS()->getType();
2130 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2131 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002132
John McCall323ed742010-05-06 08:58:33 +00002133 // We don't do anything special if this isn't an unsigned integral
2134 // comparison: we're only interested in integral comparisons, and
2135 // signed comparisons only happen in cases we don't care to warn about.
2136 if (!T->isUnsignedIntegerType())
2137 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002138
John McCall323ed742010-05-06 08:58:33 +00002139 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2140 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002141
John McCall323ed742010-05-06 08:58:33 +00002142 // Check to see if one of the (unmodified) operands is of different
2143 // signedness.
2144 Expr *signedOperand, *unsignedOperand;
2145 if (lex->getType()->isSignedIntegerType()) {
2146 assert(!rex->getType()->isSignedIntegerType() &&
2147 "unsigned comparison between two signed integer expressions?");
2148 signedOperand = lex;
2149 unsignedOperand = rex;
2150 } else if (rex->getType()->isSignedIntegerType()) {
2151 signedOperand = rex;
2152 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002153 } else {
John McCall323ed742010-05-06 08:58:33 +00002154 CheckTrivialUnsignedComparison(S, E);
2155 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002156 }
2157
John McCall323ed742010-05-06 08:58:33 +00002158 // Otherwise, calculate the effective range of the signed operand.
2159 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002160
John McCall323ed742010-05-06 08:58:33 +00002161 // Go ahead and analyze implicit conversions in the operands. Note
2162 // that we skip the implicit conversions on both sides.
2163 AnalyzeImplicitConversions(S, lex);
2164 AnalyzeImplicitConversions(S, rex);
John McCallba26e582010-01-04 23:21:16 +00002165
John McCall323ed742010-05-06 08:58:33 +00002166 // If the signed range is non-negative, -Wsign-compare won't fire,
2167 // but we should still check for comparisons which are always true
2168 // or false.
2169 if (signedRange.NonNegative)
2170 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002171
2172 // For (in)equality comparisons, if the unsigned operand is a
2173 // constant which cannot collide with a overflowed signed operand,
2174 // then reinterpreting the signed operand as unsigned will not
2175 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002176 if (E->isEqualityOp()) {
2177 unsigned comparisonWidth = S.Context.getIntWidth(T);
2178 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002179
John McCall323ed742010-05-06 08:58:33 +00002180 // We should never be unable to prove that the unsigned operand is
2181 // non-negative.
2182 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2183
2184 if (unsignedRange.Width < comparisonWidth)
2185 return;
2186 }
2187
2188 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2189 << lex->getType() << rex->getType()
2190 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002191}
2192
John McCall51313c32010-01-04 23:31:57 +00002193/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCall323ed742010-05-06 08:58:33 +00002194void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
John McCall51313c32010-01-04 23:31:57 +00002195 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2196}
2197
John McCall323ed742010-05-06 08:58:33 +00002198void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
2199 bool *ICContext = 0) {
2200 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002201
John McCall323ed742010-05-06 08:58:33 +00002202 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2203 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2204 if (Source == Target) return;
2205 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002206
2207 // Never diagnose implicit casts to bool.
2208 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2209 return;
2210
2211 // Strip vector types.
2212 if (isa<VectorType>(Source)) {
2213 if (!isa<VectorType>(Target))
John McCall323ed742010-05-06 08:58:33 +00002214 return DiagnoseImpCast(S, E, T, diag::warn_impcast_vector_scalar);
John McCall51313c32010-01-04 23:31:57 +00002215
2216 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2217 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2218 }
2219
2220 // Strip complex types.
2221 if (isa<ComplexType>(Source)) {
2222 if (!isa<ComplexType>(Target))
John McCall323ed742010-05-06 08:58:33 +00002223 return DiagnoseImpCast(S, E, T, diag::warn_impcast_complex_scalar);
John McCall51313c32010-01-04 23:31:57 +00002224
2225 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2226 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2227 }
2228
2229 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2230 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2231
2232 // If the source is floating point...
2233 if (SourceBT && SourceBT->isFloatingPoint()) {
2234 // ...and the target is floating point...
2235 if (TargetBT && TargetBT->isFloatingPoint()) {
2236 // ...then warn if we're dropping FP rank.
2237
2238 // Builtin FP kinds are ordered by increasing FP rank.
2239 if (SourceBT->getKind() > TargetBT->getKind()) {
2240 // Don't warn about float constants that are precisely
2241 // representable in the target type.
2242 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002243 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002244 // Value might be a float, a float vector, or a float complex.
2245 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002246 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2247 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002248 return;
2249 }
2250
John McCall323ed742010-05-06 08:58:33 +00002251 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002252 }
2253 return;
2254 }
2255
2256 // If the target is integral, always warn.
2257 if ((TargetBT && TargetBT->isInteger()))
2258 // TODO: don't warn for integer values?
John McCall323ed742010-05-06 08:58:33 +00002259 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_integer);
John McCall51313c32010-01-04 23:31:57 +00002260
2261 return;
2262 }
2263
John McCallf2370c92010-01-06 05:24:50 +00002264 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002265 return;
2266
John McCall323ed742010-05-06 08:58:33 +00002267 IntRange SourceRange = GetExprRange(S.Context, E);
2268 IntRange TargetRange = IntRange::forCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002269
2270 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002271 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2272 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002273 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall323ed742010-05-06 08:58:33 +00002274 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_64_32);
2275 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_precision);
2276 }
2277
2278 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2279 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2280 SourceRange.Width == TargetRange.Width)) {
2281 unsigned DiagID = diag::warn_impcast_integer_sign;
2282
2283 // Traditionally, gcc has warned about this under -Wsign-compare.
2284 // We also want to warn about it in -Wconversion.
2285 // So if -Wconversion is off, use a completely identical diagnostic
2286 // in the sign-compare group.
2287 // The conditional-checking code will
2288 if (ICContext) {
2289 DiagID = diag::warn_impcast_integer_sign_conditional;
2290 *ICContext = true;
2291 }
2292
2293 return DiagnoseImpCast(S, E, T, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002294 }
2295
2296 return;
2297}
2298
John McCall323ed742010-05-06 08:58:33 +00002299void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2300
2301void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
2302 bool &ICContext) {
2303 E = E->IgnoreParenImpCasts();
2304
2305 if (isa<ConditionalOperator>(E))
2306 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2307
2308 AnalyzeImplicitConversions(S, E);
2309 if (E->getType() != T)
2310 return CheckImplicitConversion(S, E, T, &ICContext);
2311 return;
2312}
2313
2314void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
2315 AnalyzeImplicitConversions(S, E->getCond());
2316
2317 bool Suspicious = false;
2318 CheckConditionalOperand(S, E->getTrueExpr(), T, Suspicious);
2319 CheckConditionalOperand(S, E->getFalseExpr(), T, Suspicious);
2320
2321 // If -Wconversion would have warned about either of the candidates
2322 // for a signedness conversion to the context type...
2323 if (!Suspicious) return;
2324
2325 // ...but it's currently ignored...
2326 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional))
2327 return;
2328
2329 // ...and -Wsign-compare isn't...
2330 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional))
2331 return;
2332
2333 // ...then check whether it would have warned about either of the
2334 // candidates for a signedness conversion to the condition type.
2335 if (E->getType() != T) {
2336 Suspicious = false;
2337 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
2338 E->getType(), &Suspicious);
2339 if (!Suspicious)
2340 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
2341 E->getType(), &Suspicious);
2342 if (!Suspicious)
2343 return;
2344 }
2345
2346 // If so, emit a diagnostic under -Wsign-compare.
2347 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2348 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2349 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2350 << lex->getType() << rex->getType()
2351 << lex->getSourceRange() << rex->getSourceRange();
2352}
2353
2354/// AnalyzeImplicitConversions - Find and report any interesting
2355/// implicit conversions in the given expression. There are a couple
2356/// of competing diagnostics here, -Wconversion and -Wsign-compare.
2357void AnalyzeImplicitConversions(Sema &S, Expr *OrigE) {
2358 QualType T = OrigE->getType();
2359 Expr *E = OrigE->IgnoreParenImpCasts();
2360
2361 // For conditional operators, we analyze the arguments as if they
2362 // were being fed directly into the output.
2363 if (isa<ConditionalOperator>(E)) {
2364 ConditionalOperator *CO = cast<ConditionalOperator>(E);
2365 CheckConditionalOperator(S, CO, T);
2366 return;
2367 }
2368
2369 // Go ahead and check any implicit conversions we might have skipped.
2370 // The non-canonical typecheck is just an optimization;
2371 // CheckImplicitConversion will filter out dead implicit conversions.
2372 if (E->getType() != T)
2373 CheckImplicitConversion(S, E, T);
2374
2375 // Now continue drilling into this expression.
2376
2377 // Skip past explicit casts.
2378 if (isa<ExplicitCastExpr>(E)) {
2379 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
2380 return AnalyzeImplicitConversions(S, E);
2381 }
2382
2383 // Do a somewhat different check with comparison operators.
2384 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isComparisonOp())
2385 return AnalyzeComparison(S, cast<BinaryOperator>(E));
2386
2387 // These break the otherwise-useful invariant below. Fortunately,
2388 // we don't really need to recurse into them, because any internal
2389 // expressions should have been analyzed already when they were
2390 // built into statements.
2391 if (isa<StmtExpr>(E)) return;
2392
2393 // Don't descend into unevaluated contexts.
2394 if (isa<SizeOfAlignOfExpr>(E)) return;
2395
2396 // Now just recurse over the expression's children.
2397 for (Stmt::child_iterator I = E->child_begin(), IE = E->child_end();
2398 I != IE; ++I)
2399 AnalyzeImplicitConversions(S, cast<Expr>(*I));
2400}
2401
2402} // end anonymous namespace
2403
2404/// Diagnoses "dangerous" implicit conversions within the given
2405/// expression (which is a full expression). Implements -Wconversion
2406/// and -Wsign-compare.
2407void Sema::CheckImplicitConversions(Expr *E) {
2408 // Don't diagnose in unevaluated contexts.
2409 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2410 return;
2411
2412 // Don't diagnose for value- or type-dependent expressions.
2413 if (E->isTypeDependent() || E->isValueDependent())
2414 return;
2415
2416 AnalyzeImplicitConversions(*this, E);
2417}
2418
Mike Stumpf8c49212010-01-21 03:59:47 +00002419/// CheckParmsForFunctionDef - Check that the parameters of the given
2420/// function are appropriate for the definition of a function. This
2421/// takes care of any checks that cannot be performed on the
2422/// declaration itself, e.g., that the types of each of the function
2423/// parameters are complete.
2424bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2425 bool HasInvalidParm = false;
2426 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2427 ParmVarDecl *Param = FD->getParamDecl(p);
2428
2429 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2430 // function declarator that is part of a function definition of
2431 // that function shall not have incomplete type.
2432 //
2433 // This is also C++ [dcl.fct]p6.
2434 if (!Param->isInvalidDecl() &&
2435 RequireCompleteType(Param->getLocation(), Param->getType(),
2436 diag::err_typecheck_decl_incomplete_type)) {
2437 Param->setInvalidDecl();
2438 HasInvalidParm = true;
2439 }
2440
2441 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2442 // declaration of each parameter shall include an identifier.
2443 if (Param->getIdentifier() == 0 &&
2444 !Param->isImplicit() &&
2445 !getLangOptions().CPlusPlus)
2446 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002447
2448 // C99 6.7.5.3p12:
2449 // If the function declarator is not part of a definition of that
2450 // function, parameters may have incomplete type and may use the [*]
2451 // notation in their sequences of declarator specifiers to specify
2452 // variable length array types.
2453 QualType PType = Param->getOriginalType();
2454 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2455 if (AT->getSizeModifier() == ArrayType::Star) {
2456 // FIXME: This diagnosic should point the the '[*]' if source-location
2457 // information is added for it.
2458 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2459 }
2460 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002461 }
2462
2463 return HasInvalidParm;
2464}