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