SemaChecking.cpp revision 199c3d6cd16aebbb9c7f0d42af9d922c9628bf70
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements extra semantic analysis beyond what is enforced
11//  by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/CharUnits.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Lex/Preprocessor.h"
23#include <limits>
24using namespace clang;
25
26/// getLocationOfStringLiteralByte - Return a source location that points to the
27/// specified byte of the specified string literal.
28///
29/// Strings are amazingly complex.  They can be formed from multiple tokens and
30/// can have escape sequences in them in addition to the usual trigraph and
31/// escaped newline business.  This routine handles this complexity.
32///
33SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
34                                                    unsigned ByteNo) const {
35  assert(!SL->isWide() && "This doesn't work for wide strings yet");
36
37  // Loop over all of the tokens in this string until we find the one that
38  // contains the byte we're looking for.
39  unsigned TokNo = 0;
40  while (1) {
41    assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
42    SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
43
44    // Get the spelling of the string so that we can get the data that makes up
45    // the string literal, not the identifier for the macro it is potentially
46    // expanded through.
47    SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
48
49    // Re-lex the token to get its length and original spelling.
50    std::pair<FileID, unsigned> LocInfo =
51      SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
52    std::pair<const char *,const char *> Buffer =
53      SourceMgr.getBufferData(LocInfo.first);
54    const char *StrData = Buffer.first+LocInfo.second;
55
56    // Create a langops struct and enable trigraphs.  This is sufficient for
57    // relexing tokens.
58    LangOptions LangOpts;
59    LangOpts.Trigraphs = true;
60
61    // Create a lexer starting at the beginning of this token.
62    Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
63                   Buffer.second);
64    Token TheTok;
65    TheLexer.LexFromRawLexer(TheTok);
66
67    // Use the StringLiteralParser to compute the length of the string in bytes.
68    StringLiteralParser SLP(&TheTok, 1, PP);
69    unsigned TokNumBytes = SLP.GetStringLength();
70
71    // If the byte is in this token, return the location of the byte.
72    if (ByteNo < TokNumBytes ||
73        (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
74      unsigned Offset =
75        StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
76
77      // Now that we know the offset of the token in the spelling, use the
78      // preprocessor to get the offset in the original source.
79      return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
80    }
81
82    // Move to the next string token.
83    ++TokNo;
84    ByteNo -= TokNumBytes;
85  }
86}
87
88/// CheckablePrintfAttr - does a function call have a "printf" attribute
89/// and arguments that merit checking?
90bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
91  if (Format->getType() == "printf") return true;
92  if (Format->getType() == "printf0") {
93    // printf0 allows null "format" string; if so don't check format/args
94    unsigned format_idx = Format->getFormatIdx() - 1;
95    // Does the index refer to the implicit object argument?
96    if (isa<CXXMemberCallExpr>(TheCall)) {
97      if (format_idx == 0)
98        return false;
99      --format_idx;
100    }
101    if (format_idx < TheCall->getNumArgs()) {
102      Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
103      if (!Format->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
104        return true;
105    }
106  }
107  return false;
108}
109
110Action::OwningExprResult
111Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
112  OwningExprResult TheCallResult(Owned(TheCall));
113
114  switch (BuiltinID) {
115  case Builtin::BI__builtin___CFStringMakeConstantString:
116    assert(TheCall->getNumArgs() == 1 &&
117           "Wrong # arguments to builtin CFStringMakeConstantString");
118    if (CheckObjCString(TheCall->getArg(0)))
119      return ExprError();
120    break;
121  case Builtin::BI__builtin_stdarg_start:
122  case Builtin::BI__builtin_va_start:
123    if (SemaBuiltinVAStart(TheCall))
124      return ExprError();
125    break;
126  case Builtin::BI__builtin_isgreater:
127  case Builtin::BI__builtin_isgreaterequal:
128  case Builtin::BI__builtin_isless:
129  case Builtin::BI__builtin_islessequal:
130  case Builtin::BI__builtin_islessgreater:
131  case Builtin::BI__builtin_isunordered:
132    if (SemaBuiltinUnorderedCompare(TheCall))
133      return ExprError();
134    break;
135  case Builtin::BI__builtin_isfinite:
136  case Builtin::BI__builtin_isinf:
137  case Builtin::BI__builtin_isinf_sign:
138  case Builtin::BI__builtin_isnan:
139  case Builtin::BI__builtin_isnormal:
140    if (SemaBuiltinUnaryFP(TheCall))
141      return ExprError();
142    break;
143  case Builtin::BI__builtin_return_address:
144  case Builtin::BI__builtin_frame_address:
145    if (SemaBuiltinStackAddress(TheCall))
146      return ExprError();
147    break;
148  case Builtin::BI__builtin_eh_return_data_regno:
149    if (SemaBuiltinEHReturnDataRegNo(TheCall))
150      return ExprError();
151    break;
152  case Builtin::BI__builtin_shufflevector:
153    return SemaBuiltinShuffleVector(TheCall);
154    // TheCall will be freed by the smart pointer here, but that's fine, since
155    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
156  case Builtin::BI__builtin_prefetch:
157    if (SemaBuiltinPrefetch(TheCall))
158      return ExprError();
159    break;
160  case Builtin::BI__builtin_object_size:
161    if (SemaBuiltinObjectSize(TheCall))
162      return ExprError();
163    break;
164  case Builtin::BI__builtin_longjmp:
165    if (SemaBuiltinLongjmp(TheCall))
166      return ExprError();
167    break;
168  case Builtin::BI__sync_fetch_and_add:
169  case Builtin::BI__sync_fetch_and_sub:
170  case Builtin::BI__sync_fetch_and_or:
171  case Builtin::BI__sync_fetch_and_and:
172  case Builtin::BI__sync_fetch_and_xor:
173  case Builtin::BI__sync_fetch_and_nand:
174  case Builtin::BI__sync_add_and_fetch:
175  case Builtin::BI__sync_sub_and_fetch:
176  case Builtin::BI__sync_and_and_fetch:
177  case Builtin::BI__sync_or_and_fetch:
178  case Builtin::BI__sync_xor_and_fetch:
179  case Builtin::BI__sync_nand_and_fetch:
180  case Builtin::BI__sync_val_compare_and_swap:
181  case Builtin::BI__sync_bool_compare_and_swap:
182  case Builtin::BI__sync_lock_test_and_set:
183  case Builtin::BI__sync_lock_release:
184    if (SemaBuiltinAtomicOverloaded(TheCall))
185      return ExprError();
186    break;
187  }
188
189  return move(TheCallResult);
190}
191
192/// CheckFunctionCall - Check a direct function call for various correctness
193/// and safety properties not strictly enforced by the C type system.
194bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
195  // Get the IdentifierInfo* for the called function.
196  IdentifierInfo *FnInfo = FDecl->getIdentifier();
197
198  // None of the checks below are needed for functions that don't have
199  // simple names (e.g., C++ conversion functions).
200  if (!FnInfo)
201    return false;
202
203  // FIXME: This mechanism should be abstracted to be less fragile and
204  // more efficient. For example, just map function ids to custom
205  // handlers.
206
207  // Printf checking.
208  if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
209    if (CheckablePrintfAttr(Format, TheCall)) {
210      bool HasVAListArg = Format->getFirstArg() == 0;
211      if (!HasVAListArg) {
212        if (const FunctionProtoType *Proto
213            = FDecl->getType()->getAs<FunctionProtoType>())
214          HasVAListArg = !Proto->isVariadic();
215      }
216      CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
217                           HasVAListArg ? 0 : Format->getFirstArg() - 1);
218    }
219  }
220
221  for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
222       NonNull = NonNull->getNext<NonNullAttr>())
223    CheckNonNullArguments(NonNull, TheCall);
224
225  return false;
226}
227
228bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
229  // Printf checking.
230  const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
231  if (!Format)
232    return false;
233
234  const VarDecl *V = dyn_cast<VarDecl>(NDecl);
235  if (!V)
236    return false;
237
238  QualType Ty = V->getType();
239  if (!Ty->isBlockPointerType())
240    return false;
241
242  if (!CheckablePrintfAttr(Format, TheCall))
243    return false;
244
245  bool HasVAListArg = Format->getFirstArg() == 0;
246  if (!HasVAListArg) {
247    const FunctionType *FT =
248      Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
249    if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
250      HasVAListArg = !Proto->isVariadic();
251  }
252  CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
253                       HasVAListArg ? 0 : Format->getFirstArg() - 1);
254
255  return false;
256}
257
258/// SemaBuiltinAtomicOverloaded - We have a call to a function like
259/// __sync_fetch_and_add, which is an overloaded function based on the pointer
260/// type of its first argument.  The main ActOnCallExpr routines have already
261/// promoted the types of arguments because all of these calls are prototyped as
262/// void(...).
263///
264/// This function goes through and does final semantic checking for these
265/// builtins,
266bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
267  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
268  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
269
270  // Ensure that we have at least one argument to do type inference from.
271  if (TheCall->getNumArgs() < 1)
272    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
273              << 0 << TheCall->getCallee()->getSourceRange();
274
275  // Inspect the first argument of the atomic builtin.  This should always be
276  // a pointer type, whose element is an integral scalar or pointer type.
277  // Because it is a pointer type, we don't have to worry about any implicit
278  // casts here.
279  Expr *FirstArg = TheCall->getArg(0);
280  if (!FirstArg->getType()->isPointerType())
281    return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
282             << FirstArg->getType() << FirstArg->getSourceRange();
283
284  QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
285  if (!ValType->isIntegerType() && !ValType->isPointerType() &&
286      !ValType->isBlockPointerType())
287    return Diag(DRE->getLocStart(),
288                diag::err_atomic_builtin_must_be_pointer_intptr)
289             << FirstArg->getType() << FirstArg->getSourceRange();
290
291  // We need to figure out which concrete builtin this maps onto.  For example,
292  // __sync_fetch_and_add with a 2 byte object turns into
293  // __sync_fetch_and_add_2.
294#define BUILTIN_ROW(x) \
295  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
296    Builtin::BI##x##_8, Builtin::BI##x##_16 }
297
298  static const unsigned BuiltinIndices[][5] = {
299    BUILTIN_ROW(__sync_fetch_and_add),
300    BUILTIN_ROW(__sync_fetch_and_sub),
301    BUILTIN_ROW(__sync_fetch_and_or),
302    BUILTIN_ROW(__sync_fetch_and_and),
303    BUILTIN_ROW(__sync_fetch_and_xor),
304    BUILTIN_ROW(__sync_fetch_and_nand),
305
306    BUILTIN_ROW(__sync_add_and_fetch),
307    BUILTIN_ROW(__sync_sub_and_fetch),
308    BUILTIN_ROW(__sync_and_and_fetch),
309    BUILTIN_ROW(__sync_or_and_fetch),
310    BUILTIN_ROW(__sync_xor_and_fetch),
311    BUILTIN_ROW(__sync_nand_and_fetch),
312
313    BUILTIN_ROW(__sync_val_compare_and_swap),
314    BUILTIN_ROW(__sync_bool_compare_and_swap),
315    BUILTIN_ROW(__sync_lock_test_and_set),
316    BUILTIN_ROW(__sync_lock_release)
317  };
318#undef BUILTIN_ROW
319
320  // Determine the index of the size.
321  unsigned SizeIndex;
322  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
323  case 1: SizeIndex = 0; break;
324  case 2: SizeIndex = 1; break;
325  case 4: SizeIndex = 2; break;
326  case 8: SizeIndex = 3; break;
327  case 16: SizeIndex = 4; break;
328  default:
329    return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
330             << FirstArg->getType() << FirstArg->getSourceRange();
331  }
332
333  // Each of these builtins has one pointer argument, followed by some number of
334  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
335  // that we ignore.  Find out which row of BuiltinIndices to read from as well
336  // as the number of fixed args.
337  unsigned BuiltinID = FDecl->getBuiltinID();
338  unsigned BuiltinIndex, NumFixed = 1;
339  switch (BuiltinID) {
340  default: assert(0 && "Unknown overloaded atomic builtin!");
341  case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
342  case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
343  case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
344  case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
345  case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
346  case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
347
348  case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
349  case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
350  case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
351  case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 9; break;
352  case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
353  case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
354
355  case Builtin::BI__sync_val_compare_and_swap:
356    BuiltinIndex = 12;
357    NumFixed = 2;
358    break;
359  case Builtin::BI__sync_bool_compare_and_swap:
360    BuiltinIndex = 13;
361    NumFixed = 2;
362    break;
363  case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
364  case Builtin::BI__sync_lock_release:
365    BuiltinIndex = 15;
366    NumFixed = 0;
367    break;
368  }
369
370  // Now that we know how many fixed arguments we expect, first check that we
371  // have at least that many.
372  if (TheCall->getNumArgs() < 1+NumFixed)
373    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
374            << 0 << TheCall->getCallee()->getSourceRange();
375
376
377  // Get the decl for the concrete builtin from this, we can tell what the
378  // concrete integer type we should convert to is.
379  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
380  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
381  IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
382  FunctionDecl *NewBuiltinDecl =
383    cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
384                                           TUScope, false, DRE->getLocStart()));
385  const FunctionProtoType *BuiltinFT =
386    NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
387  ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
388
389  // If the first type needs to be converted (e.g. void** -> int*), do it now.
390  if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
391    ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
392    TheCall->setArg(0, FirstArg);
393  }
394
395  // Next, walk the valid ones promoting to the right type.
396  for (unsigned i = 0; i != NumFixed; ++i) {
397    Expr *Arg = TheCall->getArg(i+1);
398
399    // If the argument is an implicit cast, then there was a promotion due to
400    // "...", just remove it now.
401    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
402      Arg = ICE->getSubExpr();
403      ICE->setSubExpr(0);
404      ICE->Destroy(Context);
405      TheCall->setArg(i+1, Arg);
406    }
407
408    // GCC does an implicit conversion to the pointer or integer ValType.  This
409    // can fail in some cases (1i -> int**), check for this error case now.
410    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
411    CXXMethodDecl *ConversionDecl = 0;
412    if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
413                       ConversionDecl))
414      return true;
415
416    // Okay, we have something that *can* be converted to the right type.  Check
417    // to see if there is a potentially weird extension going on here.  This can
418    // happen when you do an atomic operation on something like an char* and
419    // pass in 42.  The 42 gets converted to char.  This is even more strange
420    // for things like 45.123 -> char, etc.
421    // FIXME: Do this check.
422    ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
423    TheCall->setArg(i+1, Arg);
424  }
425
426  // Switch the DeclRefExpr to refer to the new decl.
427  DRE->setDecl(NewBuiltinDecl);
428  DRE->setType(NewBuiltinDecl->getType());
429
430  // Set the callee in the CallExpr.
431  // FIXME: This leaks the original parens and implicit casts.
432  Expr *PromotedCall = DRE;
433  UsualUnaryConversions(PromotedCall);
434  TheCall->setCallee(PromotedCall);
435
436
437  // Change the result type of the call to match the result type of the decl.
438  TheCall->setType(NewBuiltinDecl->getResultType());
439  return false;
440}
441
442
443/// CheckObjCString - Checks that the argument to the builtin
444/// CFString constructor is correct
445/// FIXME: GCC currently emits the following warning:
446/// "warning: input conversion stopped due to an input byte that does not
447///           belong to the input codeset UTF-8"
448/// Note: It might also make sense to do the UTF-16 conversion here (would
449/// simplify the backend).
450bool Sema::CheckObjCString(Expr *Arg) {
451  Arg = Arg->IgnoreParenCasts();
452  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
453
454  if (!Literal || Literal->isWide()) {
455    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
456      << Arg->getSourceRange();
457    return true;
458  }
459
460  const char *Data = Literal->getStrData();
461  unsigned Length = Literal->getByteLength();
462
463  for (unsigned i = 0; i < Length; ++i) {
464    if (!Data[i]) {
465      Diag(getLocationOfStringLiteralByte(Literal, i),
466           diag::warn_cfstring_literal_contains_nul_character)
467        << Arg->getSourceRange();
468      break;
469    }
470  }
471
472  return false;
473}
474
475/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
476/// Emit an error and return true on failure, return false on success.
477bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
478  Expr *Fn = TheCall->getCallee();
479  if (TheCall->getNumArgs() > 2) {
480    Diag(TheCall->getArg(2)->getLocStart(),
481         diag::err_typecheck_call_too_many_args)
482      << 0 /*function call*/ << Fn->getSourceRange()
483      << SourceRange(TheCall->getArg(2)->getLocStart(),
484                     (*(TheCall->arg_end()-1))->getLocEnd());
485    return true;
486  }
487
488  if (TheCall->getNumArgs() < 2) {
489    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
490      << 0 /*function call*/;
491  }
492
493  // Determine whether the current function is variadic or not.
494  bool isVariadic;
495  if (CurBlock)
496    isVariadic = CurBlock->isVariadic;
497  else if (getCurFunctionDecl()) {
498    if (FunctionProtoType* FTP =
499            dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
500      isVariadic = FTP->isVariadic();
501    else
502      isVariadic = false;
503  } else {
504    isVariadic = getCurMethodDecl()->isVariadic();
505  }
506
507  if (!isVariadic) {
508    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
509    return true;
510  }
511
512  // Verify that the second argument to the builtin is the last argument of the
513  // current function or method.
514  bool SecondArgIsLastNamedArgument = false;
515  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
516
517  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
518    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
519      // FIXME: This isn't correct for methods (results in bogus warning).
520      // Get the last formal in the current function.
521      const ParmVarDecl *LastArg;
522      if (CurBlock)
523        LastArg = *(CurBlock->TheDecl->param_end()-1);
524      else if (FunctionDecl *FD = getCurFunctionDecl())
525        LastArg = *(FD->param_end()-1);
526      else
527        LastArg = *(getCurMethodDecl()->param_end()-1);
528      SecondArgIsLastNamedArgument = PV == LastArg;
529    }
530  }
531
532  if (!SecondArgIsLastNamedArgument)
533    Diag(TheCall->getArg(1)->getLocStart(),
534         diag::warn_second_parameter_of_va_start_not_last_named_argument);
535  return false;
536}
537
538/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
539/// friends.  This is declared to take (...), so we have to check everything.
540bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
541  if (TheCall->getNumArgs() < 2)
542    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
543      << 0 /*function call*/;
544  if (TheCall->getNumArgs() > 2)
545    return Diag(TheCall->getArg(2)->getLocStart(),
546                diag::err_typecheck_call_too_many_args)
547      << 0 /*function call*/
548      << SourceRange(TheCall->getArg(2)->getLocStart(),
549                     (*(TheCall->arg_end()-1))->getLocEnd());
550
551  Expr *OrigArg0 = TheCall->getArg(0);
552  Expr *OrigArg1 = TheCall->getArg(1);
553
554  // Do standard promotions between the two arguments, returning their common
555  // type.
556  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
557
558  // Make sure any conversions are pushed back into the call; this is
559  // type safe since unordered compare builtins are declared as "_Bool
560  // foo(...)".
561  TheCall->setArg(0, OrigArg0);
562  TheCall->setArg(1, OrigArg1);
563
564  if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
565    return false;
566
567  // If the common type isn't a real floating type, then the arguments were
568  // invalid for this operation.
569  if (!Res->isRealFloatingType())
570    return Diag(OrigArg0->getLocStart(),
571                diag::err_typecheck_call_invalid_ordered_compare)
572      << OrigArg0->getType() << OrigArg1->getType()
573      << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
574
575  return false;
576}
577
578/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isnan and
579/// friends.  This is declared to take (...), so we have to check everything.
580bool Sema::SemaBuiltinUnaryFP(CallExpr *TheCall) {
581  if (TheCall->getNumArgs() < 1)
582    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
583      << 0 /*function call*/;
584  if (TheCall->getNumArgs() > 1)
585    return Diag(TheCall->getArg(1)->getLocStart(),
586                diag::err_typecheck_call_too_many_args)
587      << 0 /*function call*/
588      << SourceRange(TheCall->getArg(1)->getLocStart(),
589                     (*(TheCall->arg_end()-1))->getLocEnd());
590
591  Expr *OrigArg = TheCall->getArg(0);
592
593  if (OrigArg->isTypeDependent())
594    return false;
595
596  // This operation requires a floating-point number
597  if (!OrigArg->getType()->isRealFloatingType())
598    return Diag(OrigArg->getLocStart(),
599                diag::err_typecheck_call_invalid_unary_fp)
600      << OrigArg->getType() << OrigArg->getSourceRange();
601
602  return false;
603}
604
605bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
606  // The signature for these builtins is exact; the only thing we need
607  // to check is that the argument is a constant.
608  SourceLocation Loc;
609  if (!TheCall->getArg(0)->isTypeDependent() &&
610      !TheCall->getArg(0)->isValueDependent() &&
611      !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
612    return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
613
614  return false;
615}
616
617/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
618// This is declared to take (...), so we have to check everything.
619Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
620  if (TheCall->getNumArgs() < 3)
621    return ExprError(Diag(TheCall->getLocEnd(),
622                          diag::err_typecheck_call_too_few_args)
623      << 0 /*function call*/ << TheCall->getSourceRange());
624
625  unsigned numElements = std::numeric_limits<unsigned>::max();
626  if (!TheCall->getArg(0)->isTypeDependent() &&
627      !TheCall->getArg(1)->isTypeDependent()) {
628    QualType FAType = TheCall->getArg(0)->getType();
629    QualType SAType = TheCall->getArg(1)->getType();
630
631    if (!FAType->isVectorType() || !SAType->isVectorType()) {
632      Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
633        << SourceRange(TheCall->getArg(0)->getLocStart(),
634                       TheCall->getArg(1)->getLocEnd());
635      return ExprError();
636    }
637
638    if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
639      Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
640        << SourceRange(TheCall->getArg(0)->getLocStart(),
641                       TheCall->getArg(1)->getLocEnd());
642      return ExprError();
643    }
644
645    numElements = FAType->getAs<VectorType>()->getNumElements();
646    if (TheCall->getNumArgs() != numElements+2) {
647      if (TheCall->getNumArgs() < numElements+2)
648        return ExprError(Diag(TheCall->getLocEnd(),
649                              diag::err_typecheck_call_too_few_args)
650                 << 0 /*function call*/ << TheCall->getSourceRange());
651      return ExprError(Diag(TheCall->getLocEnd(),
652                            diag::err_typecheck_call_too_many_args)
653                 << 0 /*function call*/ << TheCall->getSourceRange());
654    }
655  }
656
657  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
658    if (TheCall->getArg(i)->isTypeDependent() ||
659        TheCall->getArg(i)->isValueDependent())
660      continue;
661
662    llvm::APSInt Result(32);
663    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
664      return ExprError(Diag(TheCall->getLocStart(),
665                  diag::err_shufflevector_nonconstant_argument)
666                << TheCall->getArg(i)->getSourceRange());
667
668    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
669      return ExprError(Diag(TheCall->getLocStart(),
670                  diag::err_shufflevector_argument_too_large)
671               << TheCall->getArg(i)->getSourceRange());
672  }
673
674  llvm::SmallVector<Expr*, 32> exprs;
675
676  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
677    exprs.push_back(TheCall->getArg(i));
678    TheCall->setArg(i, 0);
679  }
680
681  return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
682                                            exprs.size(), exprs[0]->getType(),
683                                            TheCall->getCallee()->getLocStart(),
684                                            TheCall->getRParenLoc()));
685}
686
687/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
688// This is declared to take (const void*, ...) and can take two
689// optional constant int args.
690bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
691  unsigned NumArgs = TheCall->getNumArgs();
692
693  if (NumArgs > 3)
694    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
695             << 0 /*function call*/ << TheCall->getSourceRange();
696
697  // Argument 0 is checked for us and the remaining arguments must be
698  // constant integers.
699  for (unsigned i = 1; i != NumArgs; ++i) {
700    Expr *Arg = TheCall->getArg(i);
701    if (Arg->isTypeDependent())
702      continue;
703
704    if (!Arg->getType()->isIntegralType())
705      return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type)
706              << Arg->getSourceRange();
707
708    ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast);
709    TheCall->setArg(i, Arg);
710
711    if (Arg->isValueDependent())
712      continue;
713
714    llvm::APSInt Result;
715    if (!Arg->isIntegerConstantExpr(Result, Context))
716      return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice)
717        << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
718
719    // FIXME: gcc issues a warning and rewrites these to 0. These
720    // seems especially odd for the third argument since the default
721    // is 3.
722    if (i == 1) {
723      if (Result.getLimitedValue() > 1)
724        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
725             << "0" << "1" << Arg->getSourceRange();
726    } else {
727      if (Result.getLimitedValue() > 3)
728        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
729            << "0" << "3" << Arg->getSourceRange();
730    }
731  }
732
733  return false;
734}
735
736/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
737/// operand must be an integer constant.
738bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
739  llvm::APSInt Result;
740  if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
741    return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
742      << TheCall->getArg(0)->getSourceRange();
743
744  return false;
745}
746
747
748/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
749/// int type). This simply type checks that type is one of the defined
750/// constants (0-3).
751// For compatability check 0-3, llvm only handles 0 and 2.
752bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
753  Expr *Arg = TheCall->getArg(1);
754  if (Arg->isTypeDependent())
755    return false;
756
757  QualType ArgType = Arg->getType();
758  const BuiltinType *BT = ArgType->getAs<BuiltinType>();
759  llvm::APSInt Result(32);
760  if (!BT || BT->getKind() != BuiltinType::Int)
761    return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
762             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
763
764  if (Arg->isValueDependent())
765    return false;
766
767  if (!Arg->isIntegerConstantExpr(Result, Context)) {
768    return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
769             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
770  }
771
772  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
773    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
774             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
775  }
776
777  return false;
778}
779
780/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
781/// This checks that val is a constant 1.
782bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
783  Expr *Arg = TheCall->getArg(1);
784  if (Arg->isTypeDependent() || Arg->isValueDependent())
785    return false;
786
787  llvm::APSInt Result(32);
788  if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
789    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
790             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
791
792  return false;
793}
794
795// Handle i > 1 ? "x" : "y", recursivelly
796bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
797                                  bool HasVAListArg,
798                                  unsigned format_idx, unsigned firstDataArg) {
799  if (E->isTypeDependent() || E->isValueDependent())
800    return false;
801
802  switch (E->getStmtClass()) {
803  case Stmt::ConditionalOperatorClass: {
804    const ConditionalOperator *C = cast<ConditionalOperator>(E);
805    return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
806                                  HasVAListArg, format_idx, firstDataArg)
807        && SemaCheckStringLiteral(C->getRHS(), TheCall,
808                                  HasVAListArg, format_idx, firstDataArg);
809  }
810
811  case Stmt::ImplicitCastExprClass: {
812    const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
813    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
814                                  format_idx, firstDataArg);
815  }
816
817  case Stmt::ParenExprClass: {
818    const ParenExpr *Expr = cast<ParenExpr>(E);
819    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
820                                  format_idx, firstDataArg);
821  }
822
823  case Stmt::DeclRefExprClass: {
824    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
825
826    // As an exception, do not flag errors for variables binding to
827    // const string literals.
828    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
829      bool isConstant = false;
830      QualType T = DR->getType();
831
832      if (const ArrayType *AT = Context.getAsArrayType(T)) {
833        isConstant = AT->getElementType().isConstant(Context);
834      } else if (const PointerType *PT = T->getAs<PointerType>()) {
835        isConstant = T.isConstant(Context) &&
836                     PT->getPointeeType().isConstant(Context);
837      }
838
839      if (isConstant) {
840        const VarDecl *Def = 0;
841        if (const Expr *Init = VD->getDefinition(Def))
842          return SemaCheckStringLiteral(Init, TheCall,
843                                        HasVAListArg, format_idx, firstDataArg);
844      }
845
846      // For vprintf* functions (i.e., HasVAListArg==true), we add a
847      // special check to see if the format string is a function parameter
848      // of the function calling the printf function.  If the function
849      // has an attribute indicating it is a printf-like function, then we
850      // should suppress warnings concerning non-literals being used in a call
851      // to a vprintf function.  For example:
852      //
853      // void
854      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
855      //      va_list ap;
856      //      va_start(ap, fmt);
857      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
858      //      ...
859      //
860      //
861      //  FIXME: We don't have full attribute support yet, so just check to see
862      //    if the argument is a DeclRefExpr that references a parameter.  We'll
863      //    add proper support for checking the attribute later.
864      if (HasVAListArg)
865        if (isa<ParmVarDecl>(VD))
866          return true;
867    }
868
869    return false;
870  }
871
872  case Stmt::CallExprClass: {
873    const CallExpr *CE = cast<CallExpr>(E);
874    if (const ImplicitCastExpr *ICE
875          = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
876      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
877        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
878          if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
879            unsigned ArgIndex = FA->getFormatIdx();
880            const Expr *Arg = CE->getArg(ArgIndex - 1);
881
882            return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
883                                          format_idx, firstDataArg);
884          }
885        }
886      }
887    }
888
889    return false;
890  }
891  case Stmt::ObjCStringLiteralClass:
892  case Stmt::StringLiteralClass: {
893    const StringLiteral *StrE = NULL;
894
895    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
896      StrE = ObjCFExpr->getString();
897    else
898      StrE = cast<StringLiteral>(E);
899
900    if (StrE) {
901      CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
902                        firstDataArg);
903      return true;
904    }
905
906    return false;
907  }
908
909  default:
910    return false;
911  }
912}
913
914void
915Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
916                            const CallExpr *TheCall) {
917  for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
918       i != e; ++i) {
919    const Expr *ArgExpr = TheCall->getArg(*i);
920    if (ArgExpr->isNullPointerConstant(Context,
921                                       Expr::NPC_ValueDependentIsNotNull))
922      Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
923        << ArgExpr->getSourceRange();
924  }
925}
926
927/// CheckPrintfArguments - Check calls to printf (and similar functions) for
928/// correct use of format strings.
929///
930///  HasVAListArg - A predicate indicating whether the printf-like
931///    function is passed an explicit va_arg argument (e.g., vprintf)
932///
933///  format_idx - The index into Args for the format string.
934///
935/// Improper format strings to functions in the printf family can be
936/// the source of bizarre bugs and very serious security holes.  A
937/// good source of information is available in the following paper
938/// (which includes additional references):
939///
940///  FormatGuard: Automatic Protection From printf Format String
941///  Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
942///
943/// Functionality implemented:
944///
945///  We can statically check the following properties for string
946///  literal format strings for non v.*printf functions (where the
947///  arguments are passed directly):
948//
949///  (1) Are the number of format conversions equal to the number of
950///      data arguments?
951///
952///  (2) Does each format conversion correctly match the type of the
953///      corresponding data argument?  (TODO)
954///
955/// Moreover, for all printf functions we can:
956///
957///  (3) Check for a missing format string (when not caught by type checking).
958///
959///  (4) Check for no-operation flags; e.g. using "#" with format
960///      conversion 'c'  (TODO)
961///
962///  (5) Check the use of '%n', a major source of security holes.
963///
964///  (6) Check for malformed format conversions that don't specify anything.
965///
966///  (7) Check for empty format strings.  e.g: printf("");
967///
968///  (8) Check that the format string is a wide literal.
969///
970/// All of these checks can be done by parsing the format string.
971///
972/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
973void
974Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
975                           unsigned format_idx, unsigned firstDataArg) {
976  const Expr *Fn = TheCall->getCallee();
977
978  // The way the format attribute works in GCC, the implicit this argument
979  // of member functions is counted. However, it doesn't appear in our own
980  // lists, so decrement format_idx in that case.
981  if (isa<CXXMemberCallExpr>(TheCall)) {
982    // Catch a format attribute mistakenly referring to the object argument.
983    if (format_idx == 0)
984      return;
985    --format_idx;
986    if(firstDataArg != 0)
987      --firstDataArg;
988  }
989
990  // CHECK: printf-like function is called with no format string.
991  if (format_idx >= TheCall->getNumArgs()) {
992    Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
993      << Fn->getSourceRange();
994    return;
995  }
996
997  const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
998
999  // CHECK: format string is not a string literal.
1000  //
1001  // Dynamically generated format strings are difficult to
1002  // automatically vet at compile time.  Requiring that format strings
1003  // are string literals: (1) permits the checking of format strings by
1004  // the compiler and thereby (2) can practically remove the source of
1005  // many format string exploits.
1006
1007  // Format string can be either ObjC string (e.g. @"%d") or
1008  // C string (e.g. "%d")
1009  // ObjC string uses the same format specifiers as C string, so we can use
1010  // the same format string checking logic for both ObjC and C strings.
1011  if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1012                             firstDataArg))
1013    return;  // Literal format string found, check done!
1014
1015  // If there are no arguments specified, warn with -Wformat-security, otherwise
1016  // warn only with -Wformat-nonliteral.
1017  if (TheCall->getNumArgs() == format_idx+1)
1018    Diag(TheCall->getArg(format_idx)->getLocStart(),
1019         diag::warn_printf_nonliteral_noargs)
1020      << OrigFormatExpr->getSourceRange();
1021  else
1022    Diag(TheCall->getArg(format_idx)->getLocStart(),
1023         diag::warn_printf_nonliteral)
1024           << OrigFormatExpr->getSourceRange();
1025}
1026
1027void Sema::CheckPrintfString(const StringLiteral *FExpr,
1028                             const Expr *OrigFormatExpr,
1029                             const CallExpr *TheCall, bool HasVAListArg,
1030                             unsigned format_idx, unsigned firstDataArg) {
1031
1032  const ObjCStringLiteral *ObjCFExpr =
1033    dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
1034
1035  // CHECK: is the format string a wide literal?
1036  if (FExpr->isWide()) {
1037    Diag(FExpr->getLocStart(),
1038         diag::warn_printf_format_string_is_wide_literal)
1039      << OrigFormatExpr->getSourceRange();
1040    return;
1041  }
1042
1043  // Str - The format string.  NOTE: this is NOT null-terminated!
1044  const char *Str = FExpr->getStrData();
1045
1046  // CHECK: empty format string?
1047  unsigned StrLen = FExpr->getByteLength();
1048
1049  if (StrLen == 0) {
1050    Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1051      << OrigFormatExpr->getSourceRange();
1052    return;
1053  }
1054
1055  // We process the format string using a binary state machine.  The
1056  // current state is stored in CurrentState.
1057  enum {
1058    state_OrdChr,
1059    state_Conversion
1060  } CurrentState = state_OrdChr;
1061
1062  // numConversions - The number of conversions seen so far.  This is
1063  //  incremented as we traverse the format string.
1064  unsigned numConversions = 0;
1065
1066  // numDataArgs - The number of data arguments after the format
1067  //  string.  This can only be determined for non vprintf-like
1068  //  functions.  For those functions, this value is 1 (the sole
1069  //  va_arg argument).
1070  unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
1071
1072  // Inspect the format string.
1073  unsigned StrIdx = 0;
1074
1075  // LastConversionIdx - Index within the format string where we last saw
1076  //  a '%' character that starts a new format conversion.
1077  unsigned LastConversionIdx = 0;
1078
1079  for (; StrIdx < StrLen; ++StrIdx) {
1080
1081    // Is the number of detected conversion conversions greater than
1082    // the number of matching data arguments?  If so, stop.
1083    if (!HasVAListArg && numConversions > numDataArgs) break;
1084
1085    // Handle "\0"
1086    if (Str[StrIdx] == '\0') {
1087      // The string returned by getStrData() is not null-terminated,
1088      // so the presence of a null character is likely an error.
1089      Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
1090           diag::warn_printf_format_string_contains_null_char)
1091        <<  OrigFormatExpr->getSourceRange();
1092      return;
1093    }
1094
1095    // Ordinary characters (not processing a format conversion).
1096    if (CurrentState == state_OrdChr) {
1097      if (Str[StrIdx] == '%') {
1098        CurrentState = state_Conversion;
1099        LastConversionIdx = StrIdx;
1100      }
1101      continue;
1102    }
1103
1104    // Seen '%'.  Now processing a format conversion.
1105    switch (Str[StrIdx]) {
1106    // Handle dynamic precision or width specifier.
1107    case '*': {
1108      ++numConversions;
1109
1110      if (!HasVAListArg) {
1111        if (numConversions > numDataArgs) {
1112          SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
1113
1114          if (Str[StrIdx-1] == '.')
1115            Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
1116              << OrigFormatExpr->getSourceRange();
1117          else
1118            Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
1119              << OrigFormatExpr->getSourceRange();
1120
1121          // Don't do any more checking.  We'll just emit spurious errors.
1122          return;
1123        }
1124
1125        // Perform type checking on width/precision specifier.
1126        const Expr *E = TheCall->getArg(format_idx+numConversions);
1127        if (const BuiltinType *BT = E->getType()->getAs<BuiltinType>())
1128          if (BT->getKind() == BuiltinType::Int)
1129            break;
1130
1131        SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
1132
1133        if (Str[StrIdx-1] == '.')
1134          Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1135          << E->getType() << E->getSourceRange();
1136        else
1137          Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1138          << E->getType() << E->getSourceRange();
1139
1140        break;
1141      }
1142    }
1143
1144    // Characters which can terminate a format conversion
1145    // (e.g. "%d").  Characters that specify length modifiers or
1146    // other flags are handled by the default case below.
1147    //
1148    // FIXME: additional checks will go into the following cases.
1149    case 'i':
1150    case 'd':
1151    case 'o':
1152    case 'u':
1153    case 'x':
1154    case 'X':
1155    case 'D':
1156    case 'O':
1157    case 'U':
1158    case 'e':
1159    case 'E':
1160    case 'f':
1161    case 'F':
1162    case 'g':
1163    case 'G':
1164    case 'a':
1165    case 'A':
1166    case 'c':
1167    case 'C':
1168    case 'S':
1169    case 's':
1170    case 'p':
1171      ++numConversions;
1172      CurrentState = state_OrdChr;
1173      break;
1174
1175    case 'm':
1176      // FIXME: Warn in situations where this isn't supported!
1177      CurrentState = state_OrdChr;
1178      break;
1179
1180    // CHECK: Are we using "%n"?  Issue a warning.
1181    case 'n': {
1182      ++numConversions;
1183      CurrentState = state_OrdChr;
1184      SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1185                                                          LastConversionIdx);
1186
1187      Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
1188      break;
1189    }
1190
1191    // Handle "%@"
1192    case '@':
1193      // %@ is allowed in ObjC format strings only.
1194      if (ObjCFExpr != NULL)
1195        CurrentState = state_OrdChr;
1196      else {
1197        // Issue a warning: invalid format conversion.
1198        SourceLocation Loc =
1199          getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1200
1201        Diag(Loc, diag::warn_printf_invalid_conversion)
1202          <<  std::string(Str+LastConversionIdx,
1203                          Str+std::min(LastConversionIdx+2, StrLen))
1204          << OrigFormatExpr->getSourceRange();
1205      }
1206      ++numConversions;
1207      break;
1208
1209    // Handle "%%"
1210    case '%':
1211      // Sanity check: Was the first "%" character the previous one?
1212      // If not, we will assume that we have a malformed format
1213      // conversion, and that the current "%" character is the start
1214      // of a new conversion.
1215      if (StrIdx - LastConversionIdx == 1)
1216        CurrentState = state_OrdChr;
1217      else {
1218        // Issue a warning: invalid format conversion.
1219        SourceLocation Loc =
1220          getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1221
1222        Diag(Loc, diag::warn_printf_invalid_conversion)
1223          << std::string(Str+LastConversionIdx, Str+StrIdx)
1224          << OrigFormatExpr->getSourceRange();
1225
1226        // This conversion is broken.  Advance to the next format
1227        // conversion.
1228        LastConversionIdx = StrIdx;
1229        ++numConversions;
1230      }
1231      break;
1232
1233    default:
1234      // This case catches all other characters: flags, widths, etc.
1235      // We should eventually process those as well.
1236      break;
1237    }
1238  }
1239
1240  if (CurrentState == state_Conversion) {
1241    // Issue a warning: invalid format conversion.
1242    SourceLocation Loc =
1243      getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1244
1245    Diag(Loc, diag::warn_printf_invalid_conversion)
1246      << std::string(Str+LastConversionIdx,
1247                     Str+std::min(LastConversionIdx+2, StrLen))
1248      << OrigFormatExpr->getSourceRange();
1249    return;
1250  }
1251
1252  if (!HasVAListArg) {
1253    // CHECK: Does the number of format conversions exceed the number
1254    //        of data arguments?
1255    if (numConversions > numDataArgs) {
1256      SourceLocation Loc =
1257        getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1258
1259      Diag(Loc, diag::warn_printf_insufficient_data_args)
1260        << OrigFormatExpr->getSourceRange();
1261    }
1262    // CHECK: Does the number of data arguments exceed the number of
1263    //        format conversions in the format string?
1264    else if (numConversions < numDataArgs)
1265      Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
1266           diag::warn_printf_too_many_data_args)
1267        << OrigFormatExpr->getSourceRange();
1268  }
1269}
1270
1271//===--- CHECK: Return Address of Stack Variable --------------------------===//
1272
1273static DeclRefExpr* EvalVal(Expr *E);
1274static DeclRefExpr* EvalAddr(Expr* E);
1275
1276/// CheckReturnStackAddr - Check if a return statement returns the address
1277///   of a stack variable.
1278void
1279Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1280                           SourceLocation ReturnLoc) {
1281
1282  // Perform checking for returned stack addresses.
1283  if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
1284    if (DeclRefExpr *DR = EvalAddr(RetValExp))
1285      Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
1286       << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1287
1288    // Skip over implicit cast expressions when checking for block expressions.
1289    RetValExp = RetValExp->IgnoreParenCasts();
1290
1291    if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
1292      if (C->hasBlockDeclRefExprs())
1293        Diag(C->getLocStart(), diag::err_ret_local_block)
1294          << C->getSourceRange();
1295
1296    if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1297      Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1298        << ALE->getSourceRange();
1299
1300  } else if (lhsType->isReferenceType()) {
1301    // Perform checking for stack values returned by reference.
1302    // Check for a reference to the stack
1303    if (DeclRefExpr *DR = EvalVal(RetValExp))
1304      Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
1305        << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1306  }
1307}
1308
1309/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1310///  check if the expression in a return statement evaluates to an address
1311///  to a location on the stack.  The recursion is used to traverse the
1312///  AST of the return expression, with recursion backtracking when we
1313///  encounter a subexpression that (1) clearly does not lead to the address
1314///  of a stack variable or (2) is something we cannot determine leads to
1315///  the address of a stack variable based on such local checking.
1316///
1317///  EvalAddr processes expressions that are pointers that are used as
1318///  references (and not L-values).  EvalVal handles all other values.
1319///  At the base case of the recursion is a check for a DeclRefExpr* in
1320///  the refers to a stack variable.
1321///
1322///  This implementation handles:
1323///
1324///   * pointer-to-pointer casts
1325///   * implicit conversions from array references to pointers
1326///   * taking the address of fields
1327///   * arbitrary interplay between "&" and "*" operators
1328///   * pointer arithmetic from an address of a stack variable
1329///   * taking the address of an array element where the array is on the stack
1330static DeclRefExpr* EvalAddr(Expr *E) {
1331  // We should only be called for evaluating pointer expressions.
1332  assert((E->getType()->isAnyPointerType() ||
1333          E->getType()->isBlockPointerType() ||
1334          E->getType()->isObjCQualifiedIdType()) &&
1335         "EvalAddr only works on pointers");
1336
1337  // Our "symbolic interpreter" is just a dispatch off the currently
1338  // viewed AST node.  We then recursively traverse the AST by calling
1339  // EvalAddr and EvalVal appropriately.
1340  switch (E->getStmtClass()) {
1341  case Stmt::ParenExprClass:
1342    // Ignore parentheses.
1343    return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
1344
1345  case Stmt::UnaryOperatorClass: {
1346    // The only unary operator that make sense to handle here
1347    // is AddrOf.  All others don't make sense as pointers.
1348    UnaryOperator *U = cast<UnaryOperator>(E);
1349
1350    if (U->getOpcode() == UnaryOperator::AddrOf)
1351      return EvalVal(U->getSubExpr());
1352    else
1353      return NULL;
1354  }
1355
1356  case Stmt::BinaryOperatorClass: {
1357    // Handle pointer arithmetic.  All other binary operators are not valid
1358    // in this context.
1359    BinaryOperator *B = cast<BinaryOperator>(E);
1360    BinaryOperator::Opcode op = B->getOpcode();
1361
1362    if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1363      return NULL;
1364
1365    Expr *Base = B->getLHS();
1366
1367    // Determine which argument is the real pointer base.  It could be
1368    // the RHS argument instead of the LHS.
1369    if (!Base->getType()->isPointerType()) Base = B->getRHS();
1370
1371    assert (Base->getType()->isPointerType());
1372    return EvalAddr(Base);
1373  }
1374
1375  // For conditional operators we need to see if either the LHS or RHS are
1376  // valid DeclRefExpr*s.  If one of them is valid, we return it.
1377  case Stmt::ConditionalOperatorClass: {
1378    ConditionalOperator *C = cast<ConditionalOperator>(E);
1379
1380    // Handle the GNU extension for missing LHS.
1381    if (Expr *lhsExpr = C->getLHS())
1382      if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1383        return LHS;
1384
1385     return EvalAddr(C->getRHS());
1386  }
1387
1388  // For casts, we need to handle conversions from arrays to
1389  // pointer values, and pointer-to-pointer conversions.
1390  case Stmt::ImplicitCastExprClass:
1391  case Stmt::CStyleCastExprClass:
1392  case Stmt::CXXFunctionalCastExprClass: {
1393    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1394    QualType T = SubExpr->getType();
1395
1396    if (SubExpr->getType()->isPointerType() ||
1397        SubExpr->getType()->isBlockPointerType() ||
1398        SubExpr->getType()->isObjCQualifiedIdType())
1399      return EvalAddr(SubExpr);
1400    else if (T->isArrayType())
1401      return EvalVal(SubExpr);
1402    else
1403      return 0;
1404  }
1405
1406  // C++ casts.  For dynamic casts, static casts, and const casts, we
1407  // are always converting from a pointer-to-pointer, so we just blow
1408  // through the cast.  In the case the dynamic cast doesn't fail (and
1409  // return NULL), we take the conservative route and report cases
1410  // where we return the address of a stack variable.  For Reinterpre
1411  // FIXME: The comment about is wrong; we're not always converting
1412  // from pointer to pointer. I'm guessing that this code should also
1413  // handle references to objects.
1414  case Stmt::CXXStaticCastExprClass:
1415  case Stmt::CXXDynamicCastExprClass:
1416  case Stmt::CXXConstCastExprClass:
1417  case Stmt::CXXReinterpretCastExprClass: {
1418      Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
1419      if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
1420        return EvalAddr(S);
1421      else
1422        return NULL;
1423  }
1424
1425  // Everything else: we simply don't reason about them.
1426  default:
1427    return NULL;
1428  }
1429}
1430
1431
1432///  EvalVal - This function is complements EvalAddr in the mutual recursion.
1433///   See the comments for EvalAddr for more details.
1434static DeclRefExpr* EvalVal(Expr *E) {
1435
1436  // We should only be called for evaluating non-pointer expressions, or
1437  // expressions with a pointer type that are not used as references but instead
1438  // are l-values (e.g., DeclRefExpr with a pointer type).
1439
1440  // Our "symbolic interpreter" is just a dispatch off the currently
1441  // viewed AST node.  We then recursively traverse the AST by calling
1442  // EvalAddr and EvalVal appropriately.
1443  switch (E->getStmtClass()) {
1444  case Stmt::DeclRefExprClass: {
1445    // DeclRefExpr: the base case.  When we hit a DeclRefExpr we are looking
1446    //  at code that refers to a variable's name.  We check if it has local
1447    //  storage within the function, and if so, return the expression.
1448    DeclRefExpr *DR = cast<DeclRefExpr>(E);
1449
1450    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1451      if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1452
1453    return NULL;
1454  }
1455
1456  case Stmt::ParenExprClass:
1457    // Ignore parentheses.
1458    return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1459
1460  case Stmt::UnaryOperatorClass: {
1461    // The only unary operator that make sense to handle here
1462    // is Deref.  All others don't resolve to a "name."  This includes
1463    // handling all sorts of rvalues passed to a unary operator.
1464    UnaryOperator *U = cast<UnaryOperator>(E);
1465
1466    if (U->getOpcode() == UnaryOperator::Deref)
1467      return EvalAddr(U->getSubExpr());
1468
1469    return NULL;
1470  }
1471
1472  case Stmt::ArraySubscriptExprClass: {
1473    // Array subscripts are potential references to data on the stack.  We
1474    // retrieve the DeclRefExpr* for the array variable if it indeed
1475    // has local storage.
1476    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
1477  }
1478
1479  case Stmt::ConditionalOperatorClass: {
1480    // For conditional operators we need to see if either the LHS or RHS are
1481    // non-NULL DeclRefExpr's.  If one is non-NULL, we return it.
1482    ConditionalOperator *C = cast<ConditionalOperator>(E);
1483
1484    // Handle the GNU extension for missing LHS.
1485    if (Expr *lhsExpr = C->getLHS())
1486      if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1487        return LHS;
1488
1489    return EvalVal(C->getRHS());
1490  }
1491
1492  // Accesses to members are potential references to data on the stack.
1493  case Stmt::MemberExprClass: {
1494    MemberExpr *M = cast<MemberExpr>(E);
1495
1496    // Check for indirect access.  We only want direct field accesses.
1497    if (!M->isArrow())
1498      return EvalVal(M->getBase());
1499    else
1500      return NULL;
1501  }
1502
1503  // Everything else: we simply don't reason about them.
1504  default:
1505    return NULL;
1506  }
1507}
1508
1509//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1510
1511/// Check for comparisons of floating point operands using != and ==.
1512/// Issue a warning if these are no self-comparisons, as they are not likely
1513/// to do what the programmer intended.
1514void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1515  bool EmitWarning = true;
1516
1517  Expr* LeftExprSansParen = lex->IgnoreParens();
1518  Expr* RightExprSansParen = rex->IgnoreParens();
1519
1520  // Special case: check for x == x (which is OK).
1521  // Do not emit warnings for such cases.
1522  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1523    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1524      if (DRL->getDecl() == DRR->getDecl())
1525        EmitWarning = false;
1526
1527
1528  // Special case: check for comparisons against literals that can be exactly
1529  //  represented by APFloat.  In such cases, do not emit a warning.  This
1530  //  is a heuristic: often comparison against such literals are used to
1531  //  detect if a value in a variable has not changed.  This clearly can
1532  //  lead to false negatives.
1533  if (EmitWarning) {
1534    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1535      if (FLL->isExact())
1536        EmitWarning = false;
1537    } else
1538      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1539        if (FLR->isExact())
1540          EmitWarning = false;
1541    }
1542  }
1543
1544  // Check for comparisons with builtin types.
1545  if (EmitWarning)
1546    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1547      if (CL->isBuiltinCall(Context))
1548        EmitWarning = false;
1549
1550  if (EmitWarning)
1551    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1552      if (CR->isBuiltinCall(Context))
1553        EmitWarning = false;
1554
1555  // Emit the diagnostic.
1556  if (EmitWarning)
1557    Diag(loc, diag::warn_floatingpoint_eq)
1558      << lex->getSourceRange() << rex->getSourceRange();
1559}
1560
1561//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1562//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
1563
1564namespace {
1565
1566/// Structure recording the 'active' range of an integer-valued
1567/// expression.
1568struct IntRange {
1569  /// The number of bits active in the int.
1570  unsigned Width;
1571
1572  /// True if the int is known not to have negative values.
1573  bool NonNegative;
1574
1575  IntRange() {}
1576  IntRange(unsigned Width, bool NonNegative)
1577    : Width(Width), NonNegative(NonNegative)
1578  {}
1579
1580  // Returns the range of the bool type.
1581  static IntRange forBoolType() {
1582    return IntRange(1, true);
1583  }
1584
1585  // Returns the range of an integral type.
1586  static IntRange forType(ASTContext &C, QualType T) {
1587    return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
1588  }
1589
1590  // Returns the range of an integeral type based on its canonical
1591  // representation.
1592  static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1593    assert(T->isCanonicalUnqualified());
1594
1595    if (const VectorType *VT = dyn_cast<VectorType>(T))
1596      T = VT->getElementType().getTypePtr();
1597    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1598      T = CT->getElementType().getTypePtr();
1599    if (const EnumType *ET = dyn_cast<EnumType>(T))
1600      T = ET->getDecl()->getIntegerType().getTypePtr();
1601
1602    const BuiltinType *BT = cast<BuiltinType>(T);
1603    assert(BT->isInteger());
1604
1605    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1606  }
1607
1608  // Returns the supremum of two ranges: i.e. their conservative merge.
1609  static IntRange join(const IntRange &L, const IntRange &R) {
1610    return IntRange(std::max(L.Width, R.Width),
1611                    L.NonNegative && R.NonNegative);
1612  }
1613
1614  // Returns the infinum of two ranges: i.e. their aggressive merge.
1615  static IntRange meet(const IntRange &L, const IntRange &R) {
1616    return IntRange(std::min(L.Width, R.Width),
1617                    L.NonNegative || R.NonNegative);
1618  }
1619};
1620
1621IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1622  if (value.isSigned() && value.isNegative())
1623    return IntRange(value.getMinSignedBits(), false);
1624
1625  if (value.getBitWidth() > MaxWidth)
1626    value.trunc(MaxWidth);
1627
1628  // isNonNegative() just checks the sign bit without considering
1629  // signedness.
1630  return IntRange(value.getActiveBits(), true);
1631}
1632
1633IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
1634                       unsigned MaxWidth) {
1635  if (result.isInt())
1636    return GetValueRange(C, result.getInt(), MaxWidth);
1637
1638  if (result.isVector()) {
1639    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1640    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1641      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1642      R = IntRange::join(R, El);
1643    }
1644    return R;
1645  }
1646
1647  if (result.isComplexInt()) {
1648    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1649    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1650    return IntRange::join(R, I);
1651  }
1652
1653  // This can happen with lossless casts to intptr_t of "based" lvalues.
1654  // Assume it might use arbitrary bits.
1655  // FIXME: The only reason we need to pass the type in here is to get
1656  // the sign right on this one case.  It would be nice if APValue
1657  // preserved this.
1658  assert(result.isLValue());
1659  return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
1660}
1661
1662/// Pseudo-evaluate the given integer expression, estimating the
1663/// range of values it might take.
1664///
1665/// \param MaxWidth - the width to which the value will be truncated
1666IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1667  E = E->IgnoreParens();
1668
1669  // Try a full evaluation first.
1670  Expr::EvalResult result;
1671  if (E->Evaluate(result, C))
1672    return GetValueRange(C, result.Val, E->getType(), MaxWidth);
1673
1674  // I think we only want to look through implicit casts here; if the
1675  // user has an explicit widening cast, we should treat the value as
1676  // being of the new, wider type.
1677  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1678    if (CE->getCastKind() == CastExpr::CK_NoOp)
1679      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1680
1681    IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1682
1683    bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1684    if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1685      isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1686
1687    // Assume that non-integer casts can span the full range of the type.
1688    if (!isIntegerCast)
1689      return OutputTypeRange;
1690
1691    IntRange SubRange
1692      = GetExprRange(C, CE->getSubExpr(),
1693                     std::min(MaxWidth, OutputTypeRange.Width));
1694
1695    // Bail out if the subexpr's range is as wide as the cast type.
1696    if (SubRange.Width >= OutputTypeRange.Width)
1697      return OutputTypeRange;
1698
1699    // Otherwise, we take the smaller width, and we're non-negative if
1700    // either the output type or the subexpr is.
1701    return IntRange(SubRange.Width,
1702                    SubRange.NonNegative || OutputTypeRange.NonNegative);
1703  }
1704
1705  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1706    // If we can fold the condition, just take that operand.
1707    bool CondResult;
1708    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1709      return GetExprRange(C, CondResult ? CO->getTrueExpr()
1710                                        : CO->getFalseExpr(),
1711                          MaxWidth);
1712
1713    // Otherwise, conservatively merge.
1714    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1715    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1716    return IntRange::join(L, R);
1717  }
1718
1719  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1720    switch (BO->getOpcode()) {
1721
1722    // Boolean-valued operations are single-bit and positive.
1723    case BinaryOperator::LAnd:
1724    case BinaryOperator::LOr:
1725    case BinaryOperator::LT:
1726    case BinaryOperator::GT:
1727    case BinaryOperator::LE:
1728    case BinaryOperator::GE:
1729    case BinaryOperator::EQ:
1730    case BinaryOperator::NE:
1731      return IntRange::forBoolType();
1732
1733    // Operations with opaque sources are black-listed.
1734    case BinaryOperator::PtrMemD:
1735    case BinaryOperator::PtrMemI:
1736      return IntRange::forType(C, E->getType());
1737
1738    // Bitwise-and uses the *infinum* of the two source ranges.
1739    case BinaryOperator::And:
1740      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1741                            GetExprRange(C, BO->getRHS(), MaxWidth));
1742
1743    // Left shift gets black-listed based on a judgement call.
1744    case BinaryOperator::Shl:
1745      return IntRange::forType(C, E->getType());
1746
1747    // Right shift by a constant can narrow its left argument.
1748    case BinaryOperator::Shr: {
1749      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1750
1751      // If the shift amount is a positive constant, drop the width by
1752      // that much.
1753      llvm::APSInt shift;
1754      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1755          shift.isNonNegative()) {
1756        unsigned zext = shift.getZExtValue();
1757        if (zext >= L.Width)
1758          L.Width = (L.NonNegative ? 0 : 1);
1759        else
1760          L.Width -= zext;
1761      }
1762
1763      return L;
1764    }
1765
1766    // Comma acts as its right operand.
1767    case BinaryOperator::Comma:
1768      return GetExprRange(C, BO->getRHS(), MaxWidth);
1769
1770    // Black-list pointer subtractions.
1771    case BinaryOperator::Sub:
1772      if (BO->getLHS()->getType()->isPointerType())
1773        return IntRange::forType(C, E->getType());
1774      // fallthrough
1775
1776    default:
1777      break;
1778    }
1779
1780    // Treat every other operator as if it were closed on the
1781    // narrowest type that encompasses both operands.
1782    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1783    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1784    return IntRange::join(L, R);
1785  }
1786
1787  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1788    switch (UO->getOpcode()) {
1789    // Boolean-valued operations are white-listed.
1790    case UnaryOperator::LNot:
1791      return IntRange::forBoolType();
1792
1793    // Operations with opaque sources are black-listed.
1794    case UnaryOperator::Deref:
1795    case UnaryOperator::AddrOf: // should be impossible
1796    case UnaryOperator::OffsetOf:
1797      return IntRange::forType(C, E->getType());
1798
1799    default:
1800      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1801    }
1802  }
1803
1804  FieldDecl *BitField = E->getBitField();
1805  if (BitField) {
1806    llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1807    unsigned BitWidth = BitWidthAP.getZExtValue();
1808
1809    return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1810  }
1811
1812  return IntRange::forType(C, E->getType());
1813}
1814
1815/// Checks whether the given value, which currently has the given
1816/// source semantics, has the same value when coerced through the
1817/// target semantics.
1818bool IsSameFloatAfterCast(const llvm::APFloat &value,
1819                          const llvm::fltSemantics &Src,
1820                          const llvm::fltSemantics &Tgt) {
1821  llvm::APFloat truncated = value;
1822
1823  bool ignored;
1824  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
1825  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
1826
1827  return truncated.bitwiseIsEqual(value);
1828}
1829
1830/// Checks whether the given value, which currently has the given
1831/// source semantics, has the same value when coerced through the
1832/// target semantics.
1833///
1834/// The value might be a vector of floats (or a complex number).
1835bool IsSameFloatAfterCast(const APValue &value,
1836                          const llvm::fltSemantics &Src,
1837                          const llvm::fltSemantics &Tgt) {
1838  if (value.isFloat())
1839    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
1840
1841  if (value.isVector()) {
1842    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
1843      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
1844        return false;
1845    return true;
1846  }
1847
1848  assert(value.isComplexFloat());
1849  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
1850          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
1851}
1852
1853} // end anonymous namespace
1854
1855/// \brief Implements -Wsign-compare.
1856///
1857/// \param lex the left-hand expression
1858/// \param rex the right-hand expression
1859/// \param OpLoc the location of the joining operator
1860/// \param Equality whether this is an "equality-like" join, which
1861///   suppresses the warning in some cases
1862void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
1863                            const PartialDiagnostic &PD, bool Equality) {
1864  // Don't warn if we're in an unevaluated context.
1865  if (ExprEvalContexts.back().Context == Unevaluated)
1866    return;
1867
1868  // If either expression is value-dependent, don't warn. We'll get another
1869  // chance at instantiation time.
1870  if (lex->isValueDependent() || rex->isValueDependent())
1871    return;
1872
1873  QualType lt = lex->getType(), rt = rex->getType();
1874
1875  // Only warn if both operands are integral.
1876  if (!lt->isIntegerType() || !rt->isIntegerType())
1877    return;
1878
1879  // In C, the width of a bitfield determines its type, and the
1880  // declared type only contributes the signedness.  This duplicates
1881  // the work that will later be done by UsualUnaryConversions.
1882  // Eventually, this check will be reorganized in a way that avoids
1883  // this duplication.
1884  if (!getLangOptions().CPlusPlus) {
1885    QualType tmp;
1886    tmp = Context.isPromotableBitField(lex);
1887    if (!tmp.isNull()) lt = tmp;
1888    tmp = Context.isPromotableBitField(rex);
1889    if (!tmp.isNull()) rt = tmp;
1890  }
1891
1892  // The rule is that the signed operand becomes unsigned, so isolate the
1893  // signed operand.
1894  Expr *signedOperand = lex, *unsignedOperand = rex;
1895  QualType signedType = lt, unsignedType = rt;
1896  if (lt->isSignedIntegerType()) {
1897    if (rt->isSignedIntegerType()) return;
1898  } else {
1899    if (!rt->isSignedIntegerType()) return;
1900    std::swap(signedOperand, unsignedOperand);
1901    std::swap(signedType, unsignedType);
1902  }
1903
1904  unsigned unsignedWidth = Context.getIntWidth(unsignedType);
1905  unsigned signedWidth = Context.getIntWidth(signedType);
1906
1907  // If the unsigned type is strictly smaller than the signed type,
1908  // then (1) the result type will be signed and (2) the unsigned
1909  // value will fit fully within the signed type, and thus the result
1910  // of the comparison will be exact.
1911  if (signedWidth > unsignedWidth)
1912    return;
1913
1914  // Otherwise, calculate the effective ranges.
1915  IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth);
1916  IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth);
1917
1918  // We should never be unable to prove that the unsigned operand is
1919  // non-negative.
1920  assert(unsignedRange.NonNegative && "unsigned range includes negative?");
1921
1922  // If the signed operand is non-negative, then the signed->unsigned
1923  // conversion won't change it.
1924  if (signedRange.NonNegative)
1925    return;
1926
1927  // For (in)equality comparisons, if the unsigned operand is a
1928  // constant which cannot collide with a overflowed signed operand,
1929  // then reinterpreting the signed operand as unsigned will not
1930  // change the result of the comparison.
1931  if (Equality && unsignedRange.Width < unsignedWidth)
1932    return;
1933
1934  Diag(OpLoc, PD)
1935    << lt << rt << lex->getSourceRange() << rex->getSourceRange();
1936}
1937
1938/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
1939static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
1940  S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
1941}
1942
1943/// Implements -Wconversion.
1944void Sema::CheckImplicitConversion(Expr *E, QualType T) {
1945  // Don't diagnose in unevaluated contexts.
1946  if (ExprEvalContexts.back().Context == Sema::Unevaluated)
1947    return;
1948
1949  // Don't diagnose for value-dependent expressions.
1950  if (E->isValueDependent())
1951    return;
1952
1953  const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
1954  const Type *Target = Context.getCanonicalType(T).getTypePtr();
1955
1956  // Never diagnose implicit casts to bool.
1957  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
1958    return;
1959
1960  // Strip vector types.
1961  if (isa<VectorType>(Source)) {
1962    if (!isa<VectorType>(Target))
1963      return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar);
1964
1965    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
1966    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
1967  }
1968
1969  // Strip complex types.
1970  if (isa<ComplexType>(Source)) {
1971    if (!isa<ComplexType>(Target))
1972      return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar);
1973
1974    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
1975    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
1976  }
1977
1978  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
1979  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
1980
1981  // If the source is floating point...
1982  if (SourceBT && SourceBT->isFloatingPoint()) {
1983    // ...and the target is floating point...
1984    if (TargetBT && TargetBT->isFloatingPoint()) {
1985      // ...then warn if we're dropping FP rank.
1986
1987      // Builtin FP kinds are ordered by increasing FP rank.
1988      if (SourceBT->getKind() > TargetBT->getKind()) {
1989        // Don't warn about float constants that are precisely
1990        // representable in the target type.
1991        Expr::EvalResult result;
1992        if (E->Evaluate(result, Context)) {
1993          // Value might be a float, a float vector, or a float complex.
1994          if (IsSameFloatAfterCast(result.Val,
1995                     Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
1996                     Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
1997            return;
1998        }
1999
2000        DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision);
2001      }
2002      return;
2003    }
2004
2005    // If the target is integral, always warn.
2006    if ((TargetBT && TargetBT->isInteger()))
2007      // TODO: don't warn for integer values?
2008      return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer);
2009
2010    return;
2011  }
2012
2013  if (!Source->isIntegerType() || !Target->isIntegerType())
2014    return;
2015
2016  IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType()));
2017  IntRange TargetRange = IntRange::forCanonicalType(Context, Target);
2018
2019  // FIXME: also signed<->unsigned?
2020
2021  if (SourceRange.Width > TargetRange.Width) {
2022    // People want to build with -Wshorten-64-to-32 and not -Wconversion
2023    // and by god we'll let them.
2024    if (SourceRange.Width == 64 && TargetRange.Width == 32)
2025      return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32);
2026    return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision);
2027  }
2028
2029  return;
2030}
2031
2032