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