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