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