SemaChecking.cpp revision db9e9e61f8311d8852bd15730f78e56f3ffa0508
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements extra semantic analysis beyond what is enforced
11//  by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Sema/Sema.h"
16#include "clang/Sema/SemaInternal.h"
17#include "clang/Sema/ScopeInfo.h"
18#include "clang/Analysis/Analyses/FormatString.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/DeclObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
28#include "clang/Lex/Preprocessor.h"
29#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/Support/raw_ostream.h"
32#include "clang/Basic/TargetBuiltins.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/ConvertUTF.h"
35#include <limits>
36using namespace clang;
37using namespace sema;
38
39SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
40                                                    unsigned ByteNo) const {
41  return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
42                               PP.getLangOptions(), PP.getTargetInfo());
43}
44
45
46/// CheckablePrintfAttr - does a function call have a "printf" attribute
47/// and arguments that merit checking?
48bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
49  if (Format->getType() == "printf") return true;
50  if (Format->getType() == "printf0") {
51    // printf0 allows null "format" string; if so don't check format/args
52    unsigned format_idx = Format->getFormatIdx() - 1;
53    // Does the index refer to the implicit object argument?
54    if (isa<CXXMemberCallExpr>(TheCall)) {
55      if (format_idx == 0)
56        return false;
57      --format_idx;
58    }
59    if (format_idx < TheCall->getNumArgs()) {
60      Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
61      if (!Format->isNullPointerConstant(Context,
62                                         Expr::NPC_ValueDependentIsNull))
63        return true;
64    }
65  }
66  return false;
67}
68
69/// Checks that a call expression's argument count is the desired number.
70/// This is useful when doing custom type-checking.  Returns true on error.
71static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
72  unsigned argCount = call->getNumArgs();
73  if (argCount == desiredArgCount) return false;
74
75  if (argCount < desiredArgCount)
76    return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
77        << 0 /*function call*/ << desiredArgCount << argCount
78        << call->getSourceRange();
79
80  // Highlight all the excess arguments.
81  SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
82                    call->getArg(argCount - 1)->getLocEnd());
83
84  return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
85    << 0 /*function call*/ << desiredArgCount << argCount
86    << call->getArg(1)->getSourceRange();
87}
88
89ExprResult
90Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
91  ExprResult TheCallResult(Owned(TheCall));
92
93  // Find out if any arguments are required to be integer constant expressions.
94  unsigned ICEArguments = 0;
95  ASTContext::GetBuiltinTypeError Error;
96  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
97  if (Error != ASTContext::GE_None)
98    ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
99
100  // If any arguments are required to be ICE's, check and diagnose.
101  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
102    // Skip arguments not required to be ICE's.
103    if ((ICEArguments & (1 << ArgNo)) == 0) continue;
104
105    llvm::APSInt Result;
106    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
107      return true;
108    ICEArguments &= ~(1 << ArgNo);
109  }
110
111  switch (BuiltinID) {
112  case Builtin::BI__builtin___CFStringMakeConstantString:
113    assert(TheCall->getNumArgs() == 1 &&
114           "Wrong # arguments to builtin CFStringMakeConstantString");
115    if (CheckObjCString(TheCall->getArg(0)))
116      return ExprError();
117    break;
118  case Builtin::BI__builtin_stdarg_start:
119  case Builtin::BI__builtin_va_start:
120    if (SemaBuiltinVAStart(TheCall))
121      return ExprError();
122    break;
123  case Builtin::BI__builtin_isgreater:
124  case Builtin::BI__builtin_isgreaterequal:
125  case Builtin::BI__builtin_isless:
126  case Builtin::BI__builtin_islessequal:
127  case Builtin::BI__builtin_islessgreater:
128  case Builtin::BI__builtin_isunordered:
129    if (SemaBuiltinUnorderedCompare(TheCall))
130      return ExprError();
131    break;
132  case Builtin::BI__builtin_fpclassify:
133    if (SemaBuiltinFPClassification(TheCall, 6))
134      return ExprError();
135    break;
136  case Builtin::BI__builtin_isfinite:
137  case Builtin::BI__builtin_isinf:
138  case Builtin::BI__builtin_isinf_sign:
139  case Builtin::BI__builtin_isnan:
140  case Builtin::BI__builtin_isnormal:
141    if (SemaBuiltinFPClassification(TheCall, 1))
142      return ExprError();
143    break;
144  case Builtin::BI__builtin_shufflevector:
145    return SemaBuiltinShuffleVector(TheCall);
146    // TheCall will be freed by the smart pointer here, but that's fine, since
147    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
148  case Builtin::BI__builtin_prefetch:
149    if (SemaBuiltinPrefetch(TheCall))
150      return ExprError();
151    break;
152  case Builtin::BI__builtin_object_size:
153    if (SemaBuiltinObjectSize(TheCall))
154      return ExprError();
155    break;
156  case Builtin::BI__builtin_longjmp:
157    if (SemaBuiltinLongjmp(TheCall))
158      return ExprError();
159    break;
160
161  case Builtin::BI__builtin_classify_type:
162    if (checkArgCount(*this, TheCall, 1)) return true;
163    TheCall->setType(Context.IntTy);
164    break;
165  case Builtin::BI__builtin_constant_p:
166    if (checkArgCount(*this, TheCall, 1)) return true;
167    TheCall->setType(Context.IntTy);
168    break;
169  case Builtin::BI__sync_fetch_and_add:
170  case Builtin::BI__sync_fetch_and_sub:
171  case Builtin::BI__sync_fetch_and_or:
172  case Builtin::BI__sync_fetch_and_and:
173  case Builtin::BI__sync_fetch_and_xor:
174  case Builtin::BI__sync_add_and_fetch:
175  case Builtin::BI__sync_sub_and_fetch:
176  case Builtin::BI__sync_and_and_fetch:
177  case Builtin::BI__sync_or_and_fetch:
178  case Builtin::BI__sync_xor_and_fetch:
179  case Builtin::BI__sync_val_compare_and_swap:
180  case Builtin::BI__sync_bool_compare_and_swap:
181  case Builtin::BI__sync_lock_test_and_set:
182  case Builtin::BI__sync_lock_release:
183    return SemaBuiltinAtomicOverloaded(move(TheCallResult));
184  }
185
186  // Since the target specific builtins for each arch overlap, only check those
187  // of the arch we are compiling for.
188  if (BuiltinID >= Builtin::FirstTSBuiltin) {
189    switch (Context.Target.getTriple().getArch()) {
190      case llvm::Triple::arm:
191      case llvm::Triple::thumb:
192        if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
193          return ExprError();
194        break;
195      default:
196        break;
197    }
198  }
199
200  return move(TheCallResult);
201}
202
203// Get the valid immediate range for the specified NEON type code.
204static unsigned RFT(unsigned t, bool shift = false) {
205  bool quad = t & 0x10;
206
207  switch (t & 0x7) {
208    case 0: // i8
209      return shift ? 7 : (8 << (int)quad) - 1;
210    case 1: // i16
211      return shift ? 15 : (4 << (int)quad) - 1;
212    case 2: // i32
213      return shift ? 31 : (2 << (int)quad) - 1;
214    case 3: // i64
215      return shift ? 63 : (1 << (int)quad) - 1;
216    case 4: // f32
217      assert(!shift && "cannot shift float types!");
218      return (2 << (int)quad) - 1;
219    case 5: // poly8
220      return shift ? 7 : (8 << (int)quad) - 1;
221    case 6: // poly16
222      return shift ? 15 : (4 << (int)quad) - 1;
223    case 7: // float16
224      assert(!shift && "cannot shift float types!");
225      return (4 << (int)quad) - 1;
226  }
227  return 0;
228}
229
230bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
231  llvm::APSInt Result;
232
233  unsigned mask = 0;
234  unsigned TV = 0;
235  switch (BuiltinID) {
236#define GET_NEON_OVERLOAD_CHECK
237#include "clang/Basic/arm_neon.inc"
238#undef GET_NEON_OVERLOAD_CHECK
239  }
240
241  // For NEON intrinsics which are overloaded on vector element type, validate
242  // the immediate which specifies which variant to emit.
243  if (mask) {
244    unsigned ArgNo = TheCall->getNumArgs()-1;
245    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246      return true;
247
248    TV = Result.getLimitedValue(32);
249    if ((TV > 31) || (mask & (1 << TV)) == 0)
250      return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
251        << TheCall->getArg(ArgNo)->getSourceRange();
252  }
253
254  // For NEON intrinsics which take an immediate value as part of the
255  // instruction, range check them here.
256  unsigned i = 0, l = 0, u = 0;
257  switch (BuiltinID) {
258  default: return false;
259  case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
260  case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
261  case ARM::BI__builtin_arm_vcvtr_f:
262  case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
263#define GET_NEON_IMMEDIATE_CHECK
264#include "clang/Basic/arm_neon.inc"
265#undef GET_NEON_IMMEDIATE_CHECK
266  };
267
268  // Check that the immediate argument is actually a constant.
269  if (SemaBuiltinConstantArg(TheCall, i, Result))
270    return true;
271
272  // Range check against the upper/lower values for this isntruction.
273  unsigned Val = Result.getZExtValue();
274  if (Val < l || Val > (u + l))
275    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
276      << l << u+l << TheCall->getArg(i)->getSourceRange();
277
278  // FIXME: VFP Intrinsics should error if VFP not present.
279  return false;
280}
281
282/// CheckFunctionCall - Check a direct function call for various correctness
283/// and safety properties not strictly enforced by the C type system.
284bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
285  // Get the IdentifierInfo* for the called function.
286  IdentifierInfo *FnInfo = FDecl->getIdentifier();
287
288  // None of the checks below are needed for functions that don't have
289  // simple names (e.g., C++ conversion functions).
290  if (!FnInfo)
291    return false;
292
293  // FIXME: This mechanism should be abstracted to be less fragile and
294  // more efficient. For example, just map function ids to custom
295  // handlers.
296
297  // Printf and scanf checking.
298  for (specific_attr_iterator<FormatAttr>
299         i = FDecl->specific_attr_begin<FormatAttr>(),
300         e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
301
302    const FormatAttr *Format = *i;
303    const bool b = Format->getType() == "scanf";
304    if (b || CheckablePrintfAttr(Format, TheCall)) {
305      bool HasVAListArg = Format->getFirstArg() == 0;
306      CheckPrintfScanfArguments(TheCall, HasVAListArg,
307                                Format->getFormatIdx() - 1,
308                                HasVAListArg ? 0 : Format->getFirstArg() - 1,
309                                !b);
310    }
311  }
312
313  for (specific_attr_iterator<NonNullAttr>
314         i = FDecl->specific_attr_begin<NonNullAttr>(),
315         e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
316    CheckNonNullArguments(*i, TheCall);
317  }
318
319  return false;
320}
321
322bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
323  // Printf checking.
324  const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
325  if (!Format)
326    return false;
327
328  const VarDecl *V = dyn_cast<VarDecl>(NDecl);
329  if (!V)
330    return false;
331
332  QualType Ty = V->getType();
333  if (!Ty->isBlockPointerType())
334    return false;
335
336  const bool b = Format->getType() == "scanf";
337  if (!b && !CheckablePrintfAttr(Format, TheCall))
338    return false;
339
340  bool HasVAListArg = Format->getFirstArg() == 0;
341  CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
342                            HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
343
344  return false;
345}
346
347/// SemaBuiltinAtomicOverloaded - We have a call to a function like
348/// __sync_fetch_and_add, which is an overloaded function based on the pointer
349/// type of its first argument.  The main ActOnCallExpr routines have already
350/// promoted the types of arguments because all of these calls are prototyped as
351/// void(...).
352///
353/// This function goes through and does final semantic checking for these
354/// builtins,
355ExprResult
356Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
357  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
358  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
359  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
360
361  // Ensure that we have at least one argument to do type inference from.
362  if (TheCall->getNumArgs() < 1) {
363    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
364      << 0 << 1 << TheCall->getNumArgs()
365      << TheCall->getCallee()->getSourceRange();
366    return ExprError();
367  }
368
369  // Inspect the first argument of the atomic builtin.  This should always be
370  // a pointer type, whose element is an integral scalar or pointer type.
371  // Because it is a pointer type, we don't have to worry about any implicit
372  // casts here.
373  // FIXME: We don't allow floating point scalars as input.
374  Expr *FirstArg = TheCall->getArg(0);
375  if (!FirstArg->getType()->isPointerType()) {
376    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
377      << FirstArg->getType() << FirstArg->getSourceRange();
378    return ExprError();
379  }
380
381  QualType ValType =
382    FirstArg->getType()->getAs<PointerType>()->getPointeeType();
383  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
384      !ValType->isBlockPointerType()) {
385    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
386      << FirstArg->getType() << FirstArg->getSourceRange();
387    return ExprError();
388  }
389
390  // The majority of builtins return a value, but a few have special return
391  // types, so allow them to override appropriately below.
392  QualType ResultType = ValType;
393
394  // We need to figure out which concrete builtin this maps onto.  For example,
395  // __sync_fetch_and_add with a 2 byte object turns into
396  // __sync_fetch_and_add_2.
397#define BUILTIN_ROW(x) \
398  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
399    Builtin::BI##x##_8, Builtin::BI##x##_16 }
400
401  static const unsigned BuiltinIndices[][5] = {
402    BUILTIN_ROW(__sync_fetch_and_add),
403    BUILTIN_ROW(__sync_fetch_and_sub),
404    BUILTIN_ROW(__sync_fetch_and_or),
405    BUILTIN_ROW(__sync_fetch_and_and),
406    BUILTIN_ROW(__sync_fetch_and_xor),
407
408    BUILTIN_ROW(__sync_add_and_fetch),
409    BUILTIN_ROW(__sync_sub_and_fetch),
410    BUILTIN_ROW(__sync_and_and_fetch),
411    BUILTIN_ROW(__sync_or_and_fetch),
412    BUILTIN_ROW(__sync_xor_and_fetch),
413
414    BUILTIN_ROW(__sync_val_compare_and_swap),
415    BUILTIN_ROW(__sync_bool_compare_and_swap),
416    BUILTIN_ROW(__sync_lock_test_and_set),
417    BUILTIN_ROW(__sync_lock_release)
418  };
419#undef BUILTIN_ROW
420
421  // Determine the index of the size.
422  unsigned SizeIndex;
423  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
424  case 1: SizeIndex = 0; break;
425  case 2: SizeIndex = 1; break;
426  case 4: SizeIndex = 2; break;
427  case 8: SizeIndex = 3; break;
428  case 16: SizeIndex = 4; break;
429  default:
430    Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
431      << FirstArg->getType() << FirstArg->getSourceRange();
432    return ExprError();
433  }
434
435  // Each of these builtins has one pointer argument, followed by some number of
436  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
437  // that we ignore.  Find out which row of BuiltinIndices to read from as well
438  // as the number of fixed args.
439  unsigned BuiltinID = FDecl->getBuiltinID();
440  unsigned BuiltinIndex, NumFixed = 1;
441  switch (BuiltinID) {
442  default: assert(0 && "Unknown overloaded atomic builtin!");
443  case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
444  case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
445  case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
446  case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
447  case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
448
449  case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
450  case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
451  case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
452  case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
453  case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
454
455  case Builtin::BI__sync_val_compare_and_swap:
456    BuiltinIndex = 10;
457    NumFixed = 2;
458    break;
459  case Builtin::BI__sync_bool_compare_and_swap:
460    BuiltinIndex = 11;
461    NumFixed = 2;
462    ResultType = Context.BoolTy;
463    break;
464  case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
465  case Builtin::BI__sync_lock_release:
466    BuiltinIndex = 13;
467    NumFixed = 0;
468    ResultType = Context.VoidTy;
469    break;
470  }
471
472  // Now that we know how many fixed arguments we expect, first check that we
473  // have at least that many.
474  if (TheCall->getNumArgs() < 1+NumFixed) {
475    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
476      << 0 << 1+NumFixed << TheCall->getNumArgs()
477      << TheCall->getCallee()->getSourceRange();
478    return ExprError();
479  }
480
481  // Get the decl for the concrete builtin from this, we can tell what the
482  // concrete integer type we should convert to is.
483  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
484  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
485  IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
486  FunctionDecl *NewBuiltinDecl =
487    cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
488                                           TUScope, false, DRE->getLocStart()));
489
490  // The first argument --- the pointer --- has a fixed type; we
491  // deduce the types of the rest of the arguments accordingly.  Walk
492  // the remaining arguments, converting them to the deduced value type.
493  for (unsigned i = 0; i != NumFixed; ++i) {
494    Expr *Arg = TheCall->getArg(i+1);
495
496    // If the argument is an implicit cast, then there was a promotion due to
497    // "...", just remove it now.
498    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
499      Arg = ICE->getSubExpr();
500      ICE->setSubExpr(0);
501      TheCall->setArg(i+1, Arg);
502    }
503
504    // GCC does an implicit conversion to the pointer or integer ValType.  This
505    // can fail in some cases (1i -> int**), check for this error case now.
506    CastKind Kind = CK_Invalid;
507    ExprValueKind VK = VK_RValue;
508    CXXCastPath BasePath;
509    if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, VK, BasePath))
510      return ExprError();
511
512    // Okay, we have something that *can* be converted to the right type.  Check
513    // to see if there is a potentially weird extension going on here.  This can
514    // happen when you do an atomic operation on something like an char* and
515    // pass in 42.  The 42 gets converted to char.  This is even more strange
516    // for things like 45.123 -> char, etc.
517    // FIXME: Do this check.
518    ImpCastExprToType(Arg, ValType, Kind, VK, &BasePath);
519    TheCall->setArg(i+1, Arg);
520  }
521
522  // Switch the DeclRefExpr to refer to the new decl.
523  DRE->setDecl(NewBuiltinDecl);
524  DRE->setType(NewBuiltinDecl->getType());
525
526  // Set the callee in the CallExpr.
527  // FIXME: This leaks the original parens and implicit casts.
528  Expr *PromotedCall = DRE;
529  UsualUnaryConversions(PromotedCall);
530  TheCall->setCallee(PromotedCall);
531
532  // Change the result type of the call to match the original value type. This
533  // is arbitrary, but the codegen for these builtins ins design to handle it
534  // gracefully.
535  TheCall->setType(ResultType);
536
537  return move(TheCallResult);
538}
539
540
541/// CheckObjCString - Checks that the argument to the builtin
542/// CFString constructor is correct
543/// Note: It might also make sense to do the UTF-16 conversion here (would
544/// simplify the backend).
545bool Sema::CheckObjCString(Expr *Arg) {
546  Arg = Arg->IgnoreParenCasts();
547  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
548
549  if (!Literal || Literal->isWide()) {
550    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
551      << Arg->getSourceRange();
552    return true;
553  }
554
555  if (Literal->containsNonAsciiOrNull()) {
556    llvm::StringRef String = Literal->getString();
557    unsigned NumBytes = String.size();
558    llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
559    const UTF8 *FromPtr = (UTF8 *)String.data();
560    UTF16 *ToPtr = &ToBuf[0];
561
562    ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
563                                                 &ToPtr, ToPtr + NumBytes,
564                                                 strictConversion);
565    // Check for conversion failure.
566    if (Result != conversionOK)
567      Diag(Arg->getLocStart(),
568           diag::warn_cfstring_truncated) << Arg->getSourceRange();
569  }
570  return false;
571}
572
573/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
574/// Emit an error and return true on failure, return false on success.
575bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
576  Expr *Fn = TheCall->getCallee();
577  if (TheCall->getNumArgs() > 2) {
578    Diag(TheCall->getArg(2)->getLocStart(),
579         diag::err_typecheck_call_too_many_args)
580      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
581      << Fn->getSourceRange()
582      << SourceRange(TheCall->getArg(2)->getLocStart(),
583                     (*(TheCall->arg_end()-1))->getLocEnd());
584    return true;
585  }
586
587  if (TheCall->getNumArgs() < 2) {
588    return Diag(TheCall->getLocEnd(),
589      diag::err_typecheck_call_too_few_args_at_least)
590      << 0 /*function call*/ << 2 << TheCall->getNumArgs();
591  }
592
593  // Determine whether the current function is variadic or not.
594  BlockScopeInfo *CurBlock = getCurBlock();
595  bool isVariadic;
596  if (CurBlock)
597    isVariadic = CurBlock->TheDecl->isVariadic();
598  else if (FunctionDecl *FD = getCurFunctionDecl())
599    isVariadic = FD->isVariadic();
600  else
601    isVariadic = getCurMethodDecl()->isVariadic();
602
603  if (!isVariadic) {
604    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
605    return true;
606  }
607
608  // Verify that the second argument to the builtin is the last argument of the
609  // current function or method.
610  bool SecondArgIsLastNamedArgument = false;
611  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
612
613  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
614    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
615      // FIXME: This isn't correct for methods (results in bogus warning).
616      // Get the last formal in the current function.
617      const ParmVarDecl *LastArg;
618      if (CurBlock)
619        LastArg = *(CurBlock->TheDecl->param_end()-1);
620      else if (FunctionDecl *FD = getCurFunctionDecl())
621        LastArg = *(FD->param_end()-1);
622      else
623        LastArg = *(getCurMethodDecl()->param_end()-1);
624      SecondArgIsLastNamedArgument = PV == LastArg;
625    }
626  }
627
628  if (!SecondArgIsLastNamedArgument)
629    Diag(TheCall->getArg(1)->getLocStart(),
630         diag::warn_second_parameter_of_va_start_not_last_named_argument);
631  return false;
632}
633
634/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
635/// friends.  This is declared to take (...), so we have to check everything.
636bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
637  if (TheCall->getNumArgs() < 2)
638    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
639      << 0 << 2 << TheCall->getNumArgs()/*function call*/;
640  if (TheCall->getNumArgs() > 2)
641    return Diag(TheCall->getArg(2)->getLocStart(),
642                diag::err_typecheck_call_too_many_args)
643      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
644      << SourceRange(TheCall->getArg(2)->getLocStart(),
645                     (*(TheCall->arg_end()-1))->getLocEnd());
646
647  Expr *OrigArg0 = TheCall->getArg(0);
648  Expr *OrigArg1 = TheCall->getArg(1);
649
650  // Do standard promotions between the two arguments, returning their common
651  // type.
652  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
653
654  // Make sure any conversions are pushed back into the call; this is
655  // type safe since unordered compare builtins are declared as "_Bool
656  // foo(...)".
657  TheCall->setArg(0, OrigArg0);
658  TheCall->setArg(1, OrigArg1);
659
660  if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
661    return false;
662
663  // If the common type isn't a real floating type, then the arguments were
664  // invalid for this operation.
665  if (!Res->isRealFloatingType())
666    return Diag(OrigArg0->getLocStart(),
667                diag::err_typecheck_call_invalid_ordered_compare)
668      << OrigArg0->getType() << OrigArg1->getType()
669      << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
670
671  return false;
672}
673
674/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
675/// __builtin_isnan and friends.  This is declared to take (...), so we have
676/// to check everything. We expect the last argument to be a floating point
677/// value.
678bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
679  if (TheCall->getNumArgs() < NumArgs)
680    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
681      << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
682  if (TheCall->getNumArgs() > NumArgs)
683    return Diag(TheCall->getArg(NumArgs)->getLocStart(),
684                diag::err_typecheck_call_too_many_args)
685      << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
686      << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
687                     (*(TheCall->arg_end()-1))->getLocEnd());
688
689  Expr *OrigArg = TheCall->getArg(NumArgs-1);
690
691  if (OrigArg->isTypeDependent())
692    return false;
693
694  // This operation requires a non-_Complex floating-point number.
695  if (!OrigArg->getType()->isRealFloatingType())
696    return Diag(OrigArg->getLocStart(),
697                diag::err_typecheck_call_invalid_unary_fp)
698      << OrigArg->getType() << OrigArg->getSourceRange();
699
700  // If this is an implicit conversion from float -> double, remove it.
701  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
702    Expr *CastArg = Cast->getSubExpr();
703    if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
704      assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
705             "promotion from float to double is the only expected cast here");
706      Cast->setSubExpr(0);
707      TheCall->setArg(NumArgs-1, CastArg);
708      OrigArg = CastArg;
709    }
710  }
711
712  return false;
713}
714
715/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
716// This is declared to take (...), so we have to check everything.
717ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
718  if (TheCall->getNumArgs() < 2)
719    return ExprError(Diag(TheCall->getLocEnd(),
720                          diag::err_typecheck_call_too_few_args_at_least)
721      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
722      << TheCall->getSourceRange());
723
724  // Determine which of the following types of shufflevector we're checking:
725  // 1) unary, vector mask: (lhs, mask)
726  // 2) binary, vector mask: (lhs, rhs, mask)
727  // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
728  QualType resType = TheCall->getArg(0)->getType();
729  unsigned numElements = 0;
730
731  if (!TheCall->getArg(0)->isTypeDependent() &&
732      !TheCall->getArg(1)->isTypeDependent()) {
733    QualType LHSType = TheCall->getArg(0)->getType();
734    QualType RHSType = TheCall->getArg(1)->getType();
735
736    if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
737      Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
738        << SourceRange(TheCall->getArg(0)->getLocStart(),
739                       TheCall->getArg(1)->getLocEnd());
740      return ExprError();
741    }
742
743    numElements = LHSType->getAs<VectorType>()->getNumElements();
744    unsigned numResElements = TheCall->getNumArgs() - 2;
745
746    // Check to see if we have a call with 2 vector arguments, the unary shuffle
747    // with mask.  If so, verify that RHS is an integer vector type with the
748    // same number of elts as lhs.
749    if (TheCall->getNumArgs() == 2) {
750      if (!RHSType->hasIntegerRepresentation() ||
751          RHSType->getAs<VectorType>()->getNumElements() != numElements)
752        Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
753          << SourceRange(TheCall->getArg(1)->getLocStart(),
754                         TheCall->getArg(1)->getLocEnd());
755      numResElements = numElements;
756    }
757    else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
758      Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
759        << SourceRange(TheCall->getArg(0)->getLocStart(),
760                       TheCall->getArg(1)->getLocEnd());
761      return ExprError();
762    } else if (numElements != numResElements) {
763      QualType eltType = LHSType->getAs<VectorType>()->getElementType();
764      resType = Context.getVectorType(eltType, numResElements,
765                                      VectorType::GenericVector);
766    }
767  }
768
769  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
770    if (TheCall->getArg(i)->isTypeDependent() ||
771        TheCall->getArg(i)->isValueDependent())
772      continue;
773
774    llvm::APSInt Result(32);
775    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
776      return ExprError(Diag(TheCall->getLocStart(),
777                  diag::err_shufflevector_nonconstant_argument)
778                << TheCall->getArg(i)->getSourceRange());
779
780    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
781      return ExprError(Diag(TheCall->getLocStart(),
782                  diag::err_shufflevector_argument_too_large)
783               << TheCall->getArg(i)->getSourceRange());
784  }
785
786  llvm::SmallVector<Expr*, 32> exprs;
787
788  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
789    exprs.push_back(TheCall->getArg(i));
790    TheCall->setArg(i, 0);
791  }
792
793  return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
794                                            exprs.size(), resType,
795                                            TheCall->getCallee()->getLocStart(),
796                                            TheCall->getRParenLoc()));
797}
798
799/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
800// This is declared to take (const void*, ...) and can take two
801// optional constant int args.
802bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
803  unsigned NumArgs = TheCall->getNumArgs();
804
805  if (NumArgs > 3)
806    return Diag(TheCall->getLocEnd(),
807             diag::err_typecheck_call_too_many_args_at_most)
808             << 0 /*function call*/ << 3 << NumArgs
809             << TheCall->getSourceRange();
810
811  // Argument 0 is checked for us and the remaining arguments must be
812  // constant integers.
813  for (unsigned i = 1; i != NumArgs; ++i) {
814    Expr *Arg = TheCall->getArg(i);
815
816    llvm::APSInt Result;
817    if (SemaBuiltinConstantArg(TheCall, i, Result))
818      return true;
819
820    // FIXME: gcc issues a warning and rewrites these to 0. These
821    // seems especially odd for the third argument since the default
822    // is 3.
823    if (i == 1) {
824      if (Result.getLimitedValue() > 1)
825        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
826             << "0" << "1" << Arg->getSourceRange();
827    } else {
828      if (Result.getLimitedValue() > 3)
829        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
830            << "0" << "3" << Arg->getSourceRange();
831    }
832  }
833
834  return false;
835}
836
837/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
838/// TheCall is a constant expression.
839bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
840                                  llvm::APSInt &Result) {
841  Expr *Arg = TheCall->getArg(ArgNum);
842  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
843  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
844
845  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
846
847  if (!Arg->isIntegerConstantExpr(Result, Context))
848    return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
849                << FDecl->getDeclName() <<  Arg->getSourceRange();
850
851  return false;
852}
853
854/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
855/// int type). This simply type checks that type is one of the defined
856/// constants (0-3).
857// For compatability check 0-3, llvm only handles 0 and 2.
858bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
859  llvm::APSInt Result;
860
861  // Check constant-ness first.
862  if (SemaBuiltinConstantArg(TheCall, 1, Result))
863    return true;
864
865  Expr *Arg = TheCall->getArg(1);
866  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
867    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
868             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
869  }
870
871  return false;
872}
873
874/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
875/// This checks that val is a constant 1.
876bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
877  Expr *Arg = TheCall->getArg(1);
878  llvm::APSInt Result;
879
880  // TODO: This is less than ideal. Overload this to take a value.
881  if (SemaBuiltinConstantArg(TheCall, 1, Result))
882    return true;
883
884  if (Result != 1)
885    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
886             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
887
888  return false;
889}
890
891// Handle i > 1 ? "x" : "y", recursively.
892bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
893                                  bool HasVAListArg,
894                                  unsigned format_idx, unsigned firstDataArg,
895                                  bool isPrintf) {
896 tryAgain:
897  if (E->isTypeDependent() || E->isValueDependent())
898    return false;
899
900  switch (E->getStmtClass()) {
901  case Stmt::BinaryConditionalOperatorClass:
902  case Stmt::ConditionalOperatorClass: {
903    const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
904    return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
905                                  format_idx, firstDataArg, isPrintf)
906        && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
907                                  format_idx, firstDataArg, isPrintf);
908  }
909
910  case Stmt::IntegerLiteralClass:
911    // Technically -Wformat-nonliteral does not warn about this case.
912    // The behavior of printf and friends in this case is implementation
913    // dependent.  Ideally if the format string cannot be null then
914    // it should have a 'nonnull' attribute in the function prototype.
915    return true;
916
917  case Stmt::ImplicitCastExprClass: {
918    E = cast<ImplicitCastExpr>(E)->getSubExpr();
919    goto tryAgain;
920  }
921
922  case Stmt::ParenExprClass: {
923    E = cast<ParenExpr>(E)->getSubExpr();
924    goto tryAgain;
925  }
926
927  case Stmt::OpaqueValueExprClass:
928    if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
929      E = src;
930      goto tryAgain;
931    }
932    return false;
933
934  case Stmt::PredefinedExprClass:
935    // While __func__, etc., are technically not string literals, they
936    // cannot contain format specifiers and thus are not a security
937    // liability.
938    return true;
939
940  case Stmt::DeclRefExprClass: {
941    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
942
943    // As an exception, do not flag errors for variables binding to
944    // const string literals.
945    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
946      bool isConstant = false;
947      QualType T = DR->getType();
948
949      if (const ArrayType *AT = Context.getAsArrayType(T)) {
950        isConstant = AT->getElementType().isConstant(Context);
951      } else if (const PointerType *PT = T->getAs<PointerType>()) {
952        isConstant = T.isConstant(Context) &&
953                     PT->getPointeeType().isConstant(Context);
954      }
955
956      if (isConstant) {
957        if (const Expr *Init = VD->getAnyInitializer())
958          return SemaCheckStringLiteral(Init, TheCall,
959                                        HasVAListArg, format_idx, firstDataArg,
960                                        isPrintf);
961      }
962
963      // For vprintf* functions (i.e., HasVAListArg==true), we add a
964      // special check to see if the format string is a function parameter
965      // of the function calling the printf function.  If the function
966      // has an attribute indicating it is a printf-like function, then we
967      // should suppress warnings concerning non-literals being used in a call
968      // to a vprintf function.  For example:
969      //
970      // void
971      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
972      //      va_list ap;
973      //      va_start(ap, fmt);
974      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
975      //      ...
976      //
977      //
978      //  FIXME: We don't have full attribute support yet, so just check to see
979      //    if the argument is a DeclRefExpr that references a parameter.  We'll
980      //    add proper support for checking the attribute later.
981      if (HasVAListArg)
982        if (isa<ParmVarDecl>(VD))
983          return true;
984    }
985
986    return false;
987  }
988
989  case Stmt::CallExprClass: {
990    const CallExpr *CE = cast<CallExpr>(E);
991    if (const ImplicitCastExpr *ICE
992          = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
993      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
994        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
995          if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
996            unsigned ArgIndex = FA->getFormatIdx();
997            const Expr *Arg = CE->getArg(ArgIndex - 1);
998
999            return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
1000                                          format_idx, firstDataArg, isPrintf);
1001          }
1002        }
1003      }
1004    }
1005
1006    return false;
1007  }
1008  case Stmt::ObjCStringLiteralClass:
1009  case Stmt::StringLiteralClass: {
1010    const StringLiteral *StrE = NULL;
1011
1012    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1013      StrE = ObjCFExpr->getString();
1014    else
1015      StrE = cast<StringLiteral>(E);
1016
1017    if (StrE) {
1018      CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1019                        firstDataArg, isPrintf);
1020      return true;
1021    }
1022
1023    return false;
1024  }
1025
1026  default:
1027    return false;
1028  }
1029}
1030
1031void
1032Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1033                            const CallExpr *TheCall) {
1034  for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1035                                  e = NonNull->args_end();
1036       i != e; ++i) {
1037    const Expr *ArgExpr = TheCall->getArg(*i);
1038    if (ArgExpr->isNullPointerConstant(Context,
1039                                       Expr::NPC_ValueDependentIsNotNull))
1040      Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1041        << ArgExpr->getSourceRange();
1042  }
1043}
1044
1045/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1046/// functions) for correct use of format strings.
1047void
1048Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1049                                unsigned format_idx, unsigned firstDataArg,
1050                                bool isPrintf) {
1051
1052  const Expr *Fn = TheCall->getCallee();
1053
1054  // The way the format attribute works in GCC, the implicit this argument
1055  // of member functions is counted. However, it doesn't appear in our own
1056  // lists, so decrement format_idx in that case.
1057  if (isa<CXXMemberCallExpr>(TheCall)) {
1058    const CXXMethodDecl *method_decl =
1059      dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1060    if (method_decl && method_decl->isInstance()) {
1061      // Catch a format attribute mistakenly referring to the object argument.
1062      if (format_idx == 0)
1063        return;
1064      --format_idx;
1065      if(firstDataArg != 0)
1066        --firstDataArg;
1067    }
1068  }
1069
1070  // CHECK: printf/scanf-like function is called with no format string.
1071  if (format_idx >= TheCall->getNumArgs()) {
1072    Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
1073      << Fn->getSourceRange();
1074    return;
1075  }
1076
1077  const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
1078
1079  // CHECK: format string is not a string literal.
1080  //
1081  // Dynamically generated format strings are difficult to
1082  // automatically vet at compile time.  Requiring that format strings
1083  // are string literals: (1) permits the checking of format strings by
1084  // the compiler and thereby (2) can practically remove the source of
1085  // many format string exploits.
1086
1087  // Format string can be either ObjC string (e.g. @"%d") or
1088  // C string (e.g. "%d")
1089  // ObjC string uses the same format specifiers as C string, so we can use
1090  // the same format string checking logic for both ObjC and C strings.
1091  if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1092                             firstDataArg, isPrintf))
1093    return;  // Literal format string found, check done!
1094
1095  // If there are no arguments specified, warn with -Wformat-security, otherwise
1096  // warn only with -Wformat-nonliteral.
1097  if (TheCall->getNumArgs() == format_idx+1)
1098    Diag(TheCall->getArg(format_idx)->getLocStart(),
1099         diag::warn_format_nonliteral_noargs)
1100      << OrigFormatExpr->getSourceRange();
1101  else
1102    Diag(TheCall->getArg(format_idx)->getLocStart(),
1103         diag::warn_format_nonliteral)
1104           << OrigFormatExpr->getSourceRange();
1105}
1106
1107namespace {
1108class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1109protected:
1110  Sema &S;
1111  const StringLiteral *FExpr;
1112  const Expr *OrigFormatExpr;
1113  const unsigned FirstDataArg;
1114  const unsigned NumDataArgs;
1115  const bool IsObjCLiteral;
1116  const char *Beg; // Start of format string.
1117  const bool HasVAListArg;
1118  const CallExpr *TheCall;
1119  unsigned FormatIdx;
1120  llvm::BitVector CoveredArgs;
1121  bool usesPositionalArgs;
1122  bool atFirstArg;
1123public:
1124  CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1125                     const Expr *origFormatExpr, unsigned firstDataArg,
1126                     unsigned numDataArgs, bool isObjCLiteral,
1127                     const char *beg, bool hasVAListArg,
1128                     const CallExpr *theCall, unsigned formatIdx)
1129    : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1130      FirstDataArg(firstDataArg),
1131      NumDataArgs(numDataArgs),
1132      IsObjCLiteral(isObjCLiteral), Beg(beg),
1133      HasVAListArg(hasVAListArg),
1134      TheCall(theCall), FormatIdx(formatIdx),
1135      usesPositionalArgs(false), atFirstArg(true) {
1136        CoveredArgs.resize(numDataArgs);
1137        CoveredArgs.reset();
1138      }
1139
1140  void DoneProcessing();
1141
1142  void HandleIncompleteSpecifier(const char *startSpecifier,
1143                                 unsigned specifierLen);
1144
1145  virtual void HandleInvalidPosition(const char *startSpecifier,
1146                                     unsigned specifierLen,
1147                                     analyze_format_string::PositionContext p);
1148
1149  virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1150
1151  void HandleNullChar(const char *nullCharacter);
1152
1153protected:
1154  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1155                                        const char *startSpec,
1156                                        unsigned specifierLen,
1157                                        const char *csStart, unsigned csLen);
1158
1159  SourceRange getFormatStringRange();
1160  CharSourceRange getSpecifierRange(const char *startSpecifier,
1161                                    unsigned specifierLen);
1162  SourceLocation getLocationOfByte(const char *x);
1163
1164  const Expr *getDataArg(unsigned i) const;
1165
1166  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1167                    const analyze_format_string::ConversionSpecifier &CS,
1168                    const char *startSpecifier, unsigned specifierLen,
1169                    unsigned argIndex);
1170};
1171}
1172
1173SourceRange CheckFormatHandler::getFormatStringRange() {
1174  return OrigFormatExpr->getSourceRange();
1175}
1176
1177CharSourceRange CheckFormatHandler::
1178getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1179  SourceLocation Start = getLocationOfByte(startSpecifier);
1180  SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
1181
1182  // Advance the end SourceLocation by one due to half-open ranges.
1183  End = End.getFileLocWithOffset(1);
1184
1185  return CharSourceRange::getCharRange(Start, End);
1186}
1187
1188SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
1189  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1190}
1191
1192void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1193                                                   unsigned specifierLen){
1194  SourceLocation Loc = getLocationOfByte(startSpecifier);
1195  S.Diag(Loc, diag::warn_printf_incomplete_specifier)
1196    << getSpecifierRange(startSpecifier, specifierLen);
1197}
1198
1199void
1200CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1201                                     analyze_format_string::PositionContext p) {
1202  SourceLocation Loc = getLocationOfByte(startPos);
1203  S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1204    << (unsigned) p << getSpecifierRange(startPos, posLen);
1205}
1206
1207void CheckFormatHandler::HandleZeroPosition(const char *startPos,
1208                                            unsigned posLen) {
1209  SourceLocation Loc = getLocationOfByte(startPos);
1210  S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1211    << getSpecifierRange(startPos, posLen);
1212}
1213
1214void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1215  if (!IsObjCLiteral) {
1216    // The presence of a null character is likely an error.
1217    S.Diag(getLocationOfByte(nullCharacter),
1218           diag::warn_printf_format_string_contains_null_char)
1219      << getFormatStringRange();
1220  }
1221}
1222
1223const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1224  return TheCall->getArg(FirstDataArg + i);
1225}
1226
1227void CheckFormatHandler::DoneProcessing() {
1228    // Does the number of data arguments exceed the number of
1229    // format conversions in the format string?
1230  if (!HasVAListArg) {
1231      // Find any arguments that weren't covered.
1232    CoveredArgs.flip();
1233    signed notCoveredArg = CoveredArgs.find_first();
1234    if (notCoveredArg >= 0) {
1235      assert((unsigned)notCoveredArg < NumDataArgs);
1236      S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1237             diag::warn_printf_data_arg_not_used)
1238      << getFormatStringRange();
1239    }
1240  }
1241}
1242
1243bool
1244CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1245                                                     SourceLocation Loc,
1246                                                     const char *startSpec,
1247                                                     unsigned specifierLen,
1248                                                     const char *csStart,
1249                                                     unsigned csLen) {
1250
1251  bool keepGoing = true;
1252  if (argIndex < NumDataArgs) {
1253    // Consider the argument coverered, even though the specifier doesn't
1254    // make sense.
1255    CoveredArgs.set(argIndex);
1256  }
1257  else {
1258    // If argIndex exceeds the number of data arguments we
1259    // don't issue a warning because that is just a cascade of warnings (and
1260    // they may have intended '%%' anyway). We don't want to continue processing
1261    // the format string after this point, however, as we will like just get
1262    // gibberish when trying to match arguments.
1263    keepGoing = false;
1264  }
1265
1266  S.Diag(Loc, diag::warn_format_invalid_conversion)
1267    << llvm::StringRef(csStart, csLen)
1268    << getSpecifierRange(startSpec, specifierLen);
1269
1270  return keepGoing;
1271}
1272
1273bool
1274CheckFormatHandler::CheckNumArgs(
1275  const analyze_format_string::FormatSpecifier &FS,
1276  const analyze_format_string::ConversionSpecifier &CS,
1277  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1278
1279  if (argIndex >= NumDataArgs) {
1280    if (FS.usesPositionalArg())  {
1281      S.Diag(getLocationOfByte(CS.getStart()),
1282             diag::warn_printf_positional_arg_exceeds_data_args)
1283      << (argIndex+1) << NumDataArgs
1284      << getSpecifierRange(startSpecifier, specifierLen);
1285    }
1286    else {
1287      S.Diag(getLocationOfByte(CS.getStart()),
1288             diag::warn_printf_insufficient_data_args)
1289      << getSpecifierRange(startSpecifier, specifierLen);
1290    }
1291
1292    return false;
1293  }
1294  return true;
1295}
1296
1297//===--- CHECK: Printf format string checking ------------------------------===//
1298
1299namespace {
1300class CheckPrintfHandler : public CheckFormatHandler {
1301public:
1302  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1303                     const Expr *origFormatExpr, unsigned firstDataArg,
1304                     unsigned numDataArgs, bool isObjCLiteral,
1305                     const char *beg, bool hasVAListArg,
1306                     const CallExpr *theCall, unsigned formatIdx)
1307  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1308                       numDataArgs, isObjCLiteral, beg, hasVAListArg,
1309                       theCall, formatIdx) {}
1310
1311
1312  bool HandleInvalidPrintfConversionSpecifier(
1313                                      const analyze_printf::PrintfSpecifier &FS,
1314                                      const char *startSpecifier,
1315                                      unsigned specifierLen);
1316
1317  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1318                             const char *startSpecifier,
1319                             unsigned specifierLen);
1320
1321  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1322                    const char *startSpecifier, unsigned specifierLen);
1323  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1324                           const analyze_printf::OptionalAmount &Amt,
1325                           unsigned type,
1326                           const char *startSpecifier, unsigned specifierLen);
1327  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1328                  const analyze_printf::OptionalFlag &flag,
1329                  const char *startSpecifier, unsigned specifierLen);
1330  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1331                         const analyze_printf::OptionalFlag &ignoredFlag,
1332                         const analyze_printf::OptionalFlag &flag,
1333                         const char *startSpecifier, unsigned specifierLen);
1334};
1335}
1336
1337bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1338                                      const analyze_printf::PrintfSpecifier &FS,
1339                                      const char *startSpecifier,
1340                                      unsigned specifierLen) {
1341  const analyze_printf::PrintfConversionSpecifier &CS =
1342    FS.getConversionSpecifier();
1343
1344  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1345                                          getLocationOfByte(CS.getStart()),
1346                                          startSpecifier, specifierLen,
1347                                          CS.getStart(), CS.getLength());
1348}
1349
1350bool CheckPrintfHandler::HandleAmount(
1351                               const analyze_format_string::OptionalAmount &Amt,
1352                               unsigned k, const char *startSpecifier,
1353                               unsigned specifierLen) {
1354
1355  if (Amt.hasDataArgument()) {
1356    if (!HasVAListArg) {
1357      unsigned argIndex = Amt.getArgIndex();
1358      if (argIndex >= NumDataArgs) {
1359        S.Diag(getLocationOfByte(Amt.getStart()),
1360               diag::warn_printf_asterisk_missing_arg)
1361          << k << getSpecifierRange(startSpecifier, specifierLen);
1362        // Don't do any more checking.  We will just emit
1363        // spurious errors.
1364        return false;
1365      }
1366
1367      // Type check the data argument.  It should be an 'int'.
1368      // Although not in conformance with C99, we also allow the argument to be
1369      // an 'unsigned int' as that is a reasonably safe case.  GCC also
1370      // doesn't emit a warning for that case.
1371      CoveredArgs.set(argIndex);
1372      const Expr *Arg = getDataArg(argIndex);
1373      QualType T = Arg->getType();
1374
1375      const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1376      assert(ATR.isValid());
1377
1378      if (!ATR.matchesType(S.Context, T)) {
1379        S.Diag(getLocationOfByte(Amt.getStart()),
1380               diag::warn_printf_asterisk_wrong_type)
1381          << k
1382          << ATR.getRepresentativeType(S.Context) << T
1383          << getSpecifierRange(startSpecifier, specifierLen)
1384          << Arg->getSourceRange();
1385        // Don't do any more checking.  We will just emit
1386        // spurious errors.
1387        return false;
1388      }
1389    }
1390  }
1391  return true;
1392}
1393
1394void CheckPrintfHandler::HandleInvalidAmount(
1395                                      const analyze_printf::PrintfSpecifier &FS,
1396                                      const analyze_printf::OptionalAmount &Amt,
1397                                      unsigned type,
1398                                      const char *startSpecifier,
1399                                      unsigned specifierLen) {
1400  const analyze_printf::PrintfConversionSpecifier &CS =
1401    FS.getConversionSpecifier();
1402  switch (Amt.getHowSpecified()) {
1403  case analyze_printf::OptionalAmount::Constant:
1404    S.Diag(getLocationOfByte(Amt.getStart()),
1405        diag::warn_printf_nonsensical_optional_amount)
1406      << type
1407      << CS.toString()
1408      << getSpecifierRange(startSpecifier, specifierLen)
1409      << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1410          Amt.getConstantLength()));
1411    break;
1412
1413  default:
1414    S.Diag(getLocationOfByte(Amt.getStart()),
1415        diag::warn_printf_nonsensical_optional_amount)
1416      << type
1417      << CS.toString()
1418      << getSpecifierRange(startSpecifier, specifierLen);
1419    break;
1420  }
1421}
1422
1423void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1424                                    const analyze_printf::OptionalFlag &flag,
1425                                    const char *startSpecifier,
1426                                    unsigned specifierLen) {
1427  // Warn about pointless flag with a fixit removal.
1428  const analyze_printf::PrintfConversionSpecifier &CS =
1429    FS.getConversionSpecifier();
1430  S.Diag(getLocationOfByte(flag.getPosition()),
1431      diag::warn_printf_nonsensical_flag)
1432    << flag.toString() << CS.toString()
1433    << getSpecifierRange(startSpecifier, specifierLen)
1434    << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
1435}
1436
1437void CheckPrintfHandler::HandleIgnoredFlag(
1438                                const analyze_printf::PrintfSpecifier &FS,
1439                                const analyze_printf::OptionalFlag &ignoredFlag,
1440                                const analyze_printf::OptionalFlag &flag,
1441                                const char *startSpecifier,
1442                                unsigned specifierLen) {
1443  // Warn about ignored flag with a fixit removal.
1444  S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1445      diag::warn_printf_ignored_flag)
1446    << ignoredFlag.toString() << flag.toString()
1447    << getSpecifierRange(startSpecifier, specifierLen)
1448    << FixItHint::CreateRemoval(getSpecifierRange(
1449        ignoredFlag.getPosition(), 1));
1450}
1451
1452bool
1453CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
1454                                            &FS,
1455                                          const char *startSpecifier,
1456                                          unsigned specifierLen) {
1457
1458  using namespace analyze_format_string;
1459  using namespace analyze_printf;
1460  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
1461
1462  if (FS.consumesDataArgument()) {
1463    if (atFirstArg) {
1464        atFirstArg = false;
1465        usesPositionalArgs = FS.usesPositionalArg();
1466    }
1467    else if (usesPositionalArgs != FS.usesPositionalArg()) {
1468      // Cannot mix-and-match positional and non-positional arguments.
1469      S.Diag(getLocationOfByte(CS.getStart()),
1470             diag::warn_format_mix_positional_nonpositional_args)
1471        << getSpecifierRange(startSpecifier, specifierLen);
1472      return false;
1473    }
1474  }
1475
1476  // First check if the field width, precision, and conversion specifier
1477  // have matching data arguments.
1478  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1479                    startSpecifier, specifierLen)) {
1480    return false;
1481  }
1482
1483  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1484                    startSpecifier, specifierLen)) {
1485    return false;
1486  }
1487
1488  if (!CS.consumesDataArgument()) {
1489    // FIXME: Technically specifying a precision or field width here
1490    // makes no sense.  Worth issuing a warning at some point.
1491    return true;
1492  }
1493
1494  // Consume the argument.
1495  unsigned argIndex = FS.getArgIndex();
1496  if (argIndex < NumDataArgs) {
1497    // The check to see if the argIndex is valid will come later.
1498    // We set the bit here because we may exit early from this
1499    // function if we encounter some other error.
1500    CoveredArgs.set(argIndex);
1501  }
1502
1503  // Check for using an Objective-C specific conversion specifier
1504  // in a non-ObjC literal.
1505  if (!IsObjCLiteral && CS.isObjCArg()) {
1506    return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1507                                                  specifierLen);
1508  }
1509
1510  // Check for invalid use of field width
1511  if (!FS.hasValidFieldWidth()) {
1512    HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
1513        startSpecifier, specifierLen);
1514  }
1515
1516  // Check for invalid use of precision
1517  if (!FS.hasValidPrecision()) {
1518    HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1519        startSpecifier, specifierLen);
1520  }
1521
1522  // Check each flag does not conflict with any other component.
1523  if (!FS.hasValidThousandsGroupingPrefix())
1524    HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
1525  if (!FS.hasValidLeadingZeros())
1526    HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1527  if (!FS.hasValidPlusPrefix())
1528    HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
1529  if (!FS.hasValidSpacePrefix())
1530    HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
1531  if (!FS.hasValidAlternativeForm())
1532    HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1533  if (!FS.hasValidLeftJustified())
1534    HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1535
1536  // Check that flags are not ignored by another flag
1537  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1538    HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1539        startSpecifier, specifierLen);
1540  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1541    HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1542            startSpecifier, specifierLen);
1543
1544  // Check the length modifier is valid with the given conversion specifier.
1545  const LengthModifier &LM = FS.getLengthModifier();
1546  if (!FS.hasValidLengthModifier())
1547    S.Diag(getLocationOfByte(LM.getStart()),
1548        diag::warn_format_nonsensical_length)
1549      << LM.toString() << CS.toString()
1550      << getSpecifierRange(startSpecifier, specifierLen)
1551      << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1552          LM.getLength()));
1553
1554  // Are we using '%n'?
1555  if (CS.getKind() == ConversionSpecifier::nArg) {
1556    // Issue a warning about this being a possible security issue.
1557    S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
1558      << getSpecifierRange(startSpecifier, specifierLen);
1559    // Continue checking the other format specifiers.
1560    return true;
1561  }
1562
1563  // The remaining checks depend on the data arguments.
1564  if (HasVAListArg)
1565    return true;
1566
1567  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
1568    return false;
1569
1570  // Now type check the data expression that matches the
1571  // format specifier.
1572  const Expr *Ex = getDataArg(argIndex);
1573  const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1574  if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1575    // Check if we didn't match because of an implicit cast from a 'char'
1576    // or 'short' to an 'int'.  This is done because printf is a varargs
1577    // function.
1578    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1579      if (ICE->getType() == S.Context.IntTy) {
1580        // All further checking is done on the subexpression.
1581        Ex = ICE->getSubExpr();
1582        if (ATR.matchesType(S.Context, Ex->getType()))
1583          return true;
1584      }
1585
1586    // We may be able to offer a FixItHint if it is a supported type.
1587    PrintfSpecifier fixedFS = FS;
1588    bool success = fixedFS.fixType(Ex->getType());
1589
1590    if (success) {
1591      // Get the fix string from the fixed format specifier
1592      llvm::SmallString<128> buf;
1593      llvm::raw_svector_ostream os(buf);
1594      fixedFS.toString(os);
1595
1596      // FIXME: getRepresentativeType() perhaps should return a string
1597      // instead of a QualType to better handle when the representative
1598      // type is 'wint_t' (which is defined in the system headers).
1599      S.Diag(getLocationOfByte(CS.getStart()),
1600          diag::warn_printf_conversion_argument_type_mismatch)
1601        << ATR.getRepresentativeType(S.Context) << Ex->getType()
1602        << getSpecifierRange(startSpecifier, specifierLen)
1603        << Ex->getSourceRange()
1604        << FixItHint::CreateReplacement(
1605            getSpecifierRange(startSpecifier, specifierLen),
1606            os.str());
1607    }
1608    else {
1609      S.Diag(getLocationOfByte(CS.getStart()),
1610             diag::warn_printf_conversion_argument_type_mismatch)
1611        << ATR.getRepresentativeType(S.Context) << Ex->getType()
1612        << getSpecifierRange(startSpecifier, specifierLen)
1613        << Ex->getSourceRange();
1614    }
1615  }
1616
1617  return true;
1618}
1619
1620//===--- CHECK: Scanf format string checking ------------------------------===//
1621
1622namespace {
1623class CheckScanfHandler : public CheckFormatHandler {
1624public:
1625  CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1626                    const Expr *origFormatExpr, unsigned firstDataArg,
1627                    unsigned numDataArgs, bool isObjCLiteral,
1628                    const char *beg, bool hasVAListArg,
1629                    const CallExpr *theCall, unsigned formatIdx)
1630  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1631                       numDataArgs, isObjCLiteral, beg, hasVAListArg,
1632                       theCall, formatIdx) {}
1633
1634  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1635                            const char *startSpecifier,
1636                            unsigned specifierLen);
1637
1638  bool HandleInvalidScanfConversionSpecifier(
1639          const analyze_scanf::ScanfSpecifier &FS,
1640          const char *startSpecifier,
1641          unsigned specifierLen);
1642
1643  void HandleIncompleteScanList(const char *start, const char *end);
1644};
1645}
1646
1647void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1648                                                 const char *end) {
1649  S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1650    << getSpecifierRange(start, end - start);
1651}
1652
1653bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1654                                        const analyze_scanf::ScanfSpecifier &FS,
1655                                        const char *startSpecifier,
1656                                        unsigned specifierLen) {
1657
1658  const analyze_scanf::ScanfConversionSpecifier &CS =
1659    FS.getConversionSpecifier();
1660
1661  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1662                                          getLocationOfByte(CS.getStart()),
1663                                          startSpecifier, specifierLen,
1664                                          CS.getStart(), CS.getLength());
1665}
1666
1667bool CheckScanfHandler::HandleScanfSpecifier(
1668                                       const analyze_scanf::ScanfSpecifier &FS,
1669                                       const char *startSpecifier,
1670                                       unsigned specifierLen) {
1671
1672  using namespace analyze_scanf;
1673  using namespace analyze_format_string;
1674
1675  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
1676
1677  // Handle case where '%' and '*' don't consume an argument.  These shouldn't
1678  // be used to decide if we are using positional arguments consistently.
1679  if (FS.consumesDataArgument()) {
1680    if (atFirstArg) {
1681      atFirstArg = false;
1682      usesPositionalArgs = FS.usesPositionalArg();
1683    }
1684    else if (usesPositionalArgs != FS.usesPositionalArg()) {
1685      // Cannot mix-and-match positional and non-positional arguments.
1686      S.Diag(getLocationOfByte(CS.getStart()),
1687             diag::warn_format_mix_positional_nonpositional_args)
1688        << getSpecifierRange(startSpecifier, specifierLen);
1689      return false;
1690    }
1691  }
1692
1693  // Check if the field with is non-zero.
1694  const OptionalAmount &Amt = FS.getFieldWidth();
1695  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1696    if (Amt.getConstantAmount() == 0) {
1697      const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1698                                                   Amt.getConstantLength());
1699      S.Diag(getLocationOfByte(Amt.getStart()),
1700             diag::warn_scanf_nonzero_width)
1701        << R << FixItHint::CreateRemoval(R);
1702    }
1703  }
1704
1705  if (!FS.consumesDataArgument()) {
1706    // FIXME: Technically specifying a precision or field width here
1707    // makes no sense.  Worth issuing a warning at some point.
1708    return true;
1709  }
1710
1711  // Consume the argument.
1712  unsigned argIndex = FS.getArgIndex();
1713  if (argIndex < NumDataArgs) {
1714      // The check to see if the argIndex is valid will come later.
1715      // We set the bit here because we may exit early from this
1716      // function if we encounter some other error.
1717    CoveredArgs.set(argIndex);
1718  }
1719
1720  // Check the length modifier is valid with the given conversion specifier.
1721  const LengthModifier &LM = FS.getLengthModifier();
1722  if (!FS.hasValidLengthModifier()) {
1723    S.Diag(getLocationOfByte(LM.getStart()),
1724           diag::warn_format_nonsensical_length)
1725      << LM.toString() << CS.toString()
1726      << getSpecifierRange(startSpecifier, specifierLen)
1727      << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1728                                                    LM.getLength()));
1729  }
1730
1731  // The remaining checks depend on the data arguments.
1732  if (HasVAListArg)
1733    return true;
1734
1735  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
1736    return false;
1737
1738  // FIXME: Check that the argument type matches the format specifier.
1739
1740  return true;
1741}
1742
1743void Sema::CheckFormatString(const StringLiteral *FExpr,
1744                             const Expr *OrigFormatExpr,
1745                             const CallExpr *TheCall, bool HasVAListArg,
1746                             unsigned format_idx, unsigned firstDataArg,
1747                             bool isPrintf) {
1748
1749  // CHECK: is the format string a wide literal?
1750  if (FExpr->isWide()) {
1751    Diag(FExpr->getLocStart(),
1752         diag::warn_format_string_is_wide_literal)
1753    << OrigFormatExpr->getSourceRange();
1754    return;
1755  }
1756
1757  // Str - The format string.  NOTE: this is NOT null-terminated!
1758  llvm::StringRef StrRef = FExpr->getString();
1759  const char *Str = StrRef.data();
1760  unsigned StrLen = StrRef.size();
1761
1762  // CHECK: empty format string?
1763  if (StrLen == 0) {
1764    Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
1765    << OrigFormatExpr->getSourceRange();
1766    return;
1767  }
1768
1769  if (isPrintf) {
1770    CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1771                         TheCall->getNumArgs() - firstDataArg,
1772                         isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1773                         HasVAListArg, TheCall, format_idx);
1774
1775    if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1776      H.DoneProcessing();
1777  }
1778  else {
1779    CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1780                        TheCall->getNumArgs() - firstDataArg,
1781                        isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1782                        HasVAListArg, TheCall, format_idx);
1783
1784    if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1785      H.DoneProcessing();
1786  }
1787}
1788
1789//===--- CHECK: Return Address of Stack Variable --------------------------===//
1790
1791static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1792static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1793
1794/// CheckReturnStackAddr - Check if a return statement returns the address
1795///   of a stack variable.
1796void
1797Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1798                           SourceLocation ReturnLoc) {
1799
1800  Expr *stackE = 0;
1801  llvm::SmallVector<DeclRefExpr *, 8> refVars;
1802
1803  // Perform checking for returned stack addresses, local blocks,
1804  // label addresses or references to temporaries.
1805  if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
1806    stackE = EvalAddr(RetValExp, refVars);
1807  } else if (lhsType->isReferenceType()) {
1808    stackE = EvalVal(RetValExp, refVars);
1809  }
1810
1811  if (stackE == 0)
1812    return; // Nothing suspicious was found.
1813
1814  SourceLocation diagLoc;
1815  SourceRange diagRange;
1816  if (refVars.empty()) {
1817    diagLoc = stackE->getLocStart();
1818    diagRange = stackE->getSourceRange();
1819  } else {
1820    // We followed through a reference variable. 'stackE' contains the
1821    // problematic expression but we will warn at the return statement pointing
1822    // at the reference variable. We will later display the "trail" of
1823    // reference variables using notes.
1824    diagLoc = refVars[0]->getLocStart();
1825    diagRange = refVars[0]->getSourceRange();
1826  }
1827
1828  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1829    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1830                                             : diag::warn_ret_stack_addr)
1831     << DR->getDecl()->getDeclName() << diagRange;
1832  } else if (isa<BlockExpr>(stackE)) { // local block.
1833    Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1834  } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1835    Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1836  } else { // local temporary.
1837    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1838                                             : diag::warn_ret_local_temp_addr)
1839     << diagRange;
1840  }
1841
1842  // Display the "trail" of reference variables that we followed until we
1843  // found the problematic expression using notes.
1844  for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1845    VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1846    // If this var binds to another reference var, show the range of the next
1847    // var, otherwise the var binds to the problematic expression, in which case
1848    // show the range of the expression.
1849    SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1850                                  : stackE->getSourceRange();
1851    Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1852      << VD->getDeclName() << range;
1853  }
1854}
1855
1856/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1857///  check if the expression in a return statement evaluates to an address
1858///  to a location on the stack, a local block, an address of a label, or a
1859///  reference to local temporary. The recursion is used to traverse the
1860///  AST of the return expression, with recursion backtracking when we
1861///  encounter a subexpression that (1) clearly does not lead to one of the
1862///  above problematic expressions (2) is something we cannot determine leads to
1863///  a problematic expression based on such local checking.
1864///
1865///  Both EvalAddr and EvalVal follow through reference variables to evaluate
1866///  the expression that they point to. Such variables are added to the
1867///  'refVars' vector so that we know what the reference variable "trail" was.
1868///
1869///  EvalAddr processes expressions that are pointers that are used as
1870///  references (and not L-values).  EvalVal handles all other values.
1871///  At the base case of the recursion is a check for the above problematic
1872///  expressions.
1873///
1874///  This implementation handles:
1875///
1876///   * pointer-to-pointer casts
1877///   * implicit conversions from array references to pointers
1878///   * taking the address of fields
1879///   * arbitrary interplay between "&" and "*" operators
1880///   * pointer arithmetic from an address of a stack variable
1881///   * taking the address of an array element where the array is on the stack
1882static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1883  if (E->isTypeDependent())
1884      return NULL;
1885
1886  // We should only be called for evaluating pointer expressions.
1887  assert((E->getType()->isAnyPointerType() ||
1888          E->getType()->isBlockPointerType() ||
1889          E->getType()->isObjCQualifiedIdType()) &&
1890         "EvalAddr only works on pointers");
1891
1892  // Our "symbolic interpreter" is just a dispatch off the currently
1893  // viewed AST node.  We then recursively traverse the AST by calling
1894  // EvalAddr and EvalVal appropriately.
1895  switch (E->getStmtClass()) {
1896  case Stmt::ParenExprClass:
1897    // Ignore parentheses.
1898    return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1899
1900  case Stmt::DeclRefExprClass: {
1901    DeclRefExpr *DR = cast<DeclRefExpr>(E);
1902
1903    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1904      // If this is a reference variable, follow through to the expression that
1905      // it points to.
1906      if (V->hasLocalStorage() &&
1907          V->getType()->isReferenceType() && V->hasInit()) {
1908        // Add the reference variable to the "trail".
1909        refVars.push_back(DR);
1910        return EvalAddr(V->getInit(), refVars);
1911      }
1912
1913    return NULL;
1914  }
1915
1916  case Stmt::UnaryOperatorClass: {
1917    // The only unary operator that make sense to handle here
1918    // is AddrOf.  All others don't make sense as pointers.
1919    UnaryOperator *U = cast<UnaryOperator>(E);
1920
1921    if (U->getOpcode() == UO_AddrOf)
1922      return EvalVal(U->getSubExpr(), refVars);
1923    else
1924      return NULL;
1925  }
1926
1927  case Stmt::BinaryOperatorClass: {
1928    // Handle pointer arithmetic.  All other binary operators are not valid
1929    // in this context.
1930    BinaryOperator *B = cast<BinaryOperator>(E);
1931    BinaryOperatorKind op = B->getOpcode();
1932
1933    if (op != BO_Add && op != BO_Sub)
1934      return NULL;
1935
1936    Expr *Base = B->getLHS();
1937
1938    // Determine which argument is the real pointer base.  It could be
1939    // the RHS argument instead of the LHS.
1940    if (!Base->getType()->isPointerType()) Base = B->getRHS();
1941
1942    assert (Base->getType()->isPointerType());
1943    return EvalAddr(Base, refVars);
1944  }
1945
1946  // For conditional operators we need to see if either the LHS or RHS are
1947  // valid DeclRefExpr*s.  If one of them is valid, we return it.
1948  case Stmt::ConditionalOperatorClass: {
1949    ConditionalOperator *C = cast<ConditionalOperator>(E);
1950
1951    // Handle the GNU extension for missing LHS.
1952    if (Expr *lhsExpr = C->getLHS()) {
1953    // In C++, we can have a throw-expression, which has 'void' type.
1954      if (!lhsExpr->getType()->isVoidType())
1955        if (Expr* LHS = EvalAddr(lhsExpr, refVars))
1956          return LHS;
1957    }
1958
1959    // In C++, we can have a throw-expression, which has 'void' type.
1960    if (C->getRHS()->getType()->isVoidType())
1961      return NULL;
1962
1963    return EvalAddr(C->getRHS(), refVars);
1964  }
1965
1966  case Stmt::BlockExprClass:
1967    if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
1968      return E; // local block.
1969    return NULL;
1970
1971  case Stmt::AddrLabelExprClass:
1972    return E; // address of label.
1973
1974  // For casts, we need to handle conversions from arrays to
1975  // pointer values, and pointer-to-pointer conversions.
1976  case Stmt::ImplicitCastExprClass:
1977  case Stmt::CStyleCastExprClass:
1978  case Stmt::CXXFunctionalCastExprClass: {
1979    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1980    QualType T = SubExpr->getType();
1981
1982    if (SubExpr->getType()->isPointerType() ||
1983        SubExpr->getType()->isBlockPointerType() ||
1984        SubExpr->getType()->isObjCQualifiedIdType())
1985      return EvalAddr(SubExpr, refVars);
1986    else if (T->isArrayType())
1987      return EvalVal(SubExpr, refVars);
1988    else
1989      return 0;
1990  }
1991
1992  // C++ casts.  For dynamic casts, static casts, and const casts, we
1993  // are always converting from a pointer-to-pointer, so we just blow
1994  // through the cast.  In the case the dynamic cast doesn't fail (and
1995  // return NULL), we take the conservative route and report cases
1996  // where we return the address of a stack variable.  For Reinterpre
1997  // FIXME: The comment about is wrong; we're not always converting
1998  // from pointer to pointer. I'm guessing that this code should also
1999  // handle references to objects.
2000  case Stmt::CXXStaticCastExprClass:
2001  case Stmt::CXXDynamicCastExprClass:
2002  case Stmt::CXXConstCastExprClass:
2003  case Stmt::CXXReinterpretCastExprClass: {
2004      Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
2005      if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
2006        return EvalAddr(S, refVars);
2007      else
2008        return NULL;
2009  }
2010
2011  // Everything else: we simply don't reason about them.
2012  default:
2013    return NULL;
2014  }
2015}
2016
2017
2018///  EvalVal - This function is complements EvalAddr in the mutual recursion.
2019///   See the comments for EvalAddr for more details.
2020static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
2021do {
2022  // We should only be called for evaluating non-pointer expressions, or
2023  // expressions with a pointer type that are not used as references but instead
2024  // are l-values (e.g., DeclRefExpr with a pointer type).
2025
2026  // Our "symbolic interpreter" is just a dispatch off the currently
2027  // viewed AST node.  We then recursively traverse the AST by calling
2028  // EvalAddr and EvalVal appropriately.
2029  switch (E->getStmtClass()) {
2030  case Stmt::ImplicitCastExprClass: {
2031    ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
2032    if (IE->getValueKind() == VK_LValue) {
2033      E = IE->getSubExpr();
2034      continue;
2035    }
2036    return NULL;
2037  }
2038
2039  case Stmt::DeclRefExprClass: {
2040    // When we hit a DeclRefExpr we are looking at code that refers to a
2041    // variable's name. If it's not a reference variable we check if it has
2042    // local storage within the function, and if so, return the expression.
2043    DeclRefExpr *DR = cast<DeclRefExpr>(E);
2044
2045    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2046      if (V->hasLocalStorage()) {
2047        if (!V->getType()->isReferenceType())
2048          return DR;
2049
2050        // Reference variable, follow through to the expression that
2051        // it points to.
2052        if (V->hasInit()) {
2053          // Add the reference variable to the "trail".
2054          refVars.push_back(DR);
2055          return EvalVal(V->getInit(), refVars);
2056        }
2057      }
2058
2059    return NULL;
2060  }
2061
2062  case Stmt::ParenExprClass: {
2063    // Ignore parentheses.
2064    E = cast<ParenExpr>(E)->getSubExpr();
2065    continue;
2066  }
2067
2068  case Stmt::UnaryOperatorClass: {
2069    // The only unary operator that make sense to handle here
2070    // is Deref.  All others don't resolve to a "name."  This includes
2071    // handling all sorts of rvalues passed to a unary operator.
2072    UnaryOperator *U = cast<UnaryOperator>(E);
2073
2074    if (U->getOpcode() == UO_Deref)
2075      return EvalAddr(U->getSubExpr(), refVars);
2076
2077    return NULL;
2078  }
2079
2080  case Stmt::ArraySubscriptExprClass: {
2081    // Array subscripts are potential references to data on the stack.  We
2082    // retrieve the DeclRefExpr* for the array variable if it indeed
2083    // has local storage.
2084    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
2085  }
2086
2087  case Stmt::ConditionalOperatorClass: {
2088    // For conditional operators we need to see if either the LHS or RHS are
2089    // non-NULL Expr's.  If one is non-NULL, we return it.
2090    ConditionalOperator *C = cast<ConditionalOperator>(E);
2091
2092    // Handle the GNU extension for missing LHS.
2093    if (Expr *lhsExpr = C->getLHS())
2094      if (Expr *LHS = EvalVal(lhsExpr, refVars))
2095        return LHS;
2096
2097    return EvalVal(C->getRHS(), refVars);
2098  }
2099
2100  // Accesses to members are potential references to data on the stack.
2101  case Stmt::MemberExprClass: {
2102    MemberExpr *M = cast<MemberExpr>(E);
2103
2104    // Check for indirect access.  We only want direct field accesses.
2105    if (M->isArrow())
2106      return NULL;
2107
2108    // Check whether the member type is itself a reference, in which case
2109    // we're not going to refer to the member, but to what the member refers to.
2110    if (M->getMemberDecl()->getType()->isReferenceType())
2111      return NULL;
2112
2113    return EvalVal(M->getBase(), refVars);
2114  }
2115
2116  default:
2117    // Check that we don't return or take the address of a reference to a
2118    // temporary. This is only useful in C++.
2119    if (!E->isTypeDependent() && E->isRValue())
2120      return E;
2121
2122    // Everything else: we simply don't reason about them.
2123    return NULL;
2124  }
2125} while (true);
2126}
2127
2128//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2129
2130/// Check for comparisons of floating point operands using != and ==.
2131/// Issue a warning if these are no self-comparisons, as they are not likely
2132/// to do what the programmer intended.
2133void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2134  bool EmitWarning = true;
2135
2136  Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2137  Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
2138
2139  // Special case: check for x == x (which is OK).
2140  // Do not emit warnings for such cases.
2141  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2142    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2143      if (DRL->getDecl() == DRR->getDecl())
2144        EmitWarning = false;
2145
2146
2147  // Special case: check for comparisons against literals that can be exactly
2148  //  represented by APFloat.  In such cases, do not emit a warning.  This
2149  //  is a heuristic: often comparison against such literals are used to
2150  //  detect if a value in a variable has not changed.  This clearly can
2151  //  lead to false negatives.
2152  if (EmitWarning) {
2153    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2154      if (FLL->isExact())
2155        EmitWarning = false;
2156    } else
2157      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2158        if (FLR->isExact())
2159          EmitWarning = false;
2160    }
2161  }
2162
2163  // Check for comparisons with builtin types.
2164  if (EmitWarning)
2165    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
2166      if (CL->isBuiltinCall(Context))
2167        EmitWarning = false;
2168
2169  if (EmitWarning)
2170    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
2171      if (CR->isBuiltinCall(Context))
2172        EmitWarning = false;
2173
2174  // Emit the diagnostic.
2175  if (EmitWarning)
2176    Diag(loc, diag::warn_floatingpoint_eq)
2177      << lex->getSourceRange() << rex->getSourceRange();
2178}
2179
2180//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2181//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
2182
2183namespace {
2184
2185/// Structure recording the 'active' range of an integer-valued
2186/// expression.
2187struct IntRange {
2188  /// The number of bits active in the int.
2189  unsigned Width;
2190
2191  /// True if the int is known not to have negative values.
2192  bool NonNegative;
2193
2194  IntRange(unsigned Width, bool NonNegative)
2195    : Width(Width), NonNegative(NonNegative)
2196  {}
2197
2198  /// Returns the range of the bool type.
2199  static IntRange forBoolType() {
2200    return IntRange(1, true);
2201  }
2202
2203  /// Returns the range of an opaque value of the given integral type.
2204  static IntRange forValueOfType(ASTContext &C, QualType T) {
2205    return forValueOfCanonicalType(C,
2206                          T->getCanonicalTypeInternal().getTypePtr());
2207  }
2208
2209  /// Returns the range of an opaque value of a canonical integral type.
2210  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
2211    assert(T->isCanonicalUnqualified());
2212
2213    if (const VectorType *VT = dyn_cast<VectorType>(T))
2214      T = VT->getElementType().getTypePtr();
2215    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2216      T = CT->getElementType().getTypePtr();
2217
2218    // For enum types, use the known bit width of the enumerators.
2219    if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2220      EnumDecl *Enum = ET->getDecl();
2221      if (!Enum->isDefinition())
2222        return IntRange(C.getIntWidth(QualType(T, 0)), false);
2223
2224      unsigned NumPositive = Enum->getNumPositiveBits();
2225      unsigned NumNegative = Enum->getNumNegativeBits();
2226
2227      return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2228    }
2229
2230    const BuiltinType *BT = cast<BuiltinType>(T);
2231    assert(BT->isInteger());
2232
2233    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2234  }
2235
2236  /// Returns the "target" range of a canonical integral type, i.e.
2237  /// the range of values expressible in the type.
2238  ///
2239  /// This matches forValueOfCanonicalType except that enums have the
2240  /// full range of their type, not the range of their enumerators.
2241  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2242    assert(T->isCanonicalUnqualified());
2243
2244    if (const VectorType *VT = dyn_cast<VectorType>(T))
2245      T = VT->getElementType().getTypePtr();
2246    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2247      T = CT->getElementType().getTypePtr();
2248    if (const EnumType *ET = dyn_cast<EnumType>(T))
2249      T = ET->getDecl()->getIntegerType().getTypePtr();
2250
2251    const BuiltinType *BT = cast<BuiltinType>(T);
2252    assert(BT->isInteger());
2253
2254    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2255  }
2256
2257  /// Returns the supremum of two ranges: i.e. their conservative merge.
2258  static IntRange join(IntRange L, IntRange R) {
2259    return IntRange(std::max(L.Width, R.Width),
2260                    L.NonNegative && R.NonNegative);
2261  }
2262
2263  /// Returns the infinum of two ranges: i.e. their aggressive merge.
2264  static IntRange meet(IntRange L, IntRange R) {
2265    return IntRange(std::min(L.Width, R.Width),
2266                    L.NonNegative || R.NonNegative);
2267  }
2268};
2269
2270IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2271  if (value.isSigned() && value.isNegative())
2272    return IntRange(value.getMinSignedBits(), false);
2273
2274  if (value.getBitWidth() > MaxWidth)
2275    value = value.trunc(MaxWidth);
2276
2277  // isNonNegative() just checks the sign bit without considering
2278  // signedness.
2279  return IntRange(value.getActiveBits(), true);
2280}
2281
2282IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
2283                       unsigned MaxWidth) {
2284  if (result.isInt())
2285    return GetValueRange(C, result.getInt(), MaxWidth);
2286
2287  if (result.isVector()) {
2288    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2289    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2290      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2291      R = IntRange::join(R, El);
2292    }
2293    return R;
2294  }
2295
2296  if (result.isComplexInt()) {
2297    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2298    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2299    return IntRange::join(R, I);
2300  }
2301
2302  // This can happen with lossless casts to intptr_t of "based" lvalues.
2303  // Assume it might use arbitrary bits.
2304  // FIXME: The only reason we need to pass the type in here is to get
2305  // the sign right on this one case.  It would be nice if APValue
2306  // preserved this.
2307  assert(result.isLValue());
2308  return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
2309}
2310
2311/// Pseudo-evaluate the given integer expression, estimating the
2312/// range of values it might take.
2313///
2314/// \param MaxWidth - the width to which the value will be truncated
2315IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2316  E = E->IgnoreParens();
2317
2318  // Try a full evaluation first.
2319  Expr::EvalResult result;
2320  if (E->Evaluate(result, C))
2321    return GetValueRange(C, result.Val, E->getType(), MaxWidth);
2322
2323  // I think we only want to look through implicit casts here; if the
2324  // user has an explicit widening cast, we should treat the value as
2325  // being of the new, wider type.
2326  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
2327    if (CE->getCastKind() == CK_NoOp)
2328      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2329
2330    IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
2331
2332    bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
2333
2334    // Assume that non-integer casts can span the full range of the type.
2335    if (!isIntegerCast)
2336      return OutputTypeRange;
2337
2338    IntRange SubRange
2339      = GetExprRange(C, CE->getSubExpr(),
2340                     std::min(MaxWidth, OutputTypeRange.Width));
2341
2342    // Bail out if the subexpr's range is as wide as the cast type.
2343    if (SubRange.Width >= OutputTypeRange.Width)
2344      return OutputTypeRange;
2345
2346    // Otherwise, we take the smaller width, and we're non-negative if
2347    // either the output type or the subexpr is.
2348    return IntRange(SubRange.Width,
2349                    SubRange.NonNegative || OutputTypeRange.NonNegative);
2350  }
2351
2352  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2353    // If we can fold the condition, just take that operand.
2354    bool CondResult;
2355    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2356      return GetExprRange(C, CondResult ? CO->getTrueExpr()
2357                                        : CO->getFalseExpr(),
2358                          MaxWidth);
2359
2360    // Otherwise, conservatively merge.
2361    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2362    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2363    return IntRange::join(L, R);
2364  }
2365
2366  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2367    switch (BO->getOpcode()) {
2368
2369    // Boolean-valued operations are single-bit and positive.
2370    case BO_LAnd:
2371    case BO_LOr:
2372    case BO_LT:
2373    case BO_GT:
2374    case BO_LE:
2375    case BO_GE:
2376    case BO_EQ:
2377    case BO_NE:
2378      return IntRange::forBoolType();
2379
2380    // The type of these compound assignments is the type of the LHS,
2381    // so the RHS is not necessarily an integer.
2382    case BO_MulAssign:
2383    case BO_DivAssign:
2384    case BO_RemAssign:
2385    case BO_AddAssign:
2386    case BO_SubAssign:
2387      return IntRange::forValueOfType(C, E->getType());
2388
2389    // Operations with opaque sources are black-listed.
2390    case BO_PtrMemD:
2391    case BO_PtrMemI:
2392      return IntRange::forValueOfType(C, E->getType());
2393
2394    // Bitwise-and uses the *infinum* of the two source ranges.
2395    case BO_And:
2396    case BO_AndAssign:
2397      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2398                            GetExprRange(C, BO->getRHS(), MaxWidth));
2399
2400    // Left shift gets black-listed based on a judgement call.
2401    case BO_Shl:
2402      // ...except that we want to treat '1 << (blah)' as logically
2403      // positive.  It's an important idiom.
2404      if (IntegerLiteral *I
2405            = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2406        if (I->getValue() == 1) {
2407          IntRange R = IntRange::forValueOfType(C, E->getType());
2408          return IntRange(R.Width, /*NonNegative*/ true);
2409        }
2410      }
2411      // fallthrough
2412
2413    case BO_ShlAssign:
2414      return IntRange::forValueOfType(C, E->getType());
2415
2416    // Right shift by a constant can narrow its left argument.
2417    case BO_Shr:
2418    case BO_ShrAssign: {
2419      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2420
2421      // If the shift amount is a positive constant, drop the width by
2422      // that much.
2423      llvm::APSInt shift;
2424      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2425          shift.isNonNegative()) {
2426        unsigned zext = shift.getZExtValue();
2427        if (zext >= L.Width)
2428          L.Width = (L.NonNegative ? 0 : 1);
2429        else
2430          L.Width -= zext;
2431      }
2432
2433      return L;
2434    }
2435
2436    // Comma acts as its right operand.
2437    case BO_Comma:
2438      return GetExprRange(C, BO->getRHS(), MaxWidth);
2439
2440    // Black-list pointer subtractions.
2441    case BO_Sub:
2442      if (BO->getLHS()->getType()->isPointerType())
2443        return IntRange::forValueOfType(C, E->getType());
2444      // fallthrough
2445
2446    default:
2447      break;
2448    }
2449
2450    // Treat every other operator as if it were closed on the
2451    // narrowest type that encompasses both operands.
2452    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2453    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2454    return IntRange::join(L, R);
2455  }
2456
2457  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2458    switch (UO->getOpcode()) {
2459    // Boolean-valued operations are white-listed.
2460    case UO_LNot:
2461      return IntRange::forBoolType();
2462
2463    // Operations with opaque sources are black-listed.
2464    case UO_Deref:
2465    case UO_AddrOf: // should be impossible
2466      return IntRange::forValueOfType(C, E->getType());
2467
2468    default:
2469      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2470    }
2471  }
2472
2473  if (dyn_cast<OffsetOfExpr>(E)) {
2474    IntRange::forValueOfType(C, E->getType());
2475  }
2476
2477  FieldDecl *BitField = E->getBitField();
2478  if (BitField) {
2479    llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2480    unsigned BitWidth = BitWidthAP.getZExtValue();
2481
2482    return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2483  }
2484
2485  return IntRange::forValueOfType(C, E->getType());
2486}
2487
2488IntRange GetExprRange(ASTContext &C, Expr *E) {
2489  return GetExprRange(C, E, C.getIntWidth(E->getType()));
2490}
2491
2492/// Checks whether the given value, which currently has the given
2493/// source semantics, has the same value when coerced through the
2494/// target semantics.
2495bool IsSameFloatAfterCast(const llvm::APFloat &value,
2496                          const llvm::fltSemantics &Src,
2497                          const llvm::fltSemantics &Tgt) {
2498  llvm::APFloat truncated = value;
2499
2500  bool ignored;
2501  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2502  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2503
2504  return truncated.bitwiseIsEqual(value);
2505}
2506
2507/// Checks whether the given value, which currently has the given
2508/// source semantics, has the same value when coerced through the
2509/// target semantics.
2510///
2511/// The value might be a vector of floats (or a complex number).
2512bool IsSameFloatAfterCast(const APValue &value,
2513                          const llvm::fltSemantics &Src,
2514                          const llvm::fltSemantics &Tgt) {
2515  if (value.isFloat())
2516    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2517
2518  if (value.isVector()) {
2519    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2520      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2521        return false;
2522    return true;
2523  }
2524
2525  assert(value.isComplexFloat());
2526  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2527          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2528}
2529
2530void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
2531
2532static bool IsZero(Sema &S, Expr *E) {
2533  // Suppress cases where we are comparing against an enum constant.
2534  if (const DeclRefExpr *DR =
2535      dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2536    if (isa<EnumConstantDecl>(DR->getDecl()))
2537      return false;
2538
2539  // Suppress cases where the '0' value is expanded from a macro.
2540  if (E->getLocStart().isMacroID())
2541    return false;
2542
2543  llvm::APSInt Value;
2544  return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2545}
2546
2547static bool HasEnumType(Expr *E) {
2548  // Strip off implicit integral promotions.
2549  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2550    if (ICE->getCastKind() != CK_IntegralCast &&
2551        ICE->getCastKind() != CK_NoOp)
2552      break;
2553    E = ICE->getSubExpr();
2554  }
2555
2556  return E->getType()->isEnumeralType();
2557}
2558
2559void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
2560  BinaryOperatorKind op = E->getOpcode();
2561  if (E->isValueDependent())
2562    return;
2563
2564  if (op == BO_LT && IsZero(S, E->getRHS())) {
2565    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2566      << "< 0" << "false" << HasEnumType(E->getLHS())
2567      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2568  } else if (op == BO_GE && IsZero(S, E->getRHS())) {
2569    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2570      << ">= 0" << "true" << HasEnumType(E->getLHS())
2571      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2572  } else if (op == BO_GT && IsZero(S, E->getLHS())) {
2573    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2574      << "0 >" << "false" << HasEnumType(E->getRHS())
2575      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2576  } else if (op == BO_LE && IsZero(S, E->getLHS())) {
2577    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2578      << "0 <=" << "true" << HasEnumType(E->getRHS())
2579      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2580  }
2581}
2582
2583/// Analyze the operands of the given comparison.  Implements the
2584/// fallback case from AnalyzeComparison.
2585void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
2586  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2587  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2588}
2589
2590/// \brief Implements -Wsign-compare.
2591///
2592/// \param lex the left-hand expression
2593/// \param rex the right-hand expression
2594/// \param OpLoc the location of the joining operator
2595/// \param BinOpc binary opcode or 0
2596void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2597  // The type the comparison is being performed in.
2598  QualType T = E->getLHS()->getType();
2599  assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2600         && "comparison with mismatched types");
2601
2602  // We don't do anything special if this isn't an unsigned integral
2603  // comparison:  we're only interested in integral comparisons, and
2604  // signed comparisons only happen in cases we don't care to warn about.
2605  //
2606  // We also don't care about value-dependent expressions or expressions
2607  // whose result is a constant.
2608  if (!T->hasUnsignedIntegerRepresentation()
2609      || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
2610    return AnalyzeImpConvsInComparison(S, E);
2611
2612  Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2613  Expr *rex = E->getRHS()->IgnoreParenImpCasts();
2614
2615  // Check to see if one of the (unmodified) operands is of different
2616  // signedness.
2617  Expr *signedOperand, *unsignedOperand;
2618  if (lex->getType()->hasSignedIntegerRepresentation()) {
2619    assert(!rex->getType()->hasSignedIntegerRepresentation() &&
2620           "unsigned comparison between two signed integer expressions?");
2621    signedOperand = lex;
2622    unsignedOperand = rex;
2623  } else if (rex->getType()->hasSignedIntegerRepresentation()) {
2624    signedOperand = rex;
2625    unsignedOperand = lex;
2626  } else {
2627    CheckTrivialUnsignedComparison(S, E);
2628    return AnalyzeImpConvsInComparison(S, E);
2629  }
2630
2631  // Otherwise, calculate the effective range of the signed operand.
2632  IntRange signedRange = GetExprRange(S.Context, signedOperand);
2633
2634  // Go ahead and analyze implicit conversions in the operands.  Note
2635  // that we skip the implicit conversions on both sides.
2636  AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2637  AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
2638
2639  // If the signed range is non-negative, -Wsign-compare won't fire,
2640  // but we should still check for comparisons which are always true
2641  // or false.
2642  if (signedRange.NonNegative)
2643    return CheckTrivialUnsignedComparison(S, E);
2644
2645  // For (in)equality comparisons, if the unsigned operand is a
2646  // constant which cannot collide with a overflowed signed operand,
2647  // then reinterpreting the signed operand as unsigned will not
2648  // change the result of the comparison.
2649  if (E->isEqualityOp()) {
2650    unsigned comparisonWidth = S.Context.getIntWidth(T);
2651    IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
2652
2653    // We should never be unable to prove that the unsigned operand is
2654    // non-negative.
2655    assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2656
2657    if (unsignedRange.Width < comparisonWidth)
2658      return;
2659  }
2660
2661  S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2662    << lex->getType() << rex->getType()
2663    << lex->getSourceRange() << rex->getSourceRange();
2664}
2665
2666/// Analyzes an attempt to assign the given value to a bitfield.
2667///
2668/// Returns true if there was something fishy about the attempt.
2669bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2670                               SourceLocation InitLoc) {
2671  assert(Bitfield->isBitField());
2672  if (Bitfield->isInvalidDecl())
2673    return false;
2674
2675  // White-list bool bitfields.
2676  if (Bitfield->getType()->isBooleanType())
2677    return false;
2678
2679  // Ignore value- or type-dependent expressions.
2680  if (Bitfield->getBitWidth()->isValueDependent() ||
2681      Bitfield->getBitWidth()->isTypeDependent() ||
2682      Init->isValueDependent() ||
2683      Init->isTypeDependent())
2684    return false;
2685
2686  Expr *OriginalInit = Init->IgnoreParenImpCasts();
2687
2688  llvm::APSInt Width(32);
2689  Expr::EvalResult InitValue;
2690  if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
2691      !OriginalInit->Evaluate(InitValue, S.Context) ||
2692      !InitValue.Val.isInt())
2693    return false;
2694
2695  const llvm::APSInt &Value = InitValue.Val.getInt();
2696  unsigned OriginalWidth = Value.getBitWidth();
2697  unsigned FieldWidth = Width.getZExtValue();
2698
2699  if (OriginalWidth <= FieldWidth)
2700    return false;
2701
2702  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
2703
2704  // It's fairly common to write values into signed bitfields
2705  // that, if sign-extended, would end up becoming a different
2706  // value.  We don't want to warn about that.
2707  if (Value.isSigned() && Value.isNegative())
2708    TruncatedValue = TruncatedValue.sext(OriginalWidth);
2709  else
2710    TruncatedValue = TruncatedValue.zext(OriginalWidth);
2711
2712  if (Value == TruncatedValue)
2713    return false;
2714
2715  std::string PrettyValue = Value.toString(10);
2716  std::string PrettyTrunc = TruncatedValue.toString(10);
2717
2718  S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2719    << PrettyValue << PrettyTrunc << OriginalInit->getType()
2720    << Init->getSourceRange();
2721
2722  return true;
2723}
2724
2725/// Analyze the given simple or compound assignment for warning-worthy
2726/// operations.
2727void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2728  // Just recurse on the LHS.
2729  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2730
2731  // We want to recurse on the RHS as normal unless we're assigning to
2732  // a bitfield.
2733  if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
2734    if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2735                                  E->getOperatorLoc())) {
2736      // Recurse, ignoring any implicit conversions on the RHS.
2737      return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2738                                        E->getOperatorLoc());
2739    }
2740  }
2741
2742  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2743}
2744
2745/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
2746void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2747                     unsigned diag) {
2748  S.Diag(E->getExprLoc(), diag)
2749    << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
2750}
2751
2752/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
2753void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2754                     SourceLocation CContext, unsigned diag) {
2755  S.Diag(E->getExprLoc(), diag)
2756    << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2757}
2758
2759std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2760  if (!Range.Width) return "0";
2761
2762  llvm::APSInt ValueInRange = Value;
2763  ValueInRange.setIsSigned(!Range.NonNegative);
2764  ValueInRange = ValueInRange.trunc(Range.Width);
2765  return ValueInRange.toString(10);
2766}
2767
2768static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2769  SourceManager &smgr = S.Context.getSourceManager();
2770  return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2771}
2772
2773void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
2774                             SourceLocation CC, bool *ICContext = 0) {
2775  if (E->isTypeDependent() || E->isValueDependent()) return;
2776
2777  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2778  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2779  if (Source == Target) return;
2780  if (Target->isDependentType()) return;
2781
2782  // If the conversion context location is invalid don't complain.
2783  // We also don't want to emit a warning if the issue occurs from the
2784  // instantiation of a system macro.  The problem is that 'getSpellingLoc()'
2785  // is slow, so we delay this check as long as possible.  Once we detect
2786  // we are in that scenario, we just return.
2787  if (CC.isInvalid())
2788    return;
2789
2790  // Never diagnose implicit casts to bool.
2791  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2792    return;
2793
2794  // Strip vector types.
2795  if (isa<VectorType>(Source)) {
2796    if (!isa<VectorType>(Target)) {
2797      if (isFromSystemMacro(S, CC))
2798        return;
2799      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
2800    }
2801
2802    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2803    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2804  }
2805
2806  // Strip complex types.
2807  if (isa<ComplexType>(Source)) {
2808    if (!isa<ComplexType>(Target)) {
2809      if (isFromSystemMacro(S, CC))
2810        return;
2811
2812      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
2813    }
2814
2815    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2816    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2817  }
2818
2819  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2820  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2821
2822  // If the source is floating point...
2823  if (SourceBT && SourceBT->isFloatingPoint()) {
2824    // ...and the target is floating point...
2825    if (TargetBT && TargetBT->isFloatingPoint()) {
2826      // ...then warn if we're dropping FP rank.
2827
2828      // Builtin FP kinds are ordered by increasing FP rank.
2829      if (SourceBT->getKind() > TargetBT->getKind()) {
2830        // Don't warn about float constants that are precisely
2831        // representable in the target type.
2832        Expr::EvalResult result;
2833        if (E->Evaluate(result, S.Context)) {
2834          // Value might be a float, a float vector, or a float complex.
2835          if (IsSameFloatAfterCast(result.Val,
2836                   S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2837                   S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2838            return;
2839        }
2840
2841        if (isFromSystemMacro(S, CC))
2842          return;
2843
2844        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
2845      }
2846      return;
2847    }
2848
2849    // If the target is integral, always warn.
2850    if ((TargetBT && TargetBT->isInteger())) {
2851      if (isFromSystemMacro(S, CC))
2852        return;
2853
2854      Expr *InnerE = E->IgnoreParenImpCasts();
2855      if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) {
2856        DiagnoseImpCast(S, LiteralExpr, T, CC,
2857                        diag::warn_impcast_literal_float_to_integer);
2858      } else {
2859        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2860      }
2861    }
2862
2863    return;
2864  }
2865
2866  if (!Source->isIntegerType() || !Target->isIntegerType())
2867    return;
2868
2869  IntRange SourceRange = GetExprRange(S.Context, E);
2870  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
2871
2872  if (SourceRange.Width > TargetRange.Width) {
2873    // If the source is a constant, use a default-on diagnostic.
2874    // TODO: this should happen for bitfield stores, too.
2875    llvm::APSInt Value(32);
2876    if (E->isIntegerConstantExpr(Value, S.Context)) {
2877      if (isFromSystemMacro(S, CC))
2878        return;
2879
2880      std::string PrettySourceValue = Value.toString(10);
2881      std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2882
2883      S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2884        << PrettySourceValue << PrettyTargetValue
2885        << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2886      return;
2887    }
2888
2889    // People want to build with -Wshorten-64-to-32 and not -Wconversion
2890    // and by god we'll let them.
2891
2892    if (isFromSystemMacro(S, CC))
2893      return;
2894
2895    if (SourceRange.Width == 64 && TargetRange.Width == 32)
2896      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2897    return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
2898  }
2899
2900  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2901      (!TargetRange.NonNegative && SourceRange.NonNegative &&
2902       SourceRange.Width == TargetRange.Width)) {
2903
2904    if (isFromSystemMacro(S, CC))
2905      return;
2906
2907    unsigned DiagID = diag::warn_impcast_integer_sign;
2908
2909    // Traditionally, gcc has warned about this under -Wsign-compare.
2910    // We also want to warn about it in -Wconversion.
2911    // So if -Wconversion is off, use a completely identical diagnostic
2912    // in the sign-compare group.
2913    // The conditional-checking code will
2914    if (ICContext) {
2915      DiagID = diag::warn_impcast_integer_sign_conditional;
2916      *ICContext = true;
2917    }
2918
2919    return DiagnoseImpCast(S, E, T, CC, DiagID);
2920  }
2921
2922  // Diagnose conversions between different enumeration types.
2923  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
2924  // type, to give us better diagnostics.
2925  QualType SourceType = E->getType();
2926  if (!S.getLangOptions().CPlusPlus) {
2927    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2928      if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2929        EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
2930        SourceType = S.Context.getTypeDeclType(Enum);
2931        Source = S.Context.getCanonicalType(SourceType).getTypePtr();
2932      }
2933  }
2934
2935  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
2936    if (const EnumType *TargetEnum = Target->getAs<EnumType>())
2937      if ((SourceEnum->getDecl()->getIdentifier() ||
2938           SourceEnum->getDecl()->getTypedefForAnonDecl()) &&
2939          (TargetEnum->getDecl()->getIdentifier() ||
2940           TargetEnum->getDecl()->getTypedefForAnonDecl()) &&
2941          SourceEnum != TargetEnum) {
2942        if (isFromSystemMacro(S, CC))
2943          return;
2944
2945        return DiagnoseImpCast(S, E, SourceType, T, CC,
2946                               diag::warn_impcast_different_enum_types);
2947      }
2948
2949  return;
2950}
2951
2952void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2953
2954void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
2955                             SourceLocation CC, bool &ICContext) {
2956  E = E->IgnoreParenImpCasts();
2957
2958  if (isa<ConditionalOperator>(E))
2959    return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2960
2961  AnalyzeImplicitConversions(S, E, CC);
2962  if (E->getType() != T)
2963    return CheckImplicitConversion(S, E, T, CC, &ICContext);
2964  return;
2965}
2966
2967void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
2968  SourceLocation CC = E->getQuestionLoc();
2969
2970  AnalyzeImplicitConversions(S, E->getCond(), CC);
2971
2972  bool Suspicious = false;
2973  CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2974  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
2975
2976  // If -Wconversion would have warned about either of the candidates
2977  // for a signedness conversion to the context type...
2978  if (!Suspicious) return;
2979
2980  // ...but it's currently ignored...
2981  if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
2982                                 CC))
2983    return;
2984
2985  // ...and -Wsign-compare isn't...
2986  if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
2987    return;
2988
2989  // ...then check whether it would have warned about either of the
2990  // candidates for a signedness conversion to the condition type.
2991  if (E->getType() != T) {
2992    Suspicious = false;
2993    CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
2994                            E->getType(), CC, &Suspicious);
2995    if (!Suspicious)
2996      CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
2997                              E->getType(), CC, &Suspicious);
2998    if (!Suspicious)
2999      return;
3000  }
3001
3002  // If so, emit a diagnostic under -Wsign-compare.
3003  Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3004  Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3005  S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3006    << lex->getType() << rex->getType()
3007    << lex->getSourceRange() << rex->getSourceRange();
3008}
3009
3010/// AnalyzeImplicitConversions - Find and report any interesting
3011/// implicit conversions in the given expression.  There are a couple
3012/// of competing diagnostics here, -Wconversion and -Wsign-compare.
3013void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
3014  QualType T = OrigE->getType();
3015  Expr *E = OrigE->IgnoreParenImpCasts();
3016
3017  // For conditional operators, we analyze the arguments as if they
3018  // were being fed directly into the output.
3019  if (isa<ConditionalOperator>(E)) {
3020    ConditionalOperator *CO = cast<ConditionalOperator>(E);
3021    CheckConditionalOperator(S, CO, T);
3022    return;
3023  }
3024
3025  // Go ahead and check any implicit conversions we might have skipped.
3026  // The non-canonical typecheck is just an optimization;
3027  // CheckImplicitConversion will filter out dead implicit conversions.
3028  if (E->getType() != T)
3029    CheckImplicitConversion(S, E, T, CC);
3030
3031  // Now continue drilling into this expression.
3032
3033  // Skip past explicit casts.
3034  if (isa<ExplicitCastExpr>(E)) {
3035    E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
3036    return AnalyzeImplicitConversions(S, E, CC);
3037  }
3038
3039  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3040    // Do a somewhat different check with comparison operators.
3041    if (BO->isComparisonOp())
3042      return AnalyzeComparison(S, BO);
3043
3044    // And with assignments and compound assignments.
3045    if (BO->isAssignmentOp())
3046      return AnalyzeAssignment(S, BO);
3047  }
3048
3049  // These break the otherwise-useful invariant below.  Fortunately,
3050  // we don't really need to recurse into them, because any internal
3051  // expressions should have been analyzed already when they were
3052  // built into statements.
3053  if (isa<StmtExpr>(E)) return;
3054
3055  // Don't descend into unevaluated contexts.
3056  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
3057
3058  // Now just recurse over the expression's children.
3059  CC = E->getExprLoc();
3060  for (Stmt::child_range I = E->children(); I; ++I)
3061    AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
3062}
3063
3064} // end anonymous namespace
3065
3066/// Diagnoses "dangerous" implicit conversions within the given
3067/// expression (which is a full expression).  Implements -Wconversion
3068/// and -Wsign-compare.
3069///
3070/// \param CC the "context" location of the implicit conversion, i.e.
3071///   the most location of the syntactic entity requiring the implicit
3072///   conversion
3073void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
3074  // Don't diagnose in unevaluated contexts.
3075  if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3076    return;
3077
3078  // Don't diagnose for value- or type-dependent expressions.
3079  if (E->isTypeDependent() || E->isValueDependent())
3080    return;
3081
3082  // This is not the right CC for (e.g.) a variable initialization.
3083  AnalyzeImplicitConversions(*this, E, CC);
3084}
3085
3086void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3087                                       FieldDecl *BitField,
3088                                       Expr *Init) {
3089  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3090}
3091
3092/// CheckParmsForFunctionDef - Check that the parameters of the given
3093/// function are appropriate for the definition of a function. This
3094/// takes care of any checks that cannot be performed on the
3095/// declaration itself, e.g., that the types of each of the function
3096/// parameters are complete.
3097bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3098                                    bool CheckParameterNames) {
3099  bool HasInvalidParm = false;
3100  for (; P != PEnd; ++P) {
3101    ParmVarDecl *Param = *P;
3102
3103    // C99 6.7.5.3p4: the parameters in a parameter type list in a
3104    // function declarator that is part of a function definition of
3105    // that function shall not have incomplete type.
3106    //
3107    // This is also C++ [dcl.fct]p6.
3108    if (!Param->isInvalidDecl() &&
3109        RequireCompleteType(Param->getLocation(), Param->getType(),
3110                               diag::err_typecheck_decl_incomplete_type)) {
3111      Param->setInvalidDecl();
3112      HasInvalidParm = true;
3113    }
3114
3115    // C99 6.9.1p5: If the declarator includes a parameter type list, the
3116    // declaration of each parameter shall include an identifier.
3117    if (CheckParameterNames &&
3118        Param->getIdentifier() == 0 &&
3119        !Param->isImplicit() &&
3120        !getLangOptions().CPlusPlus)
3121      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
3122
3123    // C99 6.7.5.3p12:
3124    //   If the function declarator is not part of a definition of that
3125    //   function, parameters may have incomplete type and may use the [*]
3126    //   notation in their sequences of declarator specifiers to specify
3127    //   variable length array types.
3128    QualType PType = Param->getOriginalType();
3129    if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3130      if (AT->getSizeModifier() == ArrayType::Star) {
3131        // FIXME: This diagnosic should point the the '[*]' if source-location
3132        // information is added for it.
3133        Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3134      }
3135    }
3136  }
3137
3138  return HasInvalidParm;
3139}
3140
3141/// CheckCastAlign - Implements -Wcast-align, which warns when a
3142/// pointer cast increases the alignment requirements.
3143void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3144  // This is actually a lot of work to potentially be doing on every
3145  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
3146  if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3147                                          TRange.getBegin())
3148        == Diagnostic::Ignored)
3149    return;
3150
3151  // Ignore dependent types.
3152  if (T->isDependentType() || Op->getType()->isDependentType())
3153    return;
3154
3155  // Require that the destination be a pointer type.
3156  const PointerType *DestPtr = T->getAs<PointerType>();
3157  if (!DestPtr) return;
3158
3159  // If the destination has alignment 1, we're done.
3160  QualType DestPointee = DestPtr->getPointeeType();
3161  if (DestPointee->isIncompleteType()) return;
3162  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3163  if (DestAlign.isOne()) return;
3164
3165  // Require that the source be a pointer type.
3166  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3167  if (!SrcPtr) return;
3168  QualType SrcPointee = SrcPtr->getPointeeType();
3169
3170  // Whitelist casts from cv void*.  We already implicitly
3171  // whitelisted casts to cv void*, since they have alignment 1.
3172  // Also whitelist casts involving incomplete types, which implicitly
3173  // includes 'void'.
3174  if (SrcPointee->isIncompleteType()) return;
3175
3176  CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3177  if (SrcAlign >= DestAlign) return;
3178
3179  Diag(TRange.getBegin(), diag::warn_cast_align)
3180    << Op->getType() << T
3181    << static_cast<unsigned>(SrcAlign.getQuantity())
3182    << static_cast<unsigned>(DestAlign.getQuantity())
3183    << TRange << Op->getSourceRange();
3184}
3185
3186static void CheckArrayAccess_Check(Sema &S,
3187                                   const clang::ArraySubscriptExpr *E) {
3188  const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
3189  const ConstantArrayType *ArrayTy =
3190    S.Context.getAsConstantArrayType(BaseExpr->getType());
3191  if (!ArrayTy)
3192    return;
3193
3194  const Expr *IndexExpr = E->getIdx();
3195  if (IndexExpr->isValueDependent())
3196    return;
3197  llvm::APSInt index;
3198  if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
3199    return;
3200
3201  if (index.isUnsigned() || !index.isNegative()) {
3202    llvm::APInt size = ArrayTy->getSize();
3203    if (!size.isStrictlyPositive())
3204      return;
3205    if (size.getBitWidth() > index.getBitWidth())
3206      index = index.sext(size.getBitWidth());
3207    else if (size.getBitWidth() < index.getBitWidth())
3208      size = size.sext(index.getBitWidth());
3209
3210    if (index.slt(size))
3211      return;
3212
3213    S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3214                          S.PDiag(diag::warn_array_index_exceeds_bounds)
3215                            << index.toString(10, true)
3216                            << size.toString(10, true)
3217                            << IndexExpr->getSourceRange());
3218  } else {
3219    S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3220                          S.PDiag(diag::warn_array_index_precedes_bounds)
3221                            << index.toString(10, true)
3222                            << IndexExpr->getSourceRange());
3223  }
3224
3225  const NamedDecl *ND = NULL;
3226  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3227    ND = dyn_cast<NamedDecl>(DRE->getDecl());
3228  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3229    ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3230  if (ND)
3231    S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3232                          S.PDiag(diag::note_array_index_out_of_bounds)
3233                            << ND->getDeclName());
3234}
3235
3236void Sema::CheckArrayAccess(const Expr *expr) {
3237  while (true)
3238    switch (expr->getStmtClass()) {
3239      case Stmt::ParenExprClass:
3240        expr = cast<ParenExpr>(expr)->getSubExpr();
3241        continue;
3242      case Stmt::ArraySubscriptExprClass:
3243        CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3244        return;
3245      case Stmt::ConditionalOperatorClass: {
3246        const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3247        if (const Expr *lhs = cond->getLHS())
3248          CheckArrayAccess(lhs);
3249        if (const Expr *rhs = cond->getRHS())
3250          CheckArrayAccess(rhs);
3251        return;
3252      }
3253      default:
3254        return;
3255    }
3256}
3257