SemaChecking.cpp revision d5f8a4fd4d6dfb0415b93bb7ab721bba5cab1332
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 "Sema.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Basic/Diagnostic.h"
22#include "SemaUtil.h"
23using namespace clang;
24
25/// CheckFunctionCall - Check a direct function call for various correctness
26/// and safety properties not strictly enforced by the C type system.
27Action::ExprResult
28Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCallRaw) {
29  llvm::OwningPtr<CallExpr> TheCall(TheCallRaw);
30  // Get the IdentifierInfo* for the called function.
31  IdentifierInfo *FnInfo = FDecl->getIdentifier();
32
33  switch (FnInfo->getBuiltinID()) {
34  case Builtin::BI__builtin___CFStringMakeConstantString:
35    assert(TheCall->getNumArgs() == 1 &&
36           "Wrong # arguments to builtin CFStringMakeConstantString");
37    if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
38      return true;
39    return TheCall.take();
40  case Builtin::BI__builtin_stdarg_start:
41  case Builtin::BI__builtin_va_start:
42    if (SemaBuiltinVAStart(TheCall.get()))
43      return true;
44    return TheCall.take();
45  case Builtin::BI__builtin_isgreater:
46  case Builtin::BI__builtin_isgreaterequal:
47  case Builtin::BI__builtin_isless:
48  case Builtin::BI__builtin_islessequal:
49  case Builtin::BI__builtin_islessgreater:
50  case Builtin::BI__builtin_isunordered:
51    if (SemaBuiltinUnorderedCompare(TheCall.get()))
52      return true;
53    return TheCall.take();
54  case Builtin::BI__builtin_return_address:
55  case Builtin::BI__builtin_frame_address:
56    if (SemaBuiltinStackAddress(TheCall.get()))
57      return true;
58    return TheCall.take();
59  case Builtin::BI__builtin_shufflevector:
60    return SemaBuiltinShuffleVector(TheCall.get());
61  case Builtin::BI__builtin_prefetch:
62    if (SemaBuiltinPrefetch(TheCall.get()))
63      return true;
64    return TheCall.take();
65  case Builtin::BI__builtin_object_size:
66    if (SemaBuiltinObjectSize(TheCall.get()))
67      return true;
68  }
69
70  // Search the KnownFunctionIDs for the identifier.
71  unsigned i = 0, e = id_num_known_functions;
72  for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
73  if (i == e) return TheCall.take();
74
75  // Printf checking.
76  if (i <= id_vprintf) {
77    // Retrieve the index of the format string parameter and determine
78    // if the function is passed a va_arg argument.
79    unsigned format_idx = 0;
80    bool HasVAListArg = false;
81
82    switch (i) {
83    default: assert(false && "No format string argument index.");
84    case id_printf:    format_idx = 0; break;
85    case id_fprintf:   format_idx = 1; break;
86    case id_sprintf:   format_idx = 1; break;
87    case id_snprintf:  format_idx = 2; break;
88    case id_asprintf:  format_idx = 1; break;
89    case id_NSLog:     format_idx = 0; break;
90    case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
91    case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
92    case id_vfprintf:  format_idx = 1; HasVAListArg = true; break;
93    case id_vsprintf:  format_idx = 1; HasVAListArg = true; break;
94    case id_vprintf:   format_idx = 0; HasVAListArg = true; break;
95    }
96
97    CheckPrintfArguments(TheCall.get(), HasVAListArg, format_idx);
98  }
99
100  return TheCall.take();
101}
102
103/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
104/// CFString constructor is correct
105bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
106  Arg = Arg->IgnoreParenCasts();
107
108  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
109
110  if (!Literal || Literal->isWide()) {
111    Diag(Arg->getLocStart(),
112         diag::err_cfstring_literal_not_string_constant,
113         Arg->getSourceRange());
114    return true;
115  }
116
117  const char *Data = Literal->getStrData();
118  unsigned Length = Literal->getByteLength();
119
120  for (unsigned i = 0; i < Length; ++i) {
121    if (!isascii(Data[i])) {
122      Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
123           diag::warn_cfstring_literal_contains_non_ascii_character,
124           Arg->getSourceRange());
125      break;
126    }
127
128    if (!Data[i]) {
129      Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
130           diag::warn_cfstring_literal_contains_nul_character,
131           Arg->getSourceRange());
132      break;
133    }
134  }
135
136  return false;
137}
138
139/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
140/// Emit an error and return true on failure, return false on success.
141bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
142  Expr *Fn = TheCall->getCallee();
143  if (TheCall->getNumArgs() > 2) {
144    Diag(TheCall->getArg(2)->getLocStart(),
145         diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
146         SourceRange(TheCall->getArg(2)->getLocStart(),
147                     (*(TheCall->arg_end()-1))->getLocEnd()));
148    return true;
149  }
150
151  // Determine whether the current function is variadic or not.
152  bool isVariadic;
153  if (getCurFunctionDecl())
154    isVariadic =
155      cast<FunctionTypeProto>(getCurFunctionDecl()->getType())->isVariadic();
156  else
157    isVariadic = getCurMethodDecl()->isVariadic();
158
159  if (!isVariadic) {
160    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
161    return true;
162  }
163
164  // Verify that the second argument to the builtin is the last argument of the
165  // current function or method.
166  bool SecondArgIsLastNamedArgument = false;
167  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
168
169  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
170    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
171      // FIXME: This isn't correct for methods (results in bogus warning).
172      // Get the last formal in the current function.
173      const ParmVarDecl *LastArg;
174      if (getCurFunctionDecl())
175        LastArg = *(getCurFunctionDecl()->param_end()-1);
176      else
177        LastArg = *(getCurMethodDecl()->param_end()-1);
178      SecondArgIsLastNamedArgument = PV == LastArg;
179    }
180  }
181
182  if (!SecondArgIsLastNamedArgument)
183    Diag(TheCall->getArg(1)->getLocStart(),
184         diag::warn_second_parameter_of_va_start_not_last_named_argument);
185  return false;
186}
187
188/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
189/// friends.  This is declared to take (...), so we have to check everything.
190bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
191  if (TheCall->getNumArgs() < 2)
192    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args);
193  if (TheCall->getNumArgs() > 2)
194    return Diag(TheCall->getArg(2)->getLocStart(),
195                diag::err_typecheck_call_too_many_args,
196                SourceRange(TheCall->getArg(2)->getLocStart(),
197                            (*(TheCall->arg_end()-1))->getLocEnd()));
198
199  Expr *OrigArg0 = TheCall->getArg(0);
200  Expr *OrigArg1 = TheCall->getArg(1);
201
202  // Do standard promotions between the two arguments, returning their common
203  // type.
204  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
205
206  // If the common type isn't a real floating type, then the arguments were
207  // invalid for this operation.
208  if (!Res->isRealFloatingType())
209    return Diag(OrigArg0->getLocStart(),
210                diag::err_typecheck_call_invalid_ordered_compare,
211                OrigArg0->getType().getAsString(),
212                OrigArg1->getType().getAsString(),
213                SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()));
214
215  return false;
216}
217
218bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
219  // The signature for these builtins is exact; the only thing we need
220  // to check is that the argument is a constant.
221  SourceLocation Loc;
222  if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
223    return Diag(Loc, diag::err_stack_const_level, TheCall->getSourceRange());
224
225  return false;
226}
227
228/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
229// This is declared to take (...), so we have to check everything.
230Action::ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
231  if (TheCall->getNumArgs() < 3)
232    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
233                TheCall->getSourceRange());
234
235  QualType FAType = TheCall->getArg(0)->getType();
236  QualType SAType = TheCall->getArg(1)->getType();
237
238  if (!FAType->isVectorType() || !SAType->isVectorType()) {
239    Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector,
240         SourceRange(TheCall->getArg(0)->getLocStart(),
241                     TheCall->getArg(1)->getLocEnd()));
242    return true;
243  }
244
245  if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
246      Context.getCanonicalType(SAType).getUnqualifiedType()) {
247    Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector,
248         SourceRange(TheCall->getArg(0)->getLocStart(),
249                     TheCall->getArg(1)->getLocEnd()));
250    return true;
251  }
252
253  unsigned numElements = FAType->getAsVectorType()->getNumElements();
254  if (TheCall->getNumArgs() != numElements+2) {
255    if (TheCall->getNumArgs() < numElements+2)
256      return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
257                  TheCall->getSourceRange());
258    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
259                TheCall->getSourceRange());
260  }
261
262  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
263    llvm::APSInt Result(32);
264    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
265      return Diag(TheCall->getLocStart(),
266                  diag::err_shufflevector_nonconstant_argument,
267                  TheCall->getArg(i)->getSourceRange());
268
269    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
270      return Diag(TheCall->getLocStart(),
271                  diag::err_shufflevector_argument_too_large,
272                  TheCall->getArg(i)->getSourceRange());
273  }
274
275  llvm::SmallVector<Expr*, 32> exprs;
276
277  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
278    exprs.push_back(TheCall->getArg(i));
279    TheCall->setArg(i, 0);
280  }
281
282  return new ShuffleVectorExpr(exprs.begin(), numElements+2, FAType,
283                               TheCall->getCallee()->getLocStart(),
284                               TheCall->getRParenLoc());
285}
286
287/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
288// This is declared to take (const void*, ...) and can take two
289// optional constant int args.
290bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
291  unsigned numArgs = TheCall->getNumArgs();
292  bool res = false;
293
294  if (numArgs > 3) {
295    res |= Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
296                TheCall->getSourceRange());
297  }
298
299  // Argument 0 is checked for us and the remaining arguments must be
300  // constant integers.
301  for (unsigned i=1; i<numArgs; ++i) {
302    Expr *Arg = TheCall->getArg(i);
303    QualType RWType = Arg->getType();
304
305    const BuiltinType *BT = RWType->getAsBuiltinType();
306    llvm::APSInt Result;
307    if (!BT || BT->getKind() != BuiltinType::Int ||
308        !Arg->isIntegerConstantExpr(Result, Context)) {
309      if (Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument,
310               SourceRange(Arg->getLocStart(), Arg->getLocEnd()))) {
311        res = true;
312        continue;
313      }
314    }
315
316    // FIXME: gcc issues a warning and rewrites these to 0. These
317    // seems especially odd for the third argument since the default
318    // is 3.
319    if (i==1) {
320      if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
321        res |= Diag(TheCall->getLocStart(), diag::err_argument_invalid_range,
322                    "0", "1",
323                    SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
324    } else {
325      if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
326        res |= Diag(TheCall->getLocStart(), diag::err_argument_invalid_range,
327                    "0", "3",
328                    SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
329    }
330  }
331
332  return res;
333}
334
335/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
336/// int type). This simply type checks that type is one of the defined
337/// constants (0-3).
338bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
339  Expr *Arg = TheCall->getArg(1);
340  QualType ArgType = Arg->getType();
341  const BuiltinType *BT = ArgType->getAsBuiltinType();
342  llvm::APSInt Result(32);
343  if (!BT || BT->getKind() != BuiltinType::Int ||
344      !Arg->isIntegerConstantExpr(Result, Context)) {
345    return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument,
346                SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
347  }
348
349  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
350    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range,
351                "0", "3",
352                SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
353  }
354
355  return false;
356}
357
358/// CheckPrintfArguments - Check calls to printf (and similar functions) for
359/// correct use of format strings.
360///
361///  HasVAListArg - A predicate indicating whether the printf-like
362///    function is passed an explicit va_arg argument (e.g., vprintf)
363///
364///  format_idx - The index into Args for the format string.
365///
366/// Improper format strings to functions in the printf family can be
367/// the source of bizarre bugs and very serious security holes.  A
368/// good source of information is available in the following paper
369/// (which includes additional references):
370///
371///  FormatGuard: Automatic Protection From printf Format String
372///  Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
373///
374/// Functionality implemented:
375///
376///  We can statically check the following properties for string
377///  literal format strings for non v.*printf functions (where the
378///  arguments are passed directly):
379//
380///  (1) Are the number of format conversions equal to the number of
381///      data arguments?
382///
383///  (2) Does each format conversion correctly match the type of the
384///      corresponding data argument?  (TODO)
385///
386/// Moreover, for all printf functions we can:
387///
388///  (3) Check for a missing format string (when not caught by type checking).
389///
390///  (4) Check for no-operation flags; e.g. using "#" with format
391///      conversion 'c'  (TODO)
392///
393///  (5) Check the use of '%n', a major source of security holes.
394///
395///  (6) Check for malformed format conversions that don't specify anything.
396///
397///  (7) Check for empty format strings.  e.g: printf("");
398///
399///  (8) Check that the format string is a wide literal.
400///
401///  (9) Also check the arguments of functions with the __format__ attribute.
402///      (TODO).
403///
404/// All of these checks can be done by parsing the format string.
405///
406/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
407void
408Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
409                           unsigned format_idx) {
410  Expr *Fn = TheCall->getCallee();
411
412  // CHECK: printf-like function is called with no format string.
413  if (format_idx >= TheCall->getNumArgs()) {
414    Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
415         Fn->getSourceRange());
416    return;
417  }
418
419  Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
420
421  // CHECK: format string is not a string literal.
422  //
423  // Dynamically generated format strings are difficult to
424  // automatically vet at compile time.  Requiring that format strings
425  // are string literals: (1) permits the checking of format strings by
426  // the compiler and thereby (2) can practically remove the source of
427  // many format string exploits.
428
429  // Format string can be either ObjC string (e.g. @"%d") or
430  // C string (e.g. "%d")
431  // ObjC string uses the same format specifiers as C string, so we can use
432  // the same format string checking logic for both ObjC and C strings.
433  ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
434  StringLiteral *FExpr = NULL;
435
436  if(ObjCFExpr != NULL)
437    FExpr = ObjCFExpr->getString();
438  else
439    FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
440
441  if (FExpr == NULL) {
442    // For vprintf* functions (i.e., HasVAListArg==true), we add a
443    // special check to see if the format string is a function parameter
444    // of the function calling the printf function.  If the function
445    // has an attribute indicating it is a printf-like function, then we
446    // should suppress warnings concerning non-literals being used in a call
447    // to a vprintf function.  For example:
448    //
449    // void
450    // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
451    //      va_list ap;
452    //      va_start(ap, fmt);
453    //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
454    //      ...
455    //
456    //
457    //  FIXME: We don't have full attribute support yet, so just check to see
458    //    if the argument is a DeclRefExpr that references a parameter.  We'll
459    //    add proper support for checking the attribute later.
460    if (HasVAListArg)
461      if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
462        if (isa<ParmVarDecl>(DR->getDecl()))
463          return;
464
465    Diag(TheCall->getArg(format_idx)->getLocStart(),
466         diag::warn_printf_not_string_constant,
467         OrigFormatExpr->getSourceRange());
468    return;
469  }
470
471  // CHECK: is the format string a wide literal?
472  if (FExpr->isWide()) {
473    Diag(FExpr->getLocStart(),
474         diag::warn_printf_format_string_is_wide_literal,
475         OrigFormatExpr->getSourceRange());
476    return;
477  }
478
479  // Str - The format string.  NOTE: this is NOT null-terminated!
480  const char * const Str = FExpr->getStrData();
481
482  // CHECK: empty format string?
483  const unsigned StrLen = FExpr->getByteLength();
484
485  if (StrLen == 0) {
486    Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
487         OrigFormatExpr->getSourceRange());
488    return;
489  }
490
491  // We process the format string using a binary state machine.  The
492  // current state is stored in CurrentState.
493  enum {
494    state_OrdChr,
495    state_Conversion
496  } CurrentState = state_OrdChr;
497
498  // numConversions - The number of conversions seen so far.  This is
499  //  incremented as we traverse the format string.
500  unsigned numConversions = 0;
501
502  // numDataArgs - The number of data arguments after the format
503  //  string.  This can only be determined for non vprintf-like
504  //  functions.  For those functions, this value is 1 (the sole
505  //  va_arg argument).
506  unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
507
508  // Inspect the format string.
509  unsigned StrIdx = 0;
510
511  // LastConversionIdx - Index within the format string where we last saw
512  //  a '%' character that starts a new format conversion.
513  unsigned LastConversionIdx = 0;
514
515  for (; StrIdx < StrLen; ++StrIdx) {
516
517    // Is the number of detected conversion conversions greater than
518    // the number of matching data arguments?  If so, stop.
519    if (!HasVAListArg && numConversions > numDataArgs) break;
520
521    // Handle "\0"
522    if (Str[StrIdx] == '\0') {
523      // The string returned by getStrData() is not null-terminated,
524      // so the presence of a null character is likely an error.
525      Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
526           diag::warn_printf_format_string_contains_null_char,
527           OrigFormatExpr->getSourceRange());
528      return;
529    }
530
531    // Ordinary characters (not processing a format conversion).
532    if (CurrentState == state_OrdChr) {
533      if (Str[StrIdx] == '%') {
534        CurrentState = state_Conversion;
535        LastConversionIdx = StrIdx;
536      }
537      continue;
538    }
539
540    // Seen '%'.  Now processing a format conversion.
541    switch (Str[StrIdx]) {
542    // Handle dynamic precision or width specifier.
543    case '*': {
544      ++numConversions;
545
546      if (!HasVAListArg && numConversions > numDataArgs) {
547        SourceLocation Loc = FExpr->getLocStart();
548        Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
549
550        if (Str[StrIdx-1] == '.')
551          Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
552               OrigFormatExpr->getSourceRange());
553        else
554          Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
555               OrigFormatExpr->getSourceRange());
556
557        // Don't do any more checking.  We'll just emit spurious errors.
558        return;
559      }
560
561      // Perform type checking on width/precision specifier.
562      Expr *E = TheCall->getArg(format_idx+numConversions);
563      if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
564        if (BT->getKind() == BuiltinType::Int)
565          break;
566
567      SourceLocation Loc =
568        PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
569
570      if (Str[StrIdx-1] == '.')
571        Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
572             E->getType().getAsString(), E->getSourceRange());
573      else
574        Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
575             E->getType().getAsString(), E->getSourceRange());
576
577      break;
578    }
579
580    // Characters which can terminate a format conversion
581    // (e.g. "%d").  Characters that specify length modifiers or
582    // other flags are handled by the default case below.
583    //
584    // FIXME: additional checks will go into the following cases.
585    case 'i':
586    case 'd':
587    case 'o':
588    case 'u':
589    case 'x':
590    case 'X':
591    case 'D':
592    case 'O':
593    case 'U':
594    case 'e':
595    case 'E':
596    case 'f':
597    case 'F':
598    case 'g':
599    case 'G':
600    case 'a':
601    case 'A':
602    case 'c':
603    case 'C':
604    case 'S':
605    case 's':
606    case 'p':
607      ++numConversions;
608      CurrentState = state_OrdChr;
609      break;
610
611    // CHECK: Are we using "%n"?  Issue a warning.
612    case 'n': {
613      ++numConversions;
614      CurrentState = state_OrdChr;
615      SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
616                                                      LastConversionIdx+1);
617
618      Diag(Loc, diag::warn_printf_write_back, OrigFormatExpr->getSourceRange());
619      break;
620    }
621
622    // Handle "%@"
623    case '@':
624      // %@ is allowed in ObjC format strings only.
625      if(ObjCFExpr != NULL)
626        CurrentState = state_OrdChr;
627      else {
628        // Issue a warning: invalid format conversion.
629        SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
630                                                    LastConversionIdx+1);
631
632        Diag(Loc, diag::warn_printf_invalid_conversion,
633          std::string(Str+LastConversionIdx,
634          Str+std::min(LastConversionIdx+2, StrLen)),
635          OrigFormatExpr->getSourceRange());
636      }
637      ++numConversions;
638      break;
639
640    // Handle "%%"
641    case '%':
642      // Sanity check: Was the first "%" character the previous one?
643      // If not, we will assume that we have a malformed format
644      // conversion, and that the current "%" character is the start
645      // of a new conversion.
646      if (StrIdx - LastConversionIdx == 1)
647        CurrentState = state_OrdChr;
648      else {
649        // Issue a warning: invalid format conversion.
650        SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
651                                                        LastConversionIdx+1);
652
653        Diag(Loc, diag::warn_printf_invalid_conversion,
654             std::string(Str+LastConversionIdx, Str+StrIdx),
655             OrigFormatExpr->getSourceRange());
656
657        // This conversion is broken.  Advance to the next format
658        // conversion.
659        LastConversionIdx = StrIdx;
660        ++numConversions;
661      }
662      break;
663
664    default:
665      // This case catches all other characters: flags, widths, etc.
666      // We should eventually process those as well.
667      break;
668    }
669  }
670
671  if (CurrentState == state_Conversion) {
672    // Issue a warning: invalid format conversion.
673    SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
674                                                    LastConversionIdx+1);
675
676    Diag(Loc, diag::warn_printf_invalid_conversion,
677         std::string(Str+LastConversionIdx,
678                     Str+std::min(LastConversionIdx+2, StrLen)),
679         OrigFormatExpr->getSourceRange());
680    return;
681  }
682
683  if (!HasVAListArg) {
684    // CHECK: Does the number of format conversions exceed the number
685    //        of data arguments?
686    if (numConversions > numDataArgs) {
687      SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
688                                                      LastConversionIdx);
689
690      Diag(Loc, diag::warn_printf_insufficient_data_args,
691           OrigFormatExpr->getSourceRange());
692    }
693    // CHECK: Does the number of data arguments exceed the number of
694    //        format conversions in the format string?
695    else if (numConversions < numDataArgs)
696      Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
697           diag::warn_printf_too_many_data_args,
698           OrigFormatExpr->getSourceRange());
699  }
700}
701
702//===--- CHECK: Return Address of Stack Variable --------------------------===//
703
704static DeclRefExpr* EvalVal(Expr *E);
705static DeclRefExpr* EvalAddr(Expr* E);
706
707/// CheckReturnStackAddr - Check if a return statement returns the address
708///   of a stack variable.
709void
710Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
711                           SourceLocation ReturnLoc) {
712
713  // Perform checking for returned stack addresses.
714  if (lhsType->isPointerType()) {
715    if (DeclRefExpr *DR = EvalAddr(RetValExp))
716      Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
717           DR->getDecl()->getIdentifier()->getName(),
718           RetValExp->getSourceRange());
719  }
720  // Perform checking for stack values returned by reference.
721  else if (lhsType->isReferenceType()) {
722    // Check for an implicit cast to a reference.
723    if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
724      if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
725        Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
726             DR->getDecl()->getIdentifier()->getName(),
727             RetValExp->getSourceRange());
728  }
729}
730
731/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
732///  check if the expression in a return statement evaluates to an address
733///  to a location on the stack.  The recursion is used to traverse the
734///  AST of the return expression, with recursion backtracking when we
735///  encounter a subexpression that (1) clearly does not lead to the address
736///  of a stack variable or (2) is something we cannot determine leads to
737///  the address of a stack variable based on such local checking.
738///
739///  EvalAddr processes expressions that are pointers that are used as
740///  references (and not L-values).  EvalVal handles all other values.
741///  At the base case of the recursion is a check for a DeclRefExpr* in
742///  the refers to a stack variable.
743///
744///  This implementation handles:
745///
746///   * pointer-to-pointer casts
747///   * implicit conversions from array references to pointers
748///   * taking the address of fields
749///   * arbitrary interplay between "&" and "*" operators
750///   * pointer arithmetic from an address of a stack variable
751///   * taking the address of an array element where the array is on the stack
752static DeclRefExpr* EvalAddr(Expr *E) {
753  // We should only be called for evaluating pointer expressions.
754  assert((E->getType()->isPointerType() ||
755          E->getType()->isObjCQualifiedIdType()) &&
756         "EvalAddr only works on pointers");
757
758  // Our "symbolic interpreter" is just a dispatch off the currently
759  // viewed AST node.  We then recursively traverse the AST by calling
760  // EvalAddr and EvalVal appropriately.
761  switch (E->getStmtClass()) {
762  case Stmt::ParenExprClass:
763    // Ignore parentheses.
764    return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
765
766  case Stmt::UnaryOperatorClass: {
767    // The only unary operator that make sense to handle here
768    // is AddrOf.  All others don't make sense as pointers.
769    UnaryOperator *U = cast<UnaryOperator>(E);
770
771    if (U->getOpcode() == UnaryOperator::AddrOf)
772      return EvalVal(U->getSubExpr());
773    else
774      return NULL;
775  }
776
777  case Stmt::BinaryOperatorClass: {
778    // Handle pointer arithmetic.  All other binary operators are not valid
779    // in this context.
780    BinaryOperator *B = cast<BinaryOperator>(E);
781    BinaryOperator::Opcode op = B->getOpcode();
782
783    if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
784      return NULL;
785
786    Expr *Base = B->getLHS();
787
788    // Determine which argument is the real pointer base.  It could be
789    // the RHS argument instead of the LHS.
790    if (!Base->getType()->isPointerType()) Base = B->getRHS();
791
792    assert (Base->getType()->isPointerType());
793    return EvalAddr(Base);
794  }
795
796  // For conditional operators we need to see if either the LHS or RHS are
797  // valid DeclRefExpr*s.  If one of them is valid, we return it.
798  case Stmt::ConditionalOperatorClass: {
799    ConditionalOperator *C = cast<ConditionalOperator>(E);
800
801    // Handle the GNU extension for missing LHS.
802    if (Expr *lhsExpr = C->getLHS())
803      if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
804        return LHS;
805
806     return EvalAddr(C->getRHS());
807  }
808
809  // For casts, we need to handle conversions from arrays to
810  // pointer values, and pointer-to-pointer conversions.
811  case Stmt::ExplicitCastExprClass:
812  case Stmt::ImplicitCastExprClass: {
813
814    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
815    QualType T = SubExpr->getType();
816
817    if (T->isPointerType() || T->isObjCQualifiedIdType())
818      return EvalAddr(SubExpr);
819    else if (T->isArrayType())
820      return EvalVal(SubExpr);
821    else
822      return 0;
823  }
824
825  // C++ casts.  For dynamic casts, static casts, and const casts, we
826  // are always converting from a pointer-to-pointer, so we just blow
827  // through the cast.  In the case the dynamic cast doesn't fail
828  // (and return NULL), we take the conservative route and report cases
829  // where we return the address of a stack variable.  For Reinterpre
830  case Stmt::CXXCastExprClass: {
831    CXXCastExpr *C = cast<CXXCastExpr>(E);
832
833    if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
834      Expr *S = C->getSubExpr();
835      if (S->getType()->isPointerType())
836        return EvalAddr(S);
837      else
838        return NULL;
839    }
840    else
841      return EvalAddr(C->getSubExpr());
842  }
843
844  // Everything else: we simply don't reason about them.
845  default:
846    return NULL;
847  }
848}
849
850
851///  EvalVal - This function is complements EvalAddr in the mutual recursion.
852///   See the comments for EvalAddr for more details.
853static DeclRefExpr* EvalVal(Expr *E) {
854
855  // We should only be called for evaluating non-pointer expressions, or
856  // expressions with a pointer type that are not used as references but instead
857  // are l-values (e.g., DeclRefExpr with a pointer type).
858
859  // Our "symbolic interpreter" is just a dispatch off the currently
860  // viewed AST node.  We then recursively traverse the AST by calling
861  // EvalAddr and EvalVal appropriately.
862  switch (E->getStmtClass()) {
863  case Stmt::DeclRefExprClass: {
864    // DeclRefExpr: the base case.  When we hit a DeclRefExpr we are looking
865    //  at code that refers to a variable's name.  We check if it has local
866    //  storage within the function, and if so, return the expression.
867    DeclRefExpr *DR = cast<DeclRefExpr>(E);
868
869    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
870      if(V->hasLocalStorage()) return DR;
871
872    return NULL;
873  }
874
875  case Stmt::ParenExprClass:
876    // Ignore parentheses.
877    return EvalVal(cast<ParenExpr>(E)->getSubExpr());
878
879  case Stmt::UnaryOperatorClass: {
880    // The only unary operator that make sense to handle here
881    // is Deref.  All others don't resolve to a "name."  This includes
882    // handling all sorts of rvalues passed to a unary operator.
883    UnaryOperator *U = cast<UnaryOperator>(E);
884
885    if (U->getOpcode() == UnaryOperator::Deref)
886      return EvalAddr(U->getSubExpr());
887
888    return NULL;
889  }
890
891  case Stmt::ArraySubscriptExprClass: {
892    // Array subscripts are potential references to data on the stack.  We
893    // retrieve the DeclRefExpr* for the array variable if it indeed
894    // has local storage.
895    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
896  }
897
898  case Stmt::ConditionalOperatorClass: {
899    // For conditional operators we need to see if either the LHS or RHS are
900    // non-NULL DeclRefExpr's.  If one is non-NULL, we return it.
901    ConditionalOperator *C = cast<ConditionalOperator>(E);
902
903    // Handle the GNU extension for missing LHS.
904    if (Expr *lhsExpr = C->getLHS())
905      if (DeclRefExpr *LHS = EvalVal(lhsExpr))
906        return LHS;
907
908    return EvalVal(C->getRHS());
909  }
910
911  // Accesses to members are potential references to data on the stack.
912  case Stmt::MemberExprClass: {
913    MemberExpr *M = cast<MemberExpr>(E);
914
915    // Check for indirect access.  We only want direct field accesses.
916    if (!M->isArrow())
917      return EvalVal(M->getBase());
918    else
919      return NULL;
920  }
921
922  // Everything else: we simply don't reason about them.
923  default:
924    return NULL;
925  }
926}
927
928//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
929
930/// Check for comparisons of floating point operands using != and ==.
931/// Issue a warning if these are no self-comparisons, as they are not likely
932/// to do what the programmer intended.
933void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
934  bool EmitWarning = true;
935
936  Expr* LeftExprSansParen = lex->IgnoreParens();
937  Expr* RightExprSansParen = rex->IgnoreParens();
938
939  // Special case: check for x == x (which is OK).
940  // Do not emit warnings for such cases.
941  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
942    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
943      if (DRL->getDecl() == DRR->getDecl())
944        EmitWarning = false;
945
946
947  // Special case: check for comparisons against literals that can be exactly
948  //  represented by APFloat.  In such cases, do not emit a warning.  This
949  //  is a heuristic: often comparison against such literals are used to
950  //  detect if a value in a variable has not changed.  This clearly can
951  //  lead to false negatives.
952  if (EmitWarning) {
953    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
954      if (FLL->isExact())
955        EmitWarning = false;
956    }
957    else
958      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
959        if (FLR->isExact())
960          EmitWarning = false;
961    }
962  }
963
964  // Check for comparisons with builtin types.
965  if (EmitWarning)
966    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
967      if (isCallBuiltin(CL))
968        EmitWarning = false;
969
970  if (EmitWarning)
971    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
972      if (isCallBuiltin(CR))
973        EmitWarning = false;
974
975  // Emit the diagnostic.
976  if (EmitWarning)
977    Diag(loc, diag::warn_floatingpoint_eq,
978         lex->getSourceRange(),rex->getSourceRange());
979}
980