SemaChecking.cpp revision e7ac0a94f1dee3fae9292eb8372962b6d70b3e0d
1//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements extra semantic analysis beyond what is enforced
11//  by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Lex/Preprocessor.h"
22using namespace clang;
23
24/// getLocationOfStringLiteralByte - Return a source location that points to the
25/// specified byte of the specified string literal.
26///
27/// Strings are amazingly complex.  They can be formed from multiple tokens and
28/// can have escape sequences in them in addition to the usual trigraph and
29/// escaped newline business.  This routine handles this complexity.
30///
31SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
32                                                    unsigned ByteNo) const {
33  assert(!SL->isWide() && "This doesn't work for wide strings yet");
34
35  // Loop over all of the tokens in this string until we find the one that
36  // contains the byte we're looking for.
37  unsigned TokNo = 0;
38  while (1) {
39    assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
40    SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
41
42    // Get the spelling of the string so that we can get the data that makes up
43    // the string literal, not the identifier for the macro it is potentially
44    // expanded through.
45    SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
46
47    // Re-lex the token to get its length and original spelling.
48    std::pair<FileID, unsigned> LocInfo =
49      SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
50    std::pair<const char *,const char *> Buffer =
51      SourceMgr.getBufferData(LocInfo.first);
52    const char *StrData = Buffer.first+LocInfo.second;
53
54    // Create a langops struct and enable trigraphs.  This is sufficient for
55    // relexing tokens.
56    LangOptions LangOpts;
57    LangOpts.Trigraphs = true;
58
59    // Create a lexer starting at the beginning of this token.
60    Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
61                   Buffer.second);
62    Token TheTok;
63    TheLexer.LexFromRawLexer(TheTok);
64
65    // Use the StringLiteralParser to compute the length of the string in bytes.
66    StringLiteralParser SLP(&TheTok, 1, PP);
67    unsigned TokNumBytes = SLP.GetStringLength();
68
69    // If the byte is in this token, return the location of the byte.
70    if (ByteNo < TokNumBytes ||
71        (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
72      unsigned Offset =
73        StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
74
75      // Now that we know the offset of the token in the spelling, use the
76      // preprocessor to get the offset in the original source.
77      return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
78    }
79
80    // Move to the next string token.
81    ++TokNo;
82    ByteNo -= TokNumBytes;
83  }
84}
85
86
87/// CheckFunctionCall - Check a direct function call for various correctness
88/// and safety properties not strictly enforced by the C type system.
89Action::OwningExprResult
90Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
91  OwningExprResult TheCallResult(Owned(TheCall));
92  // Get the IdentifierInfo* for the called function.
93  IdentifierInfo *FnInfo = FDecl->getIdentifier();
94
95  // None of the checks below are needed for functions that don't have
96  // simple names (e.g., C++ conversion functions).
97  if (!FnInfo)
98    return move(TheCallResult);
99
100  switch (FDecl->getBuiltinID(Context)) {
101  case Builtin::BI__builtin___CFStringMakeConstantString:
102    assert(TheCall->getNumArgs() == 1 &&
103           "Wrong # arguments to builtin CFStringMakeConstantString");
104    if (CheckObjCString(TheCall->getArg(0)))
105      return ExprError();
106    return move(TheCallResult);
107  case Builtin::BI__builtin_stdarg_start:
108  case Builtin::BI__builtin_va_start:
109    if (SemaBuiltinVAStart(TheCall))
110      return ExprError();
111    return move(TheCallResult);
112  case Builtin::BI__builtin_isgreater:
113  case Builtin::BI__builtin_isgreaterequal:
114  case Builtin::BI__builtin_isless:
115  case Builtin::BI__builtin_islessequal:
116  case Builtin::BI__builtin_islessgreater:
117  case Builtin::BI__builtin_isunordered:
118    if (SemaBuiltinUnorderedCompare(TheCall))
119      return ExprError();
120    return move(TheCallResult);
121  case Builtin::BI__builtin_return_address:
122  case Builtin::BI__builtin_frame_address:
123    if (SemaBuiltinStackAddress(TheCall))
124      return ExprError();
125    return move(TheCallResult);
126  case Builtin::BI__builtin_shufflevector:
127    return SemaBuiltinShuffleVector(TheCall);
128    // TheCall will be freed by the smart pointer here, but that's fine, since
129    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
130  case Builtin::BI__builtin_prefetch:
131    if (SemaBuiltinPrefetch(TheCall))
132      return ExprError();
133    return move(TheCallResult);
134  case Builtin::BI__builtin_object_size:
135    if (SemaBuiltinObjectSize(TheCall))
136      return ExprError();
137    return move(TheCallResult);
138  case Builtin::BI__builtin_longjmp:
139    if (SemaBuiltinLongjmp(TheCall))
140      return ExprError();
141    return move(TheCallResult);
142  case Builtin::BI__sync_fetch_and_add:
143  case Builtin::BI__sync_fetch_and_sub:
144  case Builtin::BI__sync_fetch_and_or:
145  case Builtin::BI__sync_fetch_and_and:
146  case Builtin::BI__sync_fetch_and_xor:
147  case Builtin::BI__sync_add_and_fetch:
148  case Builtin::BI__sync_sub_and_fetch:
149  case Builtin::BI__sync_and_and_fetch:
150  case Builtin::BI__sync_or_and_fetch:
151  case Builtin::BI__sync_xor_and_fetch:
152  case Builtin::BI__sync_val_compare_and_swap:
153  case Builtin::BI__sync_bool_compare_and_swap:
154  case Builtin::BI__sync_lock_test_and_set:
155  case Builtin::BI__sync_lock_release:
156    if (SemaBuiltinAtomicOverloaded(TheCall))
157      return ExprError();
158    return move(TheCallResult);
159  }
160
161  // FIXME: This mechanism should be abstracted to be less fragile and
162  // more efficient. For example, just map function ids to custom
163  // handlers.
164
165  // Printf checking.
166  if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
167    if (Format->getType() == "printf") {
168      bool HasVAListArg = Format->getFirstArg() == 0;
169      if (!HasVAListArg) {
170        if (const FunctionProtoType *Proto
171            = FDecl->getType()->getAsFunctionProtoType())
172        HasVAListArg = !Proto->isVariadic();
173      }
174      CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
175                           HasVAListArg ? 0 : Format->getFirstArg() - 1);
176    }
177  }
178
179  return move(TheCallResult);
180}
181
182/// SemaBuiltinAtomicOverloaded - We have a call to a function like
183/// __sync_fetch_and_add, which is an overloaded function based on the pointer
184/// type of its first argument.  The main ActOnCallExpr routines have already
185/// promoted the types of arguments because all of these calls are prototyped as
186/// void(...).
187///
188/// This function goes through and does final semantic checking for these
189/// builtins,
190bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
191  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
192  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
193
194  // Ensure that we have at least one argument to do type inference from.
195  if (TheCall->getNumArgs() < 1)
196    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
197              << 0 << TheCall->getCallee()->getSourceRange();
198
199  // Inspect the first argument of the atomic builtin.  This should always be
200  // a pointer type, whose element is an integral scalar or pointer type.
201  // Because it is a pointer type, we don't have to worry about any implicit
202  // casts here.
203  Expr *FirstArg = TheCall->getArg(0);
204  if (!FirstArg->getType()->isPointerType())
205    return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
206             << FirstArg->getType() << FirstArg->getSourceRange();
207
208  QualType ValType = FirstArg->getType()->getAsPointerType()->getPointeeType();
209  if (!ValType->isIntegerType() && !ValType->isPointerType() &&
210      !ValType->isBlockPointerType())
211    return Diag(DRE->getLocStart(),
212                diag::err_atomic_builtin_must_be_pointer_intptr)
213             << FirstArg->getType() << FirstArg->getSourceRange();
214
215  // We need to figure out which concrete builtin this maps onto.  For example,
216  // __sync_fetch_and_add with a 2 byte object turns into
217  // __sync_fetch_and_add_2.
218#define BUILTIN_ROW(x) \
219  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
220    Builtin::BI##x##_8, Builtin::BI##x##_16 }
221
222  static const unsigned BuiltinIndices[][5] = {
223    BUILTIN_ROW(__sync_fetch_and_add),
224    BUILTIN_ROW(__sync_fetch_and_sub),
225    BUILTIN_ROW(__sync_fetch_and_or),
226    BUILTIN_ROW(__sync_fetch_and_and),
227    BUILTIN_ROW(__sync_fetch_and_xor),
228
229    BUILTIN_ROW(__sync_add_and_fetch),
230    BUILTIN_ROW(__sync_sub_and_fetch),
231    BUILTIN_ROW(__sync_and_and_fetch),
232    BUILTIN_ROW(__sync_or_and_fetch),
233    BUILTIN_ROW(__sync_xor_and_fetch),
234
235    BUILTIN_ROW(__sync_val_compare_and_swap),
236    BUILTIN_ROW(__sync_bool_compare_and_swap),
237    BUILTIN_ROW(__sync_lock_test_and_set),
238    BUILTIN_ROW(__sync_lock_release)
239  };
240#undef BUILTIN_ROW
241
242  // Determine the index of the size.
243  unsigned SizeIndex;
244  switch (Context.getTypeSize(ValType)/8) {
245  case 1: SizeIndex = 0; break;
246  case 2: SizeIndex = 1; break;
247  case 4: SizeIndex = 2; break;
248  case 8: SizeIndex = 3; break;
249  case 16: SizeIndex = 4; break;
250  default:
251    return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
252             << FirstArg->getType() << FirstArg->getSourceRange();
253  }
254
255  // Each of these builtins has one pointer argument, followed by some number of
256  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
257  // that we ignore.  Find out which row of BuiltinIndices to read from as well
258  // as the number of fixed args.
259  unsigned BuiltinID = FDecl->getBuiltinID(Context);
260  unsigned BuiltinIndex, NumFixed = 1;
261  switch (BuiltinID) {
262  default: assert(0 && "Unknown overloaded atomic builtin!");
263  case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
264  case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
265  case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
266  case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
267  case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
268
269  case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
270  case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
271  case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
272  case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
273  case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
274
275  case Builtin::BI__sync_val_compare_and_swap:
276    BuiltinIndex = 10;
277    NumFixed = 2;
278    break;
279  case Builtin::BI__sync_bool_compare_and_swap:
280    BuiltinIndex = 11;
281    NumFixed = 2;
282    break;
283  case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
284  case Builtin::BI__sync_lock_release:
285    BuiltinIndex = 13;
286    NumFixed = 0;
287    break;
288  }
289
290  // Now that we know how many fixed arguments we expect, first check that we
291  // have at least that many.
292  if (TheCall->getNumArgs() < 1+NumFixed)
293    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
294            << 0 << TheCall->getCallee()->getSourceRange();
295
296
297  // Get the decl for the concrete builtin from this, we can tell what the
298  // concrete integer type we should convert to is.
299  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
300  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
301  IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
302  FunctionDecl *NewBuiltinDecl =
303    cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
304                                           TUScope, false, DRE->getLocStart()));
305  const FunctionProtoType *BuiltinFT =
306    NewBuiltinDecl->getType()->getAsFunctionProtoType();
307  ValType = BuiltinFT->getArgType(0)->getAsPointerType()->getPointeeType();
308
309  // If the first type needs to be converted (e.g. void** -> int*), do it now.
310  if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
311    ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), false);
312    TheCall->setArg(0, FirstArg);
313  }
314
315  // Next, walk the valid ones promoting to the right type.
316  for (unsigned i = 0; i != NumFixed; ++i) {
317    Expr *Arg = TheCall->getArg(i+1);
318
319    // If the argument is an implicit cast, then there was a promotion due to
320    // "...", just remove it now.
321    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
322      Arg = ICE->getSubExpr();
323      ICE->setSubExpr(0);
324      ICE->Destroy(Context);
325      TheCall->setArg(i+1, Arg);
326    }
327
328    // GCC does an implicit conversion to the pointer or integer ValType.  This
329    // can fail in some cases (1i -> int**), check for this error case now.
330    if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg))
331      return true;
332
333    // Okay, we have something that *can* be converted to the right type.  Check
334    // to see if there is a potentially weird extension going on here.  This can
335    // happen when you do an atomic operation on something like an char* and
336    // pass in 42.  The 42 gets converted to char.  This is even more strange
337    // for things like 45.123 -> char, etc.
338    // FIXME: Do this check.
339    ImpCastExprToType(Arg, ValType, false);
340    TheCall->setArg(i+1, Arg);
341  }
342
343  // Switch the DeclRefExpr to refer to the new decl.
344  DRE->setDecl(NewBuiltinDecl);
345  DRE->setType(NewBuiltinDecl->getType());
346
347  // Set the callee in the CallExpr.
348  // FIXME: This leaks the original parens and implicit casts.
349  Expr *PromotedCall = DRE;
350  UsualUnaryConversions(PromotedCall);
351  TheCall->setCallee(PromotedCall);
352
353
354  // Change the result type of the call to match the result type of the decl.
355  TheCall->setType(NewBuiltinDecl->getResultType());
356  return false;
357}
358
359
360/// CheckObjCString - Checks that the argument to the builtin
361/// CFString constructor is correct
362/// FIXME: GCC currently emits the following warning:
363/// "warning: input conversion stopped due to an input byte that does not
364///           belong to the input codeset UTF-8"
365/// Note: It might also make sense to do the UTF-16 conversion here (would
366/// simplify the backend).
367bool Sema::CheckObjCString(Expr *Arg) {
368  Arg = Arg->IgnoreParenCasts();
369  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
370
371  if (!Literal || Literal->isWide()) {
372    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
373      << Arg->getSourceRange();
374    return true;
375  }
376
377  const char *Data = Literal->getStrData();
378  unsigned Length = Literal->getByteLength();
379
380  for (unsigned i = 0; i < Length; ++i) {
381    if (!Data[i]) {
382      Diag(getLocationOfStringLiteralByte(Literal, i),
383           diag::warn_cfstring_literal_contains_nul_character)
384        << Arg->getSourceRange();
385      break;
386    }
387  }
388
389  return false;
390}
391
392/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
393/// Emit an error and return true on failure, return false on success.
394bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
395  Expr *Fn = TheCall->getCallee();
396  if (TheCall->getNumArgs() > 2) {
397    Diag(TheCall->getArg(2)->getLocStart(),
398         diag::err_typecheck_call_too_many_args)
399      << 0 /*function call*/ << Fn->getSourceRange()
400      << SourceRange(TheCall->getArg(2)->getLocStart(),
401                     (*(TheCall->arg_end()-1))->getLocEnd());
402    return true;
403  }
404
405  if (TheCall->getNumArgs() < 2) {
406    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
407      << 0 /*function call*/;
408  }
409
410  // Determine whether the current function is variadic or not.
411  bool isVariadic;
412  if (CurBlock)
413    isVariadic = CurBlock->isVariadic;
414  else if (getCurFunctionDecl()) {
415    if (FunctionProtoType* FTP =
416            dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
417      isVariadic = FTP->isVariadic();
418    else
419      isVariadic = false;
420  } else {
421    isVariadic = getCurMethodDecl()->isVariadic();
422  }
423
424  if (!isVariadic) {
425    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
426    return true;
427  }
428
429  // Verify that the second argument to the builtin is the last argument of the
430  // current function or method.
431  bool SecondArgIsLastNamedArgument = false;
432  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
433
434  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
435    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
436      // FIXME: This isn't correct for methods (results in bogus warning).
437      // Get the last formal in the current function.
438      const ParmVarDecl *LastArg;
439      if (CurBlock)
440        LastArg = *(CurBlock->TheDecl->param_end()-1);
441      else if (FunctionDecl *FD = getCurFunctionDecl())
442        LastArg = *(FD->param_end()-1);
443      else
444        LastArg = *(getCurMethodDecl()->param_end()-1);
445      SecondArgIsLastNamedArgument = PV == LastArg;
446    }
447  }
448
449  if (!SecondArgIsLastNamedArgument)
450    Diag(TheCall->getArg(1)->getLocStart(),
451         diag::warn_second_parameter_of_va_start_not_last_named_argument);
452  return false;
453}
454
455/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
456/// friends.  This is declared to take (...), so we have to check everything.
457bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
458  if (TheCall->getNumArgs() < 2)
459    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
460      << 0 /*function call*/;
461  if (TheCall->getNumArgs() > 2)
462    return Diag(TheCall->getArg(2)->getLocStart(),
463                diag::err_typecheck_call_too_many_args)
464      << 0 /*function call*/
465      << SourceRange(TheCall->getArg(2)->getLocStart(),
466                     (*(TheCall->arg_end()-1))->getLocEnd());
467
468  Expr *OrigArg0 = TheCall->getArg(0);
469  Expr *OrigArg1 = TheCall->getArg(1);
470
471  // Do standard promotions between the two arguments, returning their common
472  // type.
473  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
474
475  // Make sure any conversions are pushed back into the call; this is
476  // type safe since unordered compare builtins are declared as "_Bool
477  // foo(...)".
478  TheCall->setArg(0, OrigArg0);
479  TheCall->setArg(1, OrigArg1);
480
481  // If the common type isn't a real floating type, then the arguments were
482  // invalid for this operation.
483  if (!Res->isRealFloatingType())
484    return Diag(OrigArg0->getLocStart(),
485                diag::err_typecheck_call_invalid_ordered_compare)
486      << OrigArg0->getType() << OrigArg1->getType()
487      << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
488
489  return false;
490}
491
492bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
493  // The signature for these builtins is exact; the only thing we need
494  // to check is that the argument is a constant.
495  SourceLocation Loc;
496  if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
497    return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
498
499  return false;
500}
501
502/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
503// This is declared to take (...), so we have to check everything.
504Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
505  if (TheCall->getNumArgs() < 3)
506    return ExprError(Diag(TheCall->getLocEnd(),
507                          diag::err_typecheck_call_too_few_args)
508      << 0 /*function call*/ << TheCall->getSourceRange());
509
510  QualType FAType = TheCall->getArg(0)->getType();
511  QualType SAType = TheCall->getArg(1)->getType();
512
513  if (!FAType->isVectorType() || !SAType->isVectorType()) {
514    Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
515      << SourceRange(TheCall->getArg(0)->getLocStart(),
516                     TheCall->getArg(1)->getLocEnd());
517    return ExprError();
518  }
519
520  if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
521      Context.getCanonicalType(SAType).getUnqualifiedType()) {
522    Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
523      << SourceRange(TheCall->getArg(0)->getLocStart(),
524                     TheCall->getArg(1)->getLocEnd());
525    return ExprError();
526  }
527
528  unsigned numElements = FAType->getAsVectorType()->getNumElements();
529  if (TheCall->getNumArgs() != numElements+2) {
530    if (TheCall->getNumArgs() < numElements+2)
531      return ExprError(Diag(TheCall->getLocEnd(),
532                            diag::err_typecheck_call_too_few_args)
533               << 0 /*function call*/ << TheCall->getSourceRange());
534    return ExprError(Diag(TheCall->getLocEnd(),
535                          diag::err_typecheck_call_too_many_args)
536             << 0 /*function call*/ << TheCall->getSourceRange());
537  }
538
539  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
540    llvm::APSInt Result(32);
541    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
542      return ExprError(Diag(TheCall->getLocStart(),
543                  diag::err_shufflevector_nonconstant_argument)
544                << TheCall->getArg(i)->getSourceRange());
545
546    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
547      return ExprError(Diag(TheCall->getLocStart(),
548                  diag::err_shufflevector_argument_too_large)
549               << TheCall->getArg(i)->getSourceRange());
550  }
551
552  llvm::SmallVector<Expr*, 32> exprs;
553
554  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
555    exprs.push_back(TheCall->getArg(i));
556    TheCall->setArg(i, 0);
557  }
558
559  return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
560                                            FAType,
561                                            TheCall->getCallee()->getLocStart(),
562                                            TheCall->getRParenLoc()));
563}
564
565/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
566// This is declared to take (const void*, ...) and can take two
567// optional constant int args.
568bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
569  unsigned NumArgs = TheCall->getNumArgs();
570
571  if (NumArgs > 3)
572    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
573             << 0 /*function call*/ << TheCall->getSourceRange();
574
575  // Argument 0 is checked for us and the remaining arguments must be
576  // constant integers.
577  for (unsigned i = 1; i != NumArgs; ++i) {
578    Expr *Arg = TheCall->getArg(i);
579    QualType RWType = Arg->getType();
580
581    const BuiltinType *BT = RWType->getAsBuiltinType();
582    llvm::APSInt Result;
583    if (!BT || BT->getKind() != BuiltinType::Int ||
584        !Arg->isIntegerConstantExpr(Result, Context))
585      return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
586              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
587
588    // FIXME: gcc issues a warning and rewrites these to 0. These
589    // seems especially odd for the third argument since the default
590    // is 3.
591    if (i == 1) {
592      if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
593        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
594             << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
595    } else {
596      if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
597        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
598            << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
599    }
600  }
601
602  return false;
603}
604
605/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
606/// int type). This simply type checks that type is one of the defined
607/// constants (0-3).
608bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
609  Expr *Arg = TheCall->getArg(1);
610  QualType ArgType = Arg->getType();
611  const BuiltinType *BT = ArgType->getAsBuiltinType();
612  llvm::APSInt Result(32);
613  if (!BT || BT->getKind() != BuiltinType::Int ||
614      !Arg->isIntegerConstantExpr(Result, Context)) {
615    return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
616             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
617  }
618
619  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
620    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
621             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
622  }
623
624  return false;
625}
626
627/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
628/// This checks that val is a constant 1.
629bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
630  Expr *Arg = TheCall->getArg(1);
631  llvm::APSInt Result(32);
632  if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
633    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
634             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
635
636  return false;
637}
638
639// Handle i > 1 ? "x" : "y", recursivelly
640bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
641                                  bool HasVAListArg,
642                                  unsigned format_idx, unsigned firstDataArg) {
643
644  switch (E->getStmtClass()) {
645  case Stmt::ConditionalOperatorClass: {
646    const ConditionalOperator *C = cast<ConditionalOperator>(E);
647    return SemaCheckStringLiteral(C->getLHS(), TheCall,
648                                  HasVAListArg, format_idx, firstDataArg)
649        && SemaCheckStringLiteral(C->getRHS(), TheCall,
650                                  HasVAListArg, format_idx, firstDataArg);
651  }
652
653  case Stmt::ImplicitCastExprClass: {
654    const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
655    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
656                                  format_idx, firstDataArg);
657  }
658
659  case Stmt::ParenExprClass: {
660    const ParenExpr *Expr = cast<ParenExpr>(E);
661    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
662                                  format_idx, firstDataArg);
663  }
664
665  case Stmt::DeclRefExprClass: {
666    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
667
668    // As an exception, do not flag errors for variables binding to
669    // const string literals.
670    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
671      bool isConstant = false;
672      QualType T = DR->getType();
673
674      if (const ArrayType *AT = Context.getAsArrayType(T)) {
675        isConstant = AT->getElementType().isConstant(Context);
676      }
677      else if (const PointerType *PT = T->getAsPointerType()) {
678        isConstant = T.isConstant(Context) &&
679                     PT->getPointeeType().isConstant(Context);
680      }
681
682      if (isConstant) {
683        const VarDecl *Def = 0;
684        if (const Expr *Init = VD->getDefinition(Def))
685          return SemaCheckStringLiteral(Init, TheCall,
686                                        HasVAListArg, format_idx, firstDataArg);
687      }
688    }
689
690    return false;
691  }
692
693  case Stmt::ObjCStringLiteralClass:
694  case Stmt::StringLiteralClass: {
695    const StringLiteral *StrE = NULL;
696
697    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
698      StrE = ObjCFExpr->getString();
699    else
700      StrE = cast<StringLiteral>(E);
701
702    if (StrE) {
703      CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
704                        firstDataArg);
705      return true;
706    }
707
708    return false;
709  }
710
711  default:
712    return false;
713  }
714}
715
716
717/// CheckPrintfArguments - Check calls to printf (and similar functions) for
718/// correct use of format strings.
719///
720///  HasVAListArg - A predicate indicating whether the printf-like
721///    function is passed an explicit va_arg argument (e.g., vprintf)
722///
723///  format_idx - The index into Args for the format string.
724///
725/// Improper format strings to functions in the printf family can be
726/// the source of bizarre bugs and very serious security holes.  A
727/// good source of information is available in the following paper
728/// (which includes additional references):
729///
730///  FormatGuard: Automatic Protection From printf Format String
731///  Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
732///
733/// Functionality implemented:
734///
735///  We can statically check the following properties for string
736///  literal format strings for non v.*printf functions (where the
737///  arguments are passed directly):
738//
739///  (1) Are the number of format conversions equal to the number of
740///      data arguments?
741///
742///  (2) Does each format conversion correctly match the type of the
743///      corresponding data argument?  (TODO)
744///
745/// Moreover, for all printf functions we can:
746///
747///  (3) Check for a missing format string (when not caught by type checking).
748///
749///  (4) Check for no-operation flags; e.g. using "#" with format
750///      conversion 'c'  (TODO)
751///
752///  (5) Check the use of '%n', a major source of security holes.
753///
754///  (6) Check for malformed format conversions that don't specify anything.
755///
756///  (7) Check for empty format strings.  e.g: printf("");
757///
758///  (8) Check that the format string is a wide literal.
759///
760///  (9) Also check the arguments of functions with the __format__ attribute.
761///      (TODO).
762///
763/// All of these checks can be done by parsing the format string.
764///
765/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
766void
767Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
768                           unsigned format_idx, unsigned firstDataArg) {
769  const Expr *Fn = TheCall->getCallee();
770
771  // CHECK: printf-like function is called with no format string.
772  if (format_idx >= TheCall->getNumArgs()) {
773    Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
774      << Fn->getSourceRange();
775    return;
776  }
777
778  const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
779
780  // CHECK: format string is not a string literal.
781  //
782  // Dynamically generated format strings are difficult to
783  // automatically vet at compile time.  Requiring that format strings
784  // are string literals: (1) permits the checking of format strings by
785  // the compiler and thereby (2) can practically remove the source of
786  // many format string exploits.
787
788  // Format string can be either ObjC string (e.g. @"%d") or
789  // C string (e.g. "%d")
790  // ObjC string uses the same format specifiers as C string, so we can use
791  // the same format string checking logic for both ObjC and C strings.
792  if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
793                             firstDataArg))
794    return;  // Literal format string found, check done!
795
796  // For vprintf* functions (i.e., HasVAListArg==true), we add a
797  // special check to see if the format string is a function parameter
798  // of the function calling the printf function.  If the function
799  // has an attribute indicating it is a printf-like function, then we
800  // should suppress warnings concerning non-literals being used in a call
801  // to a vprintf function.  For example:
802  //
803  // void
804  // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
805  //      va_list ap;
806  //      va_start(ap, fmt);
807  //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
808  //      ...
809  //
810  //
811  //  FIXME: We don't have full attribute support yet, so just check to see
812  //    if the argument is a DeclRefExpr that references a parameter.  We'll
813  //    add proper support for checking the attribute later.
814  if (HasVAListArg)
815    if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
816      if (isa<ParmVarDecl>(DR->getDecl()))
817        return;
818
819  // If there are no arguments specified, warn with -Wformat-security, otherwise
820  // warn only with -Wformat-nonliteral.
821  if (TheCall->getNumArgs() == format_idx+1)
822    Diag(TheCall->getArg(format_idx)->getLocStart(),
823         diag::warn_printf_nonliteral_noargs)
824      << OrigFormatExpr->getSourceRange();
825  else
826    Diag(TheCall->getArg(format_idx)->getLocStart(),
827         diag::warn_printf_nonliteral)
828           << OrigFormatExpr->getSourceRange();
829}
830
831void Sema::CheckPrintfString(const StringLiteral *FExpr,
832                             const Expr *OrigFormatExpr,
833                             const CallExpr *TheCall, bool HasVAListArg,
834                             unsigned format_idx, unsigned firstDataArg) {
835
836  const ObjCStringLiteral *ObjCFExpr =
837    dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
838
839  // CHECK: is the format string a wide literal?
840  if (FExpr->isWide()) {
841    Diag(FExpr->getLocStart(),
842         diag::warn_printf_format_string_is_wide_literal)
843      << OrigFormatExpr->getSourceRange();
844    return;
845  }
846
847  // Str - The format string.  NOTE: this is NOT null-terminated!
848  const char *Str = FExpr->getStrData();
849
850  // CHECK: empty format string?
851  unsigned StrLen = FExpr->getByteLength();
852
853  if (StrLen == 0) {
854    Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
855      << OrigFormatExpr->getSourceRange();
856    return;
857  }
858
859  // We process the format string using a binary state machine.  The
860  // current state is stored in CurrentState.
861  enum {
862    state_OrdChr,
863    state_Conversion
864  } CurrentState = state_OrdChr;
865
866  // numConversions - The number of conversions seen so far.  This is
867  //  incremented as we traverse the format string.
868  unsigned numConversions = 0;
869
870  // numDataArgs - The number of data arguments after the format
871  //  string.  This can only be determined for non vprintf-like
872  //  functions.  For those functions, this value is 1 (the sole
873  //  va_arg argument).
874  unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
875
876  // Inspect the format string.
877  unsigned StrIdx = 0;
878
879  // LastConversionIdx - Index within the format string where we last saw
880  //  a '%' character that starts a new format conversion.
881  unsigned LastConversionIdx = 0;
882
883  for (; StrIdx < StrLen; ++StrIdx) {
884
885    // Is the number of detected conversion conversions greater than
886    // the number of matching data arguments?  If so, stop.
887    if (!HasVAListArg && numConversions > numDataArgs) break;
888
889    // Handle "\0"
890    if (Str[StrIdx] == '\0') {
891      // The string returned by getStrData() is not null-terminated,
892      // so the presence of a null character is likely an error.
893      Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
894           diag::warn_printf_format_string_contains_null_char)
895        <<  OrigFormatExpr->getSourceRange();
896      return;
897    }
898
899    // Ordinary characters (not processing a format conversion).
900    if (CurrentState == state_OrdChr) {
901      if (Str[StrIdx] == '%') {
902        CurrentState = state_Conversion;
903        LastConversionIdx = StrIdx;
904      }
905      continue;
906    }
907
908    // Seen '%'.  Now processing a format conversion.
909    switch (Str[StrIdx]) {
910    // Handle dynamic precision or width specifier.
911    case '*': {
912      ++numConversions;
913
914      if (!HasVAListArg && numConversions > numDataArgs) {
915        SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
916
917        if (Str[StrIdx-1] == '.')
918          Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
919            << OrigFormatExpr->getSourceRange();
920        else
921          Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
922            << OrigFormatExpr->getSourceRange();
923
924        // Don't do any more checking.  We'll just emit spurious errors.
925        return;
926      }
927
928      // Perform type checking on width/precision specifier.
929      const Expr *E = TheCall->getArg(format_idx+numConversions);
930      if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
931        if (BT->getKind() == BuiltinType::Int)
932          break;
933
934      SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
935
936      if (Str[StrIdx-1] == '.')
937        Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
938          << E->getType() << E->getSourceRange();
939      else
940        Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
941          << E->getType() << E->getSourceRange();
942
943      break;
944    }
945
946    // Characters which can terminate a format conversion
947    // (e.g. "%d").  Characters that specify length modifiers or
948    // other flags are handled by the default case below.
949    //
950    // FIXME: additional checks will go into the following cases.
951    case 'i':
952    case 'd':
953    case 'o':
954    case 'u':
955    case 'x':
956    case 'X':
957    case 'D':
958    case 'O':
959    case 'U':
960    case 'e':
961    case 'E':
962    case 'f':
963    case 'F':
964    case 'g':
965    case 'G':
966    case 'a':
967    case 'A':
968    case 'c':
969    case 'C':
970    case 'S':
971    case 's':
972    case 'p':
973      ++numConversions;
974      CurrentState = state_OrdChr;
975      break;
976
977    // CHECK: Are we using "%n"?  Issue a warning.
978    case 'n': {
979      ++numConversions;
980      CurrentState = state_OrdChr;
981      SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
982                                                          LastConversionIdx);
983
984      Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
985      break;
986    }
987
988    // Handle "%@"
989    case '@':
990      // %@ is allowed in ObjC format strings only.
991      if(ObjCFExpr != NULL)
992        CurrentState = state_OrdChr;
993      else {
994        // Issue a warning: invalid format conversion.
995        SourceLocation Loc =
996          getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
997
998        Diag(Loc, diag::warn_printf_invalid_conversion)
999          <<  std::string(Str+LastConversionIdx,
1000                          Str+std::min(LastConversionIdx+2, StrLen))
1001          << OrigFormatExpr->getSourceRange();
1002      }
1003      ++numConversions;
1004      break;
1005
1006    // Handle "%%"
1007    case '%':
1008      // Sanity check: Was the first "%" character the previous one?
1009      // If not, we will assume that we have a malformed format
1010      // conversion, and that the current "%" character is the start
1011      // of a new conversion.
1012      if (StrIdx - LastConversionIdx == 1)
1013        CurrentState = state_OrdChr;
1014      else {
1015        // Issue a warning: invalid format conversion.
1016        SourceLocation Loc =
1017          getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1018
1019        Diag(Loc, diag::warn_printf_invalid_conversion)
1020          << std::string(Str+LastConversionIdx, Str+StrIdx)
1021          << OrigFormatExpr->getSourceRange();
1022
1023        // This conversion is broken.  Advance to the next format
1024        // conversion.
1025        LastConversionIdx = StrIdx;
1026        ++numConversions;
1027      }
1028      break;
1029
1030    default:
1031      // This case catches all other characters: flags, widths, etc.
1032      // We should eventually process those as well.
1033      break;
1034    }
1035  }
1036
1037  if (CurrentState == state_Conversion) {
1038    // Issue a warning: invalid format conversion.
1039    SourceLocation Loc =
1040      getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1041
1042    Diag(Loc, diag::warn_printf_invalid_conversion)
1043      << std::string(Str+LastConversionIdx,
1044                     Str+std::min(LastConversionIdx+2, StrLen))
1045      << OrigFormatExpr->getSourceRange();
1046    return;
1047  }
1048
1049  if (!HasVAListArg) {
1050    // CHECK: Does the number of format conversions exceed the number
1051    //        of data arguments?
1052    if (numConversions > numDataArgs) {
1053      SourceLocation Loc =
1054        getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
1055
1056      Diag(Loc, diag::warn_printf_insufficient_data_args)
1057        << OrigFormatExpr->getSourceRange();
1058    }
1059    // CHECK: Does the number of data arguments exceed the number of
1060    //        format conversions in the format string?
1061    else if (numConversions < numDataArgs)
1062      Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
1063           diag::warn_printf_too_many_data_args)
1064        << OrigFormatExpr->getSourceRange();
1065  }
1066}
1067
1068//===--- CHECK: Return Address of Stack Variable --------------------------===//
1069
1070static DeclRefExpr* EvalVal(Expr *E);
1071static DeclRefExpr* EvalAddr(Expr* E);
1072
1073/// CheckReturnStackAddr - Check if a return statement returns the address
1074///   of a stack variable.
1075void
1076Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1077                           SourceLocation ReturnLoc) {
1078
1079  // Perform checking for returned stack addresses.
1080  if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
1081    if (DeclRefExpr *DR = EvalAddr(RetValExp))
1082      Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
1083       << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1084
1085    // Skip over implicit cast expressions when checking for block expressions.
1086    if (ImplicitCastExpr *IcExpr =
1087          dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
1088      RetValExp = IcExpr->getSubExpr();
1089
1090    if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
1091      if (C->hasBlockDeclRefExprs())
1092        Diag(C->getLocStart(), diag::err_ret_local_block)
1093          << C->getSourceRange();
1094  }
1095  // Perform checking for stack values returned by reference.
1096  else if (lhsType->isReferenceType()) {
1097    // Check for a reference to the stack
1098    if (DeclRefExpr *DR = EvalVal(RetValExp))
1099      Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
1100        << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1101  }
1102}
1103
1104/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1105///  check if the expression in a return statement evaluates to an address
1106///  to a location on the stack.  The recursion is used to traverse the
1107///  AST of the return expression, with recursion backtracking when we
1108///  encounter a subexpression that (1) clearly does not lead to the address
1109///  of a stack variable or (2) is something we cannot determine leads to
1110///  the address of a stack variable based on such local checking.
1111///
1112///  EvalAddr processes expressions that are pointers that are used as
1113///  references (and not L-values).  EvalVal handles all other values.
1114///  At the base case of the recursion is a check for a DeclRefExpr* in
1115///  the refers to a stack variable.
1116///
1117///  This implementation handles:
1118///
1119///   * pointer-to-pointer casts
1120///   * implicit conversions from array references to pointers
1121///   * taking the address of fields
1122///   * arbitrary interplay between "&" and "*" operators
1123///   * pointer arithmetic from an address of a stack variable
1124///   * taking the address of an array element where the array is on the stack
1125static DeclRefExpr* EvalAddr(Expr *E) {
1126  // We should only be called for evaluating pointer expressions.
1127  assert((E->getType()->isPointerType() ||
1128          E->getType()->isBlockPointerType() ||
1129          E->getType()->isObjCQualifiedIdType()) &&
1130         "EvalAddr only works on pointers");
1131
1132  // Our "symbolic interpreter" is just a dispatch off the currently
1133  // viewed AST node.  We then recursively traverse the AST by calling
1134  // EvalAddr and EvalVal appropriately.
1135  switch (E->getStmtClass()) {
1136  case Stmt::ParenExprClass:
1137    // Ignore parentheses.
1138    return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
1139
1140  case Stmt::UnaryOperatorClass: {
1141    // The only unary operator that make sense to handle here
1142    // is AddrOf.  All others don't make sense as pointers.
1143    UnaryOperator *U = cast<UnaryOperator>(E);
1144
1145    if (U->getOpcode() == UnaryOperator::AddrOf)
1146      return EvalVal(U->getSubExpr());
1147    else
1148      return NULL;
1149  }
1150
1151  case Stmt::BinaryOperatorClass: {
1152    // Handle pointer arithmetic.  All other binary operators are not valid
1153    // in this context.
1154    BinaryOperator *B = cast<BinaryOperator>(E);
1155    BinaryOperator::Opcode op = B->getOpcode();
1156
1157    if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1158      return NULL;
1159
1160    Expr *Base = B->getLHS();
1161
1162    // Determine which argument is the real pointer base.  It could be
1163    // the RHS argument instead of the LHS.
1164    if (!Base->getType()->isPointerType()) Base = B->getRHS();
1165
1166    assert (Base->getType()->isPointerType());
1167    return EvalAddr(Base);
1168  }
1169
1170  // For conditional operators we need to see if either the LHS or RHS are
1171  // valid DeclRefExpr*s.  If one of them is valid, we return it.
1172  case Stmt::ConditionalOperatorClass: {
1173    ConditionalOperator *C = cast<ConditionalOperator>(E);
1174
1175    // Handle the GNU extension for missing LHS.
1176    if (Expr *lhsExpr = C->getLHS())
1177      if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1178        return LHS;
1179
1180     return EvalAddr(C->getRHS());
1181  }
1182
1183  // For casts, we need to handle conversions from arrays to
1184  // pointer values, and pointer-to-pointer conversions.
1185  case Stmt::ImplicitCastExprClass:
1186  case Stmt::CStyleCastExprClass:
1187  case Stmt::CXXFunctionalCastExprClass: {
1188    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1189    QualType T = SubExpr->getType();
1190
1191    if (SubExpr->getType()->isPointerType() ||
1192        SubExpr->getType()->isBlockPointerType() ||
1193        SubExpr->getType()->isObjCQualifiedIdType())
1194      return EvalAddr(SubExpr);
1195    else if (T->isArrayType())
1196      return EvalVal(SubExpr);
1197    else
1198      return 0;
1199  }
1200
1201  // C++ casts.  For dynamic casts, static casts, and const casts, we
1202  // are always converting from a pointer-to-pointer, so we just blow
1203  // through the cast.  In the case the dynamic cast doesn't fail (and
1204  // return NULL), we take the conservative route and report cases
1205  // where we return the address of a stack variable.  For Reinterpre
1206  // FIXME: The comment about is wrong; we're not always converting
1207  // from pointer to pointer. I'm guessing that this code should also
1208  // handle references to objects.
1209  case Stmt::CXXStaticCastExprClass:
1210  case Stmt::CXXDynamicCastExprClass:
1211  case Stmt::CXXConstCastExprClass:
1212  case Stmt::CXXReinterpretCastExprClass: {
1213      Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
1214      if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
1215        return EvalAddr(S);
1216      else
1217        return NULL;
1218  }
1219
1220  // Everything else: we simply don't reason about them.
1221  default:
1222    return NULL;
1223  }
1224}
1225
1226
1227///  EvalVal - This function is complements EvalAddr in the mutual recursion.
1228///   See the comments for EvalAddr for more details.
1229static DeclRefExpr* EvalVal(Expr *E) {
1230
1231  // We should only be called for evaluating non-pointer expressions, or
1232  // expressions with a pointer type that are not used as references but instead
1233  // are l-values (e.g., DeclRefExpr with a pointer type).
1234
1235  // Our "symbolic interpreter" is just a dispatch off the currently
1236  // viewed AST node.  We then recursively traverse the AST by calling
1237  // EvalAddr and EvalVal appropriately.
1238  switch (E->getStmtClass()) {
1239  case Stmt::DeclRefExprClass:
1240  case Stmt::QualifiedDeclRefExprClass: {
1241    // DeclRefExpr: the base case.  When we hit a DeclRefExpr we are looking
1242    //  at code that refers to a variable's name.  We check if it has local
1243    //  storage within the function, and if so, return the expression.
1244    DeclRefExpr *DR = cast<DeclRefExpr>(E);
1245
1246    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1247      if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1248
1249    return NULL;
1250  }
1251
1252  case Stmt::ParenExprClass:
1253    // Ignore parentheses.
1254    return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1255
1256  case Stmt::UnaryOperatorClass: {
1257    // The only unary operator that make sense to handle here
1258    // is Deref.  All others don't resolve to a "name."  This includes
1259    // handling all sorts of rvalues passed to a unary operator.
1260    UnaryOperator *U = cast<UnaryOperator>(E);
1261
1262    if (U->getOpcode() == UnaryOperator::Deref)
1263      return EvalAddr(U->getSubExpr());
1264
1265    return NULL;
1266  }
1267
1268  case Stmt::ArraySubscriptExprClass: {
1269    // Array subscripts are potential references to data on the stack.  We
1270    // retrieve the DeclRefExpr* for the array variable if it indeed
1271    // has local storage.
1272    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
1273  }
1274
1275  case Stmt::ConditionalOperatorClass: {
1276    // For conditional operators we need to see if either the LHS or RHS are
1277    // non-NULL DeclRefExpr's.  If one is non-NULL, we return it.
1278    ConditionalOperator *C = cast<ConditionalOperator>(E);
1279
1280    // Handle the GNU extension for missing LHS.
1281    if (Expr *lhsExpr = C->getLHS())
1282      if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1283        return LHS;
1284
1285    return EvalVal(C->getRHS());
1286  }
1287
1288  // Accesses to members are potential references to data on the stack.
1289  case Stmt::MemberExprClass: {
1290    MemberExpr *M = cast<MemberExpr>(E);
1291
1292    // Check for indirect access.  We only want direct field accesses.
1293    if (!M->isArrow())
1294      return EvalVal(M->getBase());
1295    else
1296      return NULL;
1297  }
1298
1299  // Everything else: we simply don't reason about them.
1300  default:
1301    return NULL;
1302  }
1303}
1304
1305//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1306
1307/// Check for comparisons of floating point operands using != and ==.
1308/// Issue a warning if these are no self-comparisons, as they are not likely
1309/// to do what the programmer intended.
1310void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1311  bool EmitWarning = true;
1312
1313  Expr* LeftExprSansParen = lex->IgnoreParens();
1314  Expr* RightExprSansParen = rex->IgnoreParens();
1315
1316  // Special case: check for x == x (which is OK).
1317  // Do not emit warnings for such cases.
1318  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1319    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1320      if (DRL->getDecl() == DRR->getDecl())
1321        EmitWarning = false;
1322
1323
1324  // Special case: check for comparisons against literals that can be exactly
1325  //  represented by APFloat.  In such cases, do not emit a warning.  This
1326  //  is a heuristic: often comparison against such literals are used to
1327  //  detect if a value in a variable has not changed.  This clearly can
1328  //  lead to false negatives.
1329  if (EmitWarning) {
1330    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1331      if (FLL->isExact())
1332        EmitWarning = false;
1333    }
1334    else
1335      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1336        if (FLR->isExact())
1337          EmitWarning = false;
1338    }
1339  }
1340
1341  // Check for comparisons with builtin types.
1342  if (EmitWarning)
1343    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1344      if (CL->isBuiltinCall(Context))
1345        EmitWarning = false;
1346
1347  if (EmitWarning)
1348    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1349      if (CR->isBuiltinCall(Context))
1350        EmitWarning = false;
1351
1352  // Emit the diagnostic.
1353  if (EmitWarning)
1354    Diag(loc, diag::warn_floatingpoint_eq)
1355      << lex->getSourceRange() << rex->getSourceRange();
1356}
1357