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