SemaChecking.cpp revision 0538f0e9200df56974b5a71bc276dbce456e9781
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 "clang/Sema/SemaInternal.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/CharUnits.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/Analysis/Analyses/FormatString.h"
27#include "clang/Basic/CharInfo.h"
28#include "clang/Basic/TargetBuiltins.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/Support/ConvertUTF.h"
39#include "llvm/Support/raw_ostream.h"
40#include <limits>
41using namespace clang;
42using namespace sema;
43
44SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45                                                    unsigned ByteNo) const {
46  return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
47                               PP.getLangOpts(), PP.getTargetInfo());
48}
49
50/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking.  Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53  unsigned argCount = call->getNumArgs();
54  if (argCount == desiredArgCount) return false;
55
56  if (argCount < desiredArgCount)
57    return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58        << 0 /*function call*/ << desiredArgCount << argCount
59        << call->getSourceRange();
60
61  // Highlight all the excess arguments.
62  SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63                    call->getArg(argCount - 1)->getLocEnd());
64
65  return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66    << 0 /*function call*/ << desiredArgCount << argCount
67    << call->getArg(1)->getSourceRange();
68}
69
70/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73  if (checkArgCount(S, TheCall, 2))
74    return true;
75
76  // First argument should be an integer.
77  Expr *ValArg = TheCall->getArg(0);
78  QualType Ty = ValArg->getType();
79  if (!Ty->isIntegerType()) {
80    S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81      << ValArg->getSourceRange();
82    return true;
83  }
84
85  // Second argument should be a constant string.
86  Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87  StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88  if (!Literal || !Literal->isAscii()) {
89    S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90      << StrArg->getSourceRange();
91    return true;
92  }
93
94  TheCall->setType(Ty);
95  return false;
96}
97
98ExprResult
99Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
100  ExprResult TheCallResult(Owned(TheCall));
101
102  // Find out if any arguments are required to be integer constant expressions.
103  unsigned ICEArguments = 0;
104  ASTContext::GetBuiltinTypeError Error;
105  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
106  if (Error != ASTContext::GE_None)
107    ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
108
109  // If any arguments are required to be ICE's, check and diagnose.
110  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
111    // Skip arguments not required to be ICE's.
112    if ((ICEArguments & (1 << ArgNo)) == 0) continue;
113
114    llvm::APSInt Result;
115    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
116      return true;
117    ICEArguments &= ~(1 << ArgNo);
118  }
119
120  switch (BuiltinID) {
121  case Builtin::BI__builtin___CFStringMakeConstantString:
122    assert(TheCall->getNumArgs() == 1 &&
123           "Wrong # arguments to builtin CFStringMakeConstantString");
124    if (CheckObjCString(TheCall->getArg(0)))
125      return ExprError();
126    break;
127  case Builtin::BI__builtin_stdarg_start:
128  case Builtin::BI__builtin_va_start:
129    if (SemaBuiltinVAStart(TheCall))
130      return ExprError();
131    break;
132  case Builtin::BI__builtin_isgreater:
133  case Builtin::BI__builtin_isgreaterequal:
134  case Builtin::BI__builtin_isless:
135  case Builtin::BI__builtin_islessequal:
136  case Builtin::BI__builtin_islessgreater:
137  case Builtin::BI__builtin_isunordered:
138    if (SemaBuiltinUnorderedCompare(TheCall))
139      return ExprError();
140    break;
141  case Builtin::BI__builtin_fpclassify:
142    if (SemaBuiltinFPClassification(TheCall, 6))
143      return ExprError();
144    break;
145  case Builtin::BI__builtin_isfinite:
146  case Builtin::BI__builtin_isinf:
147  case Builtin::BI__builtin_isinf_sign:
148  case Builtin::BI__builtin_isnan:
149  case Builtin::BI__builtin_isnormal:
150    if (SemaBuiltinFPClassification(TheCall, 1))
151      return ExprError();
152    break;
153  case Builtin::BI__builtin_shufflevector:
154    return SemaBuiltinShuffleVector(TheCall);
155    // TheCall will be freed by the smart pointer here, but that's fine, since
156    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
157  case Builtin::BI__builtin_prefetch:
158    if (SemaBuiltinPrefetch(TheCall))
159      return ExprError();
160    break;
161  case Builtin::BI__builtin_object_size:
162    if (SemaBuiltinObjectSize(TheCall))
163      return ExprError();
164    break;
165  case Builtin::BI__builtin_longjmp:
166    if (SemaBuiltinLongjmp(TheCall))
167      return ExprError();
168    break;
169
170  case Builtin::BI__builtin_classify_type:
171    if (checkArgCount(*this, TheCall, 1)) return true;
172    TheCall->setType(Context.IntTy);
173    break;
174  case Builtin::BI__builtin_constant_p:
175    if (checkArgCount(*this, TheCall, 1)) return true;
176    TheCall->setType(Context.IntTy);
177    break;
178  case Builtin::BI__sync_fetch_and_add:
179  case Builtin::BI__sync_fetch_and_add_1:
180  case Builtin::BI__sync_fetch_and_add_2:
181  case Builtin::BI__sync_fetch_and_add_4:
182  case Builtin::BI__sync_fetch_and_add_8:
183  case Builtin::BI__sync_fetch_and_add_16:
184  case Builtin::BI__sync_fetch_and_sub:
185  case Builtin::BI__sync_fetch_and_sub_1:
186  case Builtin::BI__sync_fetch_and_sub_2:
187  case Builtin::BI__sync_fetch_and_sub_4:
188  case Builtin::BI__sync_fetch_and_sub_8:
189  case Builtin::BI__sync_fetch_and_sub_16:
190  case Builtin::BI__sync_fetch_and_or:
191  case Builtin::BI__sync_fetch_and_or_1:
192  case Builtin::BI__sync_fetch_and_or_2:
193  case Builtin::BI__sync_fetch_and_or_4:
194  case Builtin::BI__sync_fetch_and_or_8:
195  case Builtin::BI__sync_fetch_and_or_16:
196  case Builtin::BI__sync_fetch_and_and:
197  case Builtin::BI__sync_fetch_and_and_1:
198  case Builtin::BI__sync_fetch_and_and_2:
199  case Builtin::BI__sync_fetch_and_and_4:
200  case Builtin::BI__sync_fetch_and_and_8:
201  case Builtin::BI__sync_fetch_and_and_16:
202  case Builtin::BI__sync_fetch_and_xor:
203  case Builtin::BI__sync_fetch_and_xor_1:
204  case Builtin::BI__sync_fetch_and_xor_2:
205  case Builtin::BI__sync_fetch_and_xor_4:
206  case Builtin::BI__sync_fetch_and_xor_8:
207  case Builtin::BI__sync_fetch_and_xor_16:
208  case Builtin::BI__sync_add_and_fetch:
209  case Builtin::BI__sync_add_and_fetch_1:
210  case Builtin::BI__sync_add_and_fetch_2:
211  case Builtin::BI__sync_add_and_fetch_4:
212  case Builtin::BI__sync_add_and_fetch_8:
213  case Builtin::BI__sync_add_and_fetch_16:
214  case Builtin::BI__sync_sub_and_fetch:
215  case Builtin::BI__sync_sub_and_fetch_1:
216  case Builtin::BI__sync_sub_and_fetch_2:
217  case Builtin::BI__sync_sub_and_fetch_4:
218  case Builtin::BI__sync_sub_and_fetch_8:
219  case Builtin::BI__sync_sub_and_fetch_16:
220  case Builtin::BI__sync_and_and_fetch:
221  case Builtin::BI__sync_and_and_fetch_1:
222  case Builtin::BI__sync_and_and_fetch_2:
223  case Builtin::BI__sync_and_and_fetch_4:
224  case Builtin::BI__sync_and_and_fetch_8:
225  case Builtin::BI__sync_and_and_fetch_16:
226  case Builtin::BI__sync_or_and_fetch:
227  case Builtin::BI__sync_or_and_fetch_1:
228  case Builtin::BI__sync_or_and_fetch_2:
229  case Builtin::BI__sync_or_and_fetch_4:
230  case Builtin::BI__sync_or_and_fetch_8:
231  case Builtin::BI__sync_or_and_fetch_16:
232  case Builtin::BI__sync_xor_and_fetch:
233  case Builtin::BI__sync_xor_and_fetch_1:
234  case Builtin::BI__sync_xor_and_fetch_2:
235  case Builtin::BI__sync_xor_and_fetch_4:
236  case Builtin::BI__sync_xor_and_fetch_8:
237  case Builtin::BI__sync_xor_and_fetch_16:
238  case Builtin::BI__sync_val_compare_and_swap:
239  case Builtin::BI__sync_val_compare_and_swap_1:
240  case Builtin::BI__sync_val_compare_and_swap_2:
241  case Builtin::BI__sync_val_compare_and_swap_4:
242  case Builtin::BI__sync_val_compare_and_swap_8:
243  case Builtin::BI__sync_val_compare_and_swap_16:
244  case Builtin::BI__sync_bool_compare_and_swap:
245  case Builtin::BI__sync_bool_compare_and_swap_1:
246  case Builtin::BI__sync_bool_compare_and_swap_2:
247  case Builtin::BI__sync_bool_compare_and_swap_4:
248  case Builtin::BI__sync_bool_compare_and_swap_8:
249  case Builtin::BI__sync_bool_compare_and_swap_16:
250  case Builtin::BI__sync_lock_test_and_set:
251  case Builtin::BI__sync_lock_test_and_set_1:
252  case Builtin::BI__sync_lock_test_and_set_2:
253  case Builtin::BI__sync_lock_test_and_set_4:
254  case Builtin::BI__sync_lock_test_and_set_8:
255  case Builtin::BI__sync_lock_test_and_set_16:
256  case Builtin::BI__sync_lock_release:
257  case Builtin::BI__sync_lock_release_1:
258  case Builtin::BI__sync_lock_release_2:
259  case Builtin::BI__sync_lock_release_4:
260  case Builtin::BI__sync_lock_release_8:
261  case Builtin::BI__sync_lock_release_16:
262  case Builtin::BI__sync_swap:
263  case Builtin::BI__sync_swap_1:
264  case Builtin::BI__sync_swap_2:
265  case Builtin::BI__sync_swap_4:
266  case Builtin::BI__sync_swap_8:
267  case Builtin::BI__sync_swap_16:
268    return SemaBuiltinAtomicOverloaded(TheCallResult);
269#define BUILTIN(ID, TYPE, ATTRS)
270#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
271  case Builtin::BI##ID: \
272    return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
273#include "clang/Basic/Builtins.def"
274  case Builtin::BI__builtin_annotation:
275    if (SemaBuiltinAnnotation(*this, TheCall))
276      return ExprError();
277    break;
278  }
279
280  // Since the target specific builtins for each arch overlap, only check those
281  // of the arch we are compiling for.
282  if (BuiltinID >= Builtin::FirstTSBuiltin) {
283    switch (Context.getTargetInfo().getTriple().getArch()) {
284      case llvm::Triple::arm:
285      case llvm::Triple::thumb:
286        if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
287          return ExprError();
288        break;
289      case llvm::Triple::mips:
290      case llvm::Triple::mipsel:
291      case llvm::Triple::mips64:
292      case llvm::Triple::mips64el:
293        if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
294          return ExprError();
295        break;
296      default:
297        break;
298    }
299  }
300
301  return TheCallResult;
302}
303
304// Get the valid immediate range for the specified NEON type code.
305static unsigned RFT(unsigned t, bool shift = false) {
306  NeonTypeFlags Type(t);
307  int IsQuad = Type.isQuad();
308  switch (Type.getEltType()) {
309  case NeonTypeFlags::Int8:
310  case NeonTypeFlags::Poly8:
311    return shift ? 7 : (8 << IsQuad) - 1;
312  case NeonTypeFlags::Int16:
313  case NeonTypeFlags::Poly16:
314    return shift ? 15 : (4 << IsQuad) - 1;
315  case NeonTypeFlags::Int32:
316    return shift ? 31 : (2 << IsQuad) - 1;
317  case NeonTypeFlags::Int64:
318    return shift ? 63 : (1 << IsQuad) - 1;
319  case NeonTypeFlags::Float16:
320    assert(!shift && "cannot shift float types!");
321    return (4 << IsQuad) - 1;
322  case NeonTypeFlags::Float32:
323    assert(!shift && "cannot shift float types!");
324    return (2 << IsQuad) - 1;
325  }
326  llvm_unreachable("Invalid NeonTypeFlag!");
327}
328
329/// getNeonEltType - Return the QualType corresponding to the elements of
330/// the vector type specified by the NeonTypeFlags.  This is used to check
331/// the pointer arguments for Neon load/store intrinsics.
332static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
333  switch (Flags.getEltType()) {
334  case NeonTypeFlags::Int8:
335    return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
336  case NeonTypeFlags::Int16:
337    return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
338  case NeonTypeFlags::Int32:
339    return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
340  case NeonTypeFlags::Int64:
341    return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
342  case NeonTypeFlags::Poly8:
343    return Context.SignedCharTy;
344  case NeonTypeFlags::Poly16:
345    return Context.ShortTy;
346  case NeonTypeFlags::Float16:
347    return Context.UnsignedShortTy;
348  case NeonTypeFlags::Float32:
349    return Context.FloatTy;
350  }
351  llvm_unreachable("Invalid NeonTypeFlag!");
352}
353
354bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
355  llvm::APSInt Result;
356
357  uint64_t mask = 0;
358  unsigned TV = 0;
359  int PtrArgNum = -1;
360  bool HasConstPtr = false;
361  switch (BuiltinID) {
362#define GET_NEON_OVERLOAD_CHECK
363#include "clang/Basic/arm_neon.inc"
364#undef GET_NEON_OVERLOAD_CHECK
365  }
366
367  // For NEON intrinsics which are overloaded on vector element type, validate
368  // the immediate which specifies which variant to emit.
369  unsigned ImmArg = TheCall->getNumArgs()-1;
370  if (mask) {
371    if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
372      return true;
373
374    TV = Result.getLimitedValue(64);
375    if ((TV > 63) || (mask & (1ULL << TV)) == 0)
376      return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
377        << TheCall->getArg(ImmArg)->getSourceRange();
378  }
379
380  if (PtrArgNum >= 0) {
381    // Check that pointer arguments have the specified type.
382    Expr *Arg = TheCall->getArg(PtrArgNum);
383    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
384      Arg = ICE->getSubExpr();
385    ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
386    QualType RHSTy = RHS.get()->getType();
387    QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
388    if (HasConstPtr)
389      EltTy = EltTy.withConst();
390    QualType LHSTy = Context.getPointerType(EltTy);
391    AssignConvertType ConvTy;
392    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
393    if (RHS.isInvalid())
394      return true;
395    if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
396                                 RHS.get(), AA_Assigning))
397      return true;
398  }
399
400  // For NEON intrinsics which take an immediate value as part of the
401  // instruction, range check them here.
402  unsigned i = 0, l = 0, u = 0;
403  switch (BuiltinID) {
404  default: return false;
405  case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
406  case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
407  case ARM::BI__builtin_arm_vcvtr_f:
408  case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
409#define GET_NEON_IMMEDIATE_CHECK
410#include "clang/Basic/arm_neon.inc"
411#undef GET_NEON_IMMEDIATE_CHECK
412  };
413
414  // We can't check the value of a dependent argument.
415  if (TheCall->getArg(i)->isTypeDependent() ||
416      TheCall->getArg(i)->isValueDependent())
417    return false;
418
419  // Check that the immediate argument is actually a constant.
420  if (SemaBuiltinConstantArg(TheCall, i, Result))
421    return true;
422
423  // Range check against the upper/lower values for this isntruction.
424  unsigned Val = Result.getZExtValue();
425  if (Val < l || Val > (u + l))
426    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
427      << l << u+l << TheCall->getArg(i)->getSourceRange();
428
429  // FIXME: VFP Intrinsics should error if VFP not present.
430  return false;
431}
432
433bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
434  unsigned i = 0, l = 0, u = 0;
435  switch (BuiltinID) {
436  default: return false;
437  case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
438  case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
439  case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
440  case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
441  case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
442  case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
443  case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
444  };
445
446  // We can't check the value of a dependent argument.
447  if (TheCall->getArg(i)->isTypeDependent() ||
448      TheCall->getArg(i)->isValueDependent())
449    return false;
450
451  // Check that the immediate argument is actually a constant.
452  llvm::APSInt Result;
453  if (SemaBuiltinConstantArg(TheCall, i, Result))
454    return true;
455
456  // Range check against the upper/lower values for this instruction.
457  unsigned Val = Result.getZExtValue();
458  if (Val < l || Val > u)
459    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
460      << l << u << TheCall->getArg(i)->getSourceRange();
461
462  return false;
463}
464
465/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
466/// parameter with the FormatAttr's correct format_idx and firstDataArg.
467/// Returns true when the format fits the function and the FormatStringInfo has
468/// been populated.
469bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
470                               FormatStringInfo *FSI) {
471  FSI->HasVAListArg = Format->getFirstArg() == 0;
472  FSI->FormatIdx = Format->getFormatIdx() - 1;
473  FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
474
475  // The way the format attribute works in GCC, the implicit this argument
476  // of member functions is counted. However, it doesn't appear in our own
477  // lists, so decrement format_idx in that case.
478  if (IsCXXMember) {
479    if(FSI->FormatIdx == 0)
480      return false;
481    --FSI->FormatIdx;
482    if (FSI->FirstDataArg != 0)
483      --FSI->FirstDataArg;
484  }
485  return true;
486}
487
488/// Handles the checks for format strings, non-POD arguments to vararg
489/// functions, and NULL arguments passed to non-NULL parameters.
490void Sema::checkCall(NamedDecl *FDecl,
491                     ArrayRef<const Expr *> Args,
492                     unsigned NumProtoArgs,
493                     bool IsMemberFunction,
494                     SourceLocation Loc,
495                     SourceRange Range,
496                     VariadicCallType CallType) {
497  if (CurContext->isDependentContext())
498    return;
499
500  // Printf and scanf checking.
501  bool HandledFormatString = false;
502  if (FDecl)
503    for (specific_attr_iterator<FormatAttr>
504           I = FDecl->specific_attr_begin<FormatAttr>(),
505           E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
506      if (CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc,
507                               Range))
508          HandledFormatString = true;
509
510  // Refuse POD arguments that weren't caught by the format string
511  // checks above.
512  if (!HandledFormatString && CallType != VariadicDoesNotApply)
513    for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
514      // Args[ArgIdx] can be null in malformed code.
515      if (const Expr *Arg = Args[ArgIdx])
516        variadicArgumentPODCheck(Arg, CallType);
517    }
518
519  if (FDecl) {
520    for (specific_attr_iterator<NonNullAttr>
521           I = FDecl->specific_attr_begin<NonNullAttr>(),
522           E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
523      CheckNonNullArguments(*I, Args.data(), Loc);
524
525    // Type safety checking.
526    for (specific_attr_iterator<ArgumentWithTypeTagAttr>
527           i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
528           e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
529         i != e; ++i) {
530      CheckArgumentWithTypeTag(*i, Args.data());
531    }
532  }
533}
534
535/// CheckConstructorCall - Check a constructor call for correctness and safety
536/// properties not enforced by the C type system.
537void Sema::CheckConstructorCall(FunctionDecl *FDecl,
538                                ArrayRef<const Expr *> Args,
539                                const FunctionProtoType *Proto,
540                                SourceLocation Loc) {
541  VariadicCallType CallType =
542    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
543  checkCall(FDecl, Args, Proto->getNumArgs(),
544            /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
545}
546
547/// CheckFunctionCall - Check a direct function call for various correctness
548/// and safety properties not strictly enforced by the C type system.
549bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
550                             const FunctionProtoType *Proto) {
551  bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
552                              isa<CXXMethodDecl>(FDecl);
553  bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
554                          IsMemberOperatorCall;
555  VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
556                                                  TheCall->getCallee());
557  unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
558  Expr** Args = TheCall->getArgs();
559  unsigned NumArgs = TheCall->getNumArgs();
560  if (IsMemberOperatorCall) {
561    // If this is a call to a member operator, hide the first argument
562    // from checkCall.
563    // FIXME: Our choice of AST representation here is less than ideal.
564    ++Args;
565    --NumArgs;
566  }
567  checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
568            NumProtoArgs,
569            IsMemberFunction, TheCall->getRParenLoc(),
570            TheCall->getCallee()->getSourceRange(), CallType);
571
572  IdentifierInfo *FnInfo = FDecl->getIdentifier();
573  // None of the checks below are needed for functions that don't have
574  // simple names (e.g., C++ conversion functions).
575  if (!FnInfo)
576    return false;
577
578  unsigned CMId = FDecl->getMemoryFunctionKind();
579  if (CMId == 0)
580    return false;
581
582  // Handle memory setting and copying functions.
583  if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
584    CheckStrlcpycatArguments(TheCall, FnInfo);
585  else if (CMId == Builtin::BIstrncat)
586    CheckStrncatArguments(TheCall, FnInfo);
587  else
588    CheckMemaccessArguments(TheCall, CMId, FnInfo);
589
590  return false;
591}
592
593bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
594                               ArrayRef<const Expr *> Args) {
595  VariadicCallType CallType =
596      Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
597
598  checkCall(Method, Args, Method->param_size(),
599            /*IsMemberFunction=*/false,
600            lbrac, Method->getSourceRange(), CallType);
601
602  return false;
603}
604
605bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
606                            const FunctionProtoType *Proto) {
607  const VarDecl *V = dyn_cast<VarDecl>(NDecl);
608  if (!V)
609    return false;
610
611  QualType Ty = V->getType();
612  if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
613    return false;
614
615  VariadicCallType CallType;
616  if (!Proto || !Proto->isVariadic()) {
617    CallType = VariadicDoesNotApply;
618  } else if (Ty->isBlockPointerType()) {
619    CallType = VariadicBlock;
620  } else { // Ty->isFunctionPointerType()
621    CallType = VariadicFunction;
622  }
623  unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
624
625  checkCall(NDecl,
626            llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
627                                             TheCall->getNumArgs()),
628            NumProtoArgs, /*IsMemberFunction=*/false,
629            TheCall->getRParenLoc(),
630            TheCall->getCallee()->getSourceRange(), CallType);
631
632  return false;
633}
634
635/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
636/// such as function pointers returned from functions.
637bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
638  VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
639                                                  TheCall->getCallee());
640  unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
641
642  checkCall(/*FDecl=*/0,
643            llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
644                                             TheCall->getNumArgs()),
645            NumProtoArgs, /*IsMemberFunction=*/false,
646            TheCall->getRParenLoc(),
647            TheCall->getCallee()->getSourceRange(), CallType);
648
649  return false;
650}
651
652ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
653                                         AtomicExpr::AtomicOp Op) {
654  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
655  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
656
657  // All these operations take one of the following forms:
658  enum {
659    // C    __c11_atomic_init(A *, C)
660    Init,
661    // C    __c11_atomic_load(A *, int)
662    Load,
663    // void __atomic_load(A *, CP, int)
664    Copy,
665    // C    __c11_atomic_add(A *, M, int)
666    Arithmetic,
667    // C    __atomic_exchange_n(A *, CP, int)
668    Xchg,
669    // void __atomic_exchange(A *, C *, CP, int)
670    GNUXchg,
671    // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
672    C11CmpXchg,
673    // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
674    GNUCmpXchg
675  } Form = Init;
676  const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
677  const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
678  // where:
679  //   C is an appropriate type,
680  //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
681  //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
682  //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
683  //   the int parameters are for orderings.
684
685  assert(AtomicExpr::AO__c11_atomic_init == 0 &&
686         AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
687         && "need to update code for modified C11 atomics");
688  bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
689               Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
690  bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
691             Op == AtomicExpr::AO__atomic_store_n ||
692             Op == AtomicExpr::AO__atomic_exchange_n ||
693             Op == AtomicExpr::AO__atomic_compare_exchange_n;
694  bool IsAddSub = false;
695
696  switch (Op) {
697  case AtomicExpr::AO__c11_atomic_init:
698    Form = Init;
699    break;
700
701  case AtomicExpr::AO__c11_atomic_load:
702  case AtomicExpr::AO__atomic_load_n:
703    Form = Load;
704    break;
705
706  case AtomicExpr::AO__c11_atomic_store:
707  case AtomicExpr::AO__atomic_load:
708  case AtomicExpr::AO__atomic_store:
709  case AtomicExpr::AO__atomic_store_n:
710    Form = Copy;
711    break;
712
713  case AtomicExpr::AO__c11_atomic_fetch_add:
714  case AtomicExpr::AO__c11_atomic_fetch_sub:
715  case AtomicExpr::AO__atomic_fetch_add:
716  case AtomicExpr::AO__atomic_fetch_sub:
717  case AtomicExpr::AO__atomic_add_fetch:
718  case AtomicExpr::AO__atomic_sub_fetch:
719    IsAddSub = true;
720    // Fall through.
721  case AtomicExpr::AO__c11_atomic_fetch_and:
722  case AtomicExpr::AO__c11_atomic_fetch_or:
723  case AtomicExpr::AO__c11_atomic_fetch_xor:
724  case AtomicExpr::AO__atomic_fetch_and:
725  case AtomicExpr::AO__atomic_fetch_or:
726  case AtomicExpr::AO__atomic_fetch_xor:
727  case AtomicExpr::AO__atomic_fetch_nand:
728  case AtomicExpr::AO__atomic_and_fetch:
729  case AtomicExpr::AO__atomic_or_fetch:
730  case AtomicExpr::AO__atomic_xor_fetch:
731  case AtomicExpr::AO__atomic_nand_fetch:
732    Form = Arithmetic;
733    break;
734
735  case AtomicExpr::AO__c11_atomic_exchange:
736  case AtomicExpr::AO__atomic_exchange_n:
737    Form = Xchg;
738    break;
739
740  case AtomicExpr::AO__atomic_exchange:
741    Form = GNUXchg;
742    break;
743
744  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
745  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
746    Form = C11CmpXchg;
747    break;
748
749  case AtomicExpr::AO__atomic_compare_exchange:
750  case AtomicExpr::AO__atomic_compare_exchange_n:
751    Form = GNUCmpXchg;
752    break;
753  }
754
755  // Check we have the right number of arguments.
756  if (TheCall->getNumArgs() < NumArgs[Form]) {
757    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
758      << 0 << NumArgs[Form] << TheCall->getNumArgs()
759      << TheCall->getCallee()->getSourceRange();
760    return ExprError();
761  } else if (TheCall->getNumArgs() > NumArgs[Form]) {
762    Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
763         diag::err_typecheck_call_too_many_args)
764      << 0 << NumArgs[Form] << TheCall->getNumArgs()
765      << TheCall->getCallee()->getSourceRange();
766    return ExprError();
767  }
768
769  // Inspect the first argument of the atomic operation.
770  Expr *Ptr = TheCall->getArg(0);
771  Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
772  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
773  if (!pointerType) {
774    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
775      << Ptr->getType() << Ptr->getSourceRange();
776    return ExprError();
777  }
778
779  // For a __c11 builtin, this should be a pointer to an _Atomic type.
780  QualType AtomTy = pointerType->getPointeeType(); // 'A'
781  QualType ValType = AtomTy; // 'C'
782  if (IsC11) {
783    if (!AtomTy->isAtomicType()) {
784      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
785        << Ptr->getType() << Ptr->getSourceRange();
786      return ExprError();
787    }
788    if (AtomTy.isConstQualified()) {
789      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
790        << Ptr->getType() << Ptr->getSourceRange();
791      return ExprError();
792    }
793    ValType = AtomTy->getAs<AtomicType>()->getValueType();
794  }
795
796  // For an arithmetic operation, the implied arithmetic must be well-formed.
797  if (Form == Arithmetic) {
798    // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
799    if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
800      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
801        << IsC11 << Ptr->getType() << Ptr->getSourceRange();
802      return ExprError();
803    }
804    if (!IsAddSub && !ValType->isIntegerType()) {
805      Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
806        << IsC11 << Ptr->getType() << Ptr->getSourceRange();
807      return ExprError();
808    }
809  } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
810    // For __atomic_*_n operations, the value type must be a scalar integral or
811    // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
812    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
813      << IsC11 << Ptr->getType() << Ptr->getSourceRange();
814    return ExprError();
815  }
816
817  if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
818    // For GNU atomics, require a trivially-copyable type. This is not part of
819    // the GNU atomics specification, but we enforce it for sanity.
820    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
821      << Ptr->getType() << Ptr->getSourceRange();
822    return ExprError();
823  }
824
825  // FIXME: For any builtin other than a load, the ValType must not be
826  // const-qualified.
827
828  switch (ValType.getObjCLifetime()) {
829  case Qualifiers::OCL_None:
830  case Qualifiers::OCL_ExplicitNone:
831    // okay
832    break;
833
834  case Qualifiers::OCL_Weak:
835  case Qualifiers::OCL_Strong:
836  case Qualifiers::OCL_Autoreleasing:
837    // FIXME: Can this happen? By this point, ValType should be known
838    // to be trivially copyable.
839    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
840      << ValType << Ptr->getSourceRange();
841    return ExprError();
842  }
843
844  QualType ResultType = ValType;
845  if (Form == Copy || Form == GNUXchg || Form == Init)
846    ResultType = Context.VoidTy;
847  else if (Form == C11CmpXchg || Form == GNUCmpXchg)
848    ResultType = Context.BoolTy;
849
850  // The type of a parameter passed 'by value'. In the GNU atomics, such
851  // arguments are actually passed as pointers.
852  QualType ByValType = ValType; // 'CP'
853  if (!IsC11 && !IsN)
854    ByValType = Ptr->getType();
855
856  // The first argument --- the pointer --- has a fixed type; we
857  // deduce the types of the rest of the arguments accordingly.  Walk
858  // the remaining arguments, converting them to the deduced value type.
859  for (unsigned i = 1; i != NumArgs[Form]; ++i) {
860    QualType Ty;
861    if (i < NumVals[Form] + 1) {
862      switch (i) {
863      case 1:
864        // The second argument is the non-atomic operand. For arithmetic, this
865        // is always passed by value, and for a compare_exchange it is always
866        // passed by address. For the rest, GNU uses by-address and C11 uses
867        // by-value.
868        assert(Form != Load);
869        if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
870          Ty = ValType;
871        else if (Form == Copy || Form == Xchg)
872          Ty = ByValType;
873        else if (Form == Arithmetic)
874          Ty = Context.getPointerDiffType();
875        else
876          Ty = Context.getPointerType(ValType.getUnqualifiedType());
877        break;
878      case 2:
879        // The third argument to compare_exchange / GNU exchange is a
880        // (pointer to a) desired value.
881        Ty = ByValType;
882        break;
883      case 3:
884        // The fourth argument to GNU compare_exchange is a 'weak' flag.
885        Ty = Context.BoolTy;
886        break;
887      }
888    } else {
889      // The order(s) are always converted to int.
890      Ty = Context.IntTy;
891    }
892
893    InitializedEntity Entity =
894        InitializedEntity::InitializeParameter(Context, Ty, false);
895    ExprResult Arg = TheCall->getArg(i);
896    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
897    if (Arg.isInvalid())
898      return true;
899    TheCall->setArg(i, Arg.get());
900  }
901
902  // Permute the arguments into a 'consistent' order.
903  SmallVector<Expr*, 5> SubExprs;
904  SubExprs.push_back(Ptr);
905  switch (Form) {
906  case Init:
907    // Note, AtomicExpr::getVal1() has a special case for this atomic.
908    SubExprs.push_back(TheCall->getArg(1)); // Val1
909    break;
910  case Load:
911    SubExprs.push_back(TheCall->getArg(1)); // Order
912    break;
913  case Copy:
914  case Arithmetic:
915  case Xchg:
916    SubExprs.push_back(TheCall->getArg(2)); // Order
917    SubExprs.push_back(TheCall->getArg(1)); // Val1
918    break;
919  case GNUXchg:
920    // Note, AtomicExpr::getVal2() has a special case for this atomic.
921    SubExprs.push_back(TheCall->getArg(3)); // Order
922    SubExprs.push_back(TheCall->getArg(1)); // Val1
923    SubExprs.push_back(TheCall->getArg(2)); // Val2
924    break;
925  case C11CmpXchg:
926    SubExprs.push_back(TheCall->getArg(3)); // Order
927    SubExprs.push_back(TheCall->getArg(1)); // Val1
928    SubExprs.push_back(TheCall->getArg(4)); // OrderFail
929    SubExprs.push_back(TheCall->getArg(2)); // Val2
930    break;
931  case GNUCmpXchg:
932    SubExprs.push_back(TheCall->getArg(4)); // Order
933    SubExprs.push_back(TheCall->getArg(1)); // Val1
934    SubExprs.push_back(TheCall->getArg(5)); // OrderFail
935    SubExprs.push_back(TheCall->getArg(2)); // Val2
936    SubExprs.push_back(TheCall->getArg(3)); // Weak
937    break;
938  }
939
940  AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
941                                            SubExprs, ResultType, Op,
942                                            TheCall->getRParenLoc());
943
944  if ((Op == AtomicExpr::AO__c11_atomic_load ||
945       (Op == AtomicExpr::AO__c11_atomic_store)) &&
946      Context.AtomicUsesUnsupportedLibcall(AE))
947    Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
948    ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
949
950  return Owned(AE);
951}
952
953
954/// checkBuiltinArgument - Given a call to a builtin function, perform
955/// normal type-checking on the given argument, updating the call in
956/// place.  This is useful when a builtin function requires custom
957/// type-checking for some of its arguments but not necessarily all of
958/// them.
959///
960/// Returns true on error.
961static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
962  FunctionDecl *Fn = E->getDirectCallee();
963  assert(Fn && "builtin call without direct callee!");
964
965  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
966  InitializedEntity Entity =
967    InitializedEntity::InitializeParameter(S.Context, Param);
968
969  ExprResult Arg = E->getArg(0);
970  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
971  if (Arg.isInvalid())
972    return true;
973
974  E->setArg(ArgIndex, Arg.take());
975  return false;
976}
977
978/// SemaBuiltinAtomicOverloaded - We have a call to a function like
979/// __sync_fetch_and_add, which is an overloaded function based on the pointer
980/// type of its first argument.  The main ActOnCallExpr routines have already
981/// promoted the types of arguments because all of these calls are prototyped as
982/// void(...).
983///
984/// This function goes through and does final semantic checking for these
985/// builtins,
986ExprResult
987Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
988  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
989  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
990  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
991
992  // Ensure that we have at least one argument to do type inference from.
993  if (TheCall->getNumArgs() < 1) {
994    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
995      << 0 << 1 << TheCall->getNumArgs()
996      << TheCall->getCallee()->getSourceRange();
997    return ExprError();
998  }
999
1000  // Inspect the first argument of the atomic builtin.  This should always be
1001  // a pointer type, whose element is an integral scalar or pointer type.
1002  // Because it is a pointer type, we don't have to worry about any implicit
1003  // casts here.
1004  // FIXME: We don't allow floating point scalars as input.
1005  Expr *FirstArg = TheCall->getArg(0);
1006  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1007  if (FirstArgResult.isInvalid())
1008    return ExprError();
1009  FirstArg = FirstArgResult.take();
1010  TheCall->setArg(0, FirstArg);
1011
1012  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1013  if (!pointerType) {
1014    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1015      << FirstArg->getType() << FirstArg->getSourceRange();
1016    return ExprError();
1017  }
1018
1019  QualType ValType = pointerType->getPointeeType();
1020  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1021      !ValType->isBlockPointerType()) {
1022    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1023      << FirstArg->getType() << FirstArg->getSourceRange();
1024    return ExprError();
1025  }
1026
1027  switch (ValType.getObjCLifetime()) {
1028  case Qualifiers::OCL_None:
1029  case Qualifiers::OCL_ExplicitNone:
1030    // okay
1031    break;
1032
1033  case Qualifiers::OCL_Weak:
1034  case Qualifiers::OCL_Strong:
1035  case Qualifiers::OCL_Autoreleasing:
1036    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1037      << ValType << FirstArg->getSourceRange();
1038    return ExprError();
1039  }
1040
1041  // Strip any qualifiers off ValType.
1042  ValType = ValType.getUnqualifiedType();
1043
1044  // The majority of builtins return a value, but a few have special return
1045  // types, so allow them to override appropriately below.
1046  QualType ResultType = ValType;
1047
1048  // We need to figure out which concrete builtin this maps onto.  For example,
1049  // __sync_fetch_and_add with a 2 byte object turns into
1050  // __sync_fetch_and_add_2.
1051#define BUILTIN_ROW(x) \
1052  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1053    Builtin::BI##x##_8, Builtin::BI##x##_16 }
1054
1055  static const unsigned BuiltinIndices[][5] = {
1056    BUILTIN_ROW(__sync_fetch_and_add),
1057    BUILTIN_ROW(__sync_fetch_and_sub),
1058    BUILTIN_ROW(__sync_fetch_and_or),
1059    BUILTIN_ROW(__sync_fetch_and_and),
1060    BUILTIN_ROW(__sync_fetch_and_xor),
1061
1062    BUILTIN_ROW(__sync_add_and_fetch),
1063    BUILTIN_ROW(__sync_sub_and_fetch),
1064    BUILTIN_ROW(__sync_and_and_fetch),
1065    BUILTIN_ROW(__sync_or_and_fetch),
1066    BUILTIN_ROW(__sync_xor_and_fetch),
1067
1068    BUILTIN_ROW(__sync_val_compare_and_swap),
1069    BUILTIN_ROW(__sync_bool_compare_and_swap),
1070    BUILTIN_ROW(__sync_lock_test_and_set),
1071    BUILTIN_ROW(__sync_lock_release),
1072    BUILTIN_ROW(__sync_swap)
1073  };
1074#undef BUILTIN_ROW
1075
1076  // Determine the index of the size.
1077  unsigned SizeIndex;
1078  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1079  case 1: SizeIndex = 0; break;
1080  case 2: SizeIndex = 1; break;
1081  case 4: SizeIndex = 2; break;
1082  case 8: SizeIndex = 3; break;
1083  case 16: SizeIndex = 4; break;
1084  default:
1085    Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1086      << FirstArg->getType() << FirstArg->getSourceRange();
1087    return ExprError();
1088  }
1089
1090  // Each of these builtins has one pointer argument, followed by some number of
1091  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1092  // that we ignore.  Find out which row of BuiltinIndices to read from as well
1093  // as the number of fixed args.
1094  unsigned BuiltinID = FDecl->getBuiltinID();
1095  unsigned BuiltinIndex, NumFixed = 1;
1096  switch (BuiltinID) {
1097  default: llvm_unreachable("Unknown overloaded atomic builtin!");
1098  case Builtin::BI__sync_fetch_and_add:
1099  case Builtin::BI__sync_fetch_and_add_1:
1100  case Builtin::BI__sync_fetch_and_add_2:
1101  case Builtin::BI__sync_fetch_and_add_4:
1102  case Builtin::BI__sync_fetch_and_add_8:
1103  case Builtin::BI__sync_fetch_and_add_16:
1104    BuiltinIndex = 0;
1105    break;
1106
1107  case Builtin::BI__sync_fetch_and_sub:
1108  case Builtin::BI__sync_fetch_and_sub_1:
1109  case Builtin::BI__sync_fetch_and_sub_2:
1110  case Builtin::BI__sync_fetch_and_sub_4:
1111  case Builtin::BI__sync_fetch_and_sub_8:
1112  case Builtin::BI__sync_fetch_and_sub_16:
1113    BuiltinIndex = 1;
1114    break;
1115
1116  case Builtin::BI__sync_fetch_and_or:
1117  case Builtin::BI__sync_fetch_and_or_1:
1118  case Builtin::BI__sync_fetch_and_or_2:
1119  case Builtin::BI__sync_fetch_and_or_4:
1120  case Builtin::BI__sync_fetch_and_or_8:
1121  case Builtin::BI__sync_fetch_and_or_16:
1122    BuiltinIndex = 2;
1123    break;
1124
1125  case Builtin::BI__sync_fetch_and_and:
1126  case Builtin::BI__sync_fetch_and_and_1:
1127  case Builtin::BI__sync_fetch_and_and_2:
1128  case Builtin::BI__sync_fetch_and_and_4:
1129  case Builtin::BI__sync_fetch_and_and_8:
1130  case Builtin::BI__sync_fetch_and_and_16:
1131    BuiltinIndex = 3;
1132    break;
1133
1134  case Builtin::BI__sync_fetch_and_xor:
1135  case Builtin::BI__sync_fetch_and_xor_1:
1136  case Builtin::BI__sync_fetch_and_xor_2:
1137  case Builtin::BI__sync_fetch_and_xor_4:
1138  case Builtin::BI__sync_fetch_and_xor_8:
1139  case Builtin::BI__sync_fetch_and_xor_16:
1140    BuiltinIndex = 4;
1141    break;
1142
1143  case Builtin::BI__sync_add_and_fetch:
1144  case Builtin::BI__sync_add_and_fetch_1:
1145  case Builtin::BI__sync_add_and_fetch_2:
1146  case Builtin::BI__sync_add_and_fetch_4:
1147  case Builtin::BI__sync_add_and_fetch_8:
1148  case Builtin::BI__sync_add_and_fetch_16:
1149    BuiltinIndex = 5;
1150    break;
1151
1152  case Builtin::BI__sync_sub_and_fetch:
1153  case Builtin::BI__sync_sub_and_fetch_1:
1154  case Builtin::BI__sync_sub_and_fetch_2:
1155  case Builtin::BI__sync_sub_and_fetch_4:
1156  case Builtin::BI__sync_sub_and_fetch_8:
1157  case Builtin::BI__sync_sub_and_fetch_16:
1158    BuiltinIndex = 6;
1159    break;
1160
1161  case Builtin::BI__sync_and_and_fetch:
1162  case Builtin::BI__sync_and_and_fetch_1:
1163  case Builtin::BI__sync_and_and_fetch_2:
1164  case Builtin::BI__sync_and_and_fetch_4:
1165  case Builtin::BI__sync_and_and_fetch_8:
1166  case Builtin::BI__sync_and_and_fetch_16:
1167    BuiltinIndex = 7;
1168    break;
1169
1170  case Builtin::BI__sync_or_and_fetch:
1171  case Builtin::BI__sync_or_and_fetch_1:
1172  case Builtin::BI__sync_or_and_fetch_2:
1173  case Builtin::BI__sync_or_and_fetch_4:
1174  case Builtin::BI__sync_or_and_fetch_8:
1175  case Builtin::BI__sync_or_and_fetch_16:
1176    BuiltinIndex = 8;
1177    break;
1178
1179  case Builtin::BI__sync_xor_and_fetch:
1180  case Builtin::BI__sync_xor_and_fetch_1:
1181  case Builtin::BI__sync_xor_and_fetch_2:
1182  case Builtin::BI__sync_xor_and_fetch_4:
1183  case Builtin::BI__sync_xor_and_fetch_8:
1184  case Builtin::BI__sync_xor_and_fetch_16:
1185    BuiltinIndex = 9;
1186    break;
1187
1188  case Builtin::BI__sync_val_compare_and_swap:
1189  case Builtin::BI__sync_val_compare_and_swap_1:
1190  case Builtin::BI__sync_val_compare_and_swap_2:
1191  case Builtin::BI__sync_val_compare_and_swap_4:
1192  case Builtin::BI__sync_val_compare_and_swap_8:
1193  case Builtin::BI__sync_val_compare_and_swap_16:
1194    BuiltinIndex = 10;
1195    NumFixed = 2;
1196    break;
1197
1198  case Builtin::BI__sync_bool_compare_and_swap:
1199  case Builtin::BI__sync_bool_compare_and_swap_1:
1200  case Builtin::BI__sync_bool_compare_and_swap_2:
1201  case Builtin::BI__sync_bool_compare_and_swap_4:
1202  case Builtin::BI__sync_bool_compare_and_swap_8:
1203  case Builtin::BI__sync_bool_compare_and_swap_16:
1204    BuiltinIndex = 11;
1205    NumFixed = 2;
1206    ResultType = Context.BoolTy;
1207    break;
1208
1209  case Builtin::BI__sync_lock_test_and_set:
1210  case Builtin::BI__sync_lock_test_and_set_1:
1211  case Builtin::BI__sync_lock_test_and_set_2:
1212  case Builtin::BI__sync_lock_test_and_set_4:
1213  case Builtin::BI__sync_lock_test_and_set_8:
1214  case Builtin::BI__sync_lock_test_and_set_16:
1215    BuiltinIndex = 12;
1216    break;
1217
1218  case Builtin::BI__sync_lock_release:
1219  case Builtin::BI__sync_lock_release_1:
1220  case Builtin::BI__sync_lock_release_2:
1221  case Builtin::BI__sync_lock_release_4:
1222  case Builtin::BI__sync_lock_release_8:
1223  case Builtin::BI__sync_lock_release_16:
1224    BuiltinIndex = 13;
1225    NumFixed = 0;
1226    ResultType = Context.VoidTy;
1227    break;
1228
1229  case Builtin::BI__sync_swap:
1230  case Builtin::BI__sync_swap_1:
1231  case Builtin::BI__sync_swap_2:
1232  case Builtin::BI__sync_swap_4:
1233  case Builtin::BI__sync_swap_8:
1234  case Builtin::BI__sync_swap_16:
1235    BuiltinIndex = 14;
1236    break;
1237  }
1238
1239  // Now that we know how many fixed arguments we expect, first check that we
1240  // have at least that many.
1241  if (TheCall->getNumArgs() < 1+NumFixed) {
1242    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1243      << 0 << 1+NumFixed << TheCall->getNumArgs()
1244      << TheCall->getCallee()->getSourceRange();
1245    return ExprError();
1246  }
1247
1248  // Get the decl for the concrete builtin from this, we can tell what the
1249  // concrete integer type we should convert to is.
1250  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1251  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1252  FunctionDecl *NewBuiltinDecl;
1253  if (NewBuiltinID == BuiltinID)
1254    NewBuiltinDecl = FDecl;
1255  else {
1256    // Perform builtin lookup to avoid redeclaring it.
1257    DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1258    LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1259    LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1260    assert(Res.getFoundDecl());
1261    NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1262    if (NewBuiltinDecl == 0)
1263      return ExprError();
1264  }
1265
1266  // The first argument --- the pointer --- has a fixed type; we
1267  // deduce the types of the rest of the arguments accordingly.  Walk
1268  // the remaining arguments, converting them to the deduced value type.
1269  for (unsigned i = 0; i != NumFixed; ++i) {
1270    ExprResult Arg = TheCall->getArg(i+1);
1271
1272    // GCC does an implicit conversion to the pointer or integer ValType.  This
1273    // can fail in some cases (1i -> int**), check for this error case now.
1274    // Initialize the argument.
1275    InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1276                                                   ValType, /*consume*/ false);
1277    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1278    if (Arg.isInvalid())
1279      return ExprError();
1280
1281    // Okay, we have something that *can* be converted to the right type.  Check
1282    // to see if there is a potentially weird extension going on here.  This can
1283    // happen when you do an atomic operation on something like an char* and
1284    // pass in 42.  The 42 gets converted to char.  This is even more strange
1285    // for things like 45.123 -> char, etc.
1286    // FIXME: Do this check.
1287    TheCall->setArg(i+1, Arg.take());
1288  }
1289
1290  ASTContext& Context = this->getASTContext();
1291
1292  // Create a new DeclRefExpr to refer to the new decl.
1293  DeclRefExpr* NewDRE = DeclRefExpr::Create(
1294      Context,
1295      DRE->getQualifierLoc(),
1296      SourceLocation(),
1297      NewBuiltinDecl,
1298      /*enclosing*/ false,
1299      DRE->getLocation(),
1300      Context.BuiltinFnTy,
1301      DRE->getValueKind());
1302
1303  // Set the callee in the CallExpr.
1304  // FIXME: This loses syntactic information.
1305  QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1306  ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1307                                              CK_BuiltinFnToFnPtr);
1308  TheCall->setCallee(PromotedCall.take());
1309
1310  // Change the result type of the call to match the original value type. This
1311  // is arbitrary, but the codegen for these builtins ins design to handle it
1312  // gracefully.
1313  TheCall->setType(ResultType);
1314
1315  return TheCallResult;
1316}
1317
1318/// CheckObjCString - Checks that the argument to the builtin
1319/// CFString constructor is correct
1320/// Note: It might also make sense to do the UTF-16 conversion here (would
1321/// simplify the backend).
1322bool Sema::CheckObjCString(Expr *Arg) {
1323  Arg = Arg->IgnoreParenCasts();
1324  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1325
1326  if (!Literal || !Literal->isAscii()) {
1327    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1328      << Arg->getSourceRange();
1329    return true;
1330  }
1331
1332  if (Literal->containsNonAsciiOrNull()) {
1333    StringRef String = Literal->getString();
1334    unsigned NumBytes = String.size();
1335    SmallVector<UTF16, 128> ToBuf(NumBytes);
1336    const UTF8 *FromPtr = (const UTF8 *)String.data();
1337    UTF16 *ToPtr = &ToBuf[0];
1338
1339    ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1340                                                 &ToPtr, ToPtr + NumBytes,
1341                                                 strictConversion);
1342    // Check for conversion failure.
1343    if (Result != conversionOK)
1344      Diag(Arg->getLocStart(),
1345           diag::warn_cfstring_truncated) << Arg->getSourceRange();
1346  }
1347  return false;
1348}
1349
1350/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1351/// Emit an error and return true on failure, return false on success.
1352bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1353  Expr *Fn = TheCall->getCallee();
1354  if (TheCall->getNumArgs() > 2) {
1355    Diag(TheCall->getArg(2)->getLocStart(),
1356         diag::err_typecheck_call_too_many_args)
1357      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1358      << Fn->getSourceRange()
1359      << SourceRange(TheCall->getArg(2)->getLocStart(),
1360                     (*(TheCall->arg_end()-1))->getLocEnd());
1361    return true;
1362  }
1363
1364  if (TheCall->getNumArgs() < 2) {
1365    return Diag(TheCall->getLocEnd(),
1366      diag::err_typecheck_call_too_few_args_at_least)
1367      << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1368  }
1369
1370  // Type-check the first argument normally.
1371  if (checkBuiltinArgument(*this, TheCall, 0))
1372    return true;
1373
1374  // Determine whether the current function is variadic or not.
1375  BlockScopeInfo *CurBlock = getCurBlock();
1376  bool isVariadic;
1377  if (CurBlock)
1378    isVariadic = CurBlock->TheDecl->isVariadic();
1379  else if (FunctionDecl *FD = getCurFunctionDecl())
1380    isVariadic = FD->isVariadic();
1381  else
1382    isVariadic = getCurMethodDecl()->isVariadic();
1383
1384  if (!isVariadic) {
1385    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1386    return true;
1387  }
1388
1389  // Verify that the second argument to the builtin is the last argument of the
1390  // current function or method.
1391  bool SecondArgIsLastNamedArgument = false;
1392  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1393
1394  // These are valid if SecondArgIsLastNamedArgument is false after the next
1395  // block.
1396  QualType Type;
1397  SourceLocation ParamLoc;
1398
1399  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1400    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1401      // FIXME: This isn't correct for methods (results in bogus warning).
1402      // Get the last formal in the current function.
1403      const ParmVarDecl *LastArg;
1404      if (CurBlock)
1405        LastArg = *(CurBlock->TheDecl->param_end()-1);
1406      else if (FunctionDecl *FD = getCurFunctionDecl())
1407        LastArg = *(FD->param_end()-1);
1408      else
1409        LastArg = *(getCurMethodDecl()->param_end()-1);
1410      SecondArgIsLastNamedArgument = PV == LastArg;
1411
1412      Type = PV->getType();
1413      ParamLoc = PV->getLocation();
1414    }
1415  }
1416
1417  if (!SecondArgIsLastNamedArgument)
1418    Diag(TheCall->getArg(1)->getLocStart(),
1419         diag::warn_second_parameter_of_va_start_not_last_named_argument);
1420  else if (Type->isReferenceType()) {
1421    Diag(Arg->getLocStart(),
1422         diag::warn_va_start_of_reference_type_is_undefined);
1423    Diag(ParamLoc, diag::note_parameter_type) << Type;
1424  }
1425
1426  return false;
1427}
1428
1429/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1430/// friends.  This is declared to take (...), so we have to check everything.
1431bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1432  if (TheCall->getNumArgs() < 2)
1433    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1434      << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1435  if (TheCall->getNumArgs() > 2)
1436    return Diag(TheCall->getArg(2)->getLocStart(),
1437                diag::err_typecheck_call_too_many_args)
1438      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1439      << SourceRange(TheCall->getArg(2)->getLocStart(),
1440                     (*(TheCall->arg_end()-1))->getLocEnd());
1441
1442  ExprResult OrigArg0 = TheCall->getArg(0);
1443  ExprResult OrigArg1 = TheCall->getArg(1);
1444
1445  // Do standard promotions between the two arguments, returning their common
1446  // type.
1447  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1448  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1449    return true;
1450
1451  // Make sure any conversions are pushed back into the call; this is
1452  // type safe since unordered compare builtins are declared as "_Bool
1453  // foo(...)".
1454  TheCall->setArg(0, OrigArg0.get());
1455  TheCall->setArg(1, OrigArg1.get());
1456
1457  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1458    return false;
1459
1460  // If the common type isn't a real floating type, then the arguments were
1461  // invalid for this operation.
1462  if (Res.isNull() || !Res->isRealFloatingType())
1463    return Diag(OrigArg0.get()->getLocStart(),
1464                diag::err_typecheck_call_invalid_ordered_compare)
1465      << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1466      << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1467
1468  return false;
1469}
1470
1471/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1472/// __builtin_isnan and friends.  This is declared to take (...), so we have
1473/// to check everything. We expect the last argument to be a floating point
1474/// value.
1475bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1476  if (TheCall->getNumArgs() < NumArgs)
1477    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1478      << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1479  if (TheCall->getNumArgs() > NumArgs)
1480    return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1481                diag::err_typecheck_call_too_many_args)
1482      << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1483      << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1484                     (*(TheCall->arg_end()-1))->getLocEnd());
1485
1486  Expr *OrigArg = TheCall->getArg(NumArgs-1);
1487
1488  if (OrigArg->isTypeDependent())
1489    return false;
1490
1491  // This operation requires a non-_Complex floating-point number.
1492  if (!OrigArg->getType()->isRealFloatingType())
1493    return Diag(OrigArg->getLocStart(),
1494                diag::err_typecheck_call_invalid_unary_fp)
1495      << OrigArg->getType() << OrigArg->getSourceRange();
1496
1497  // If this is an implicit conversion from float -> double, remove it.
1498  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1499    Expr *CastArg = Cast->getSubExpr();
1500    if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1501      assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1502             "promotion from float to double is the only expected cast here");
1503      Cast->setSubExpr(0);
1504      TheCall->setArg(NumArgs-1, CastArg);
1505    }
1506  }
1507
1508  return false;
1509}
1510
1511/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1512// This is declared to take (...), so we have to check everything.
1513ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1514  if (TheCall->getNumArgs() < 2)
1515    return ExprError(Diag(TheCall->getLocEnd(),
1516                          diag::err_typecheck_call_too_few_args_at_least)
1517      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1518      << TheCall->getSourceRange());
1519
1520  // Determine which of the following types of shufflevector we're checking:
1521  // 1) unary, vector mask: (lhs, mask)
1522  // 2) binary, vector mask: (lhs, rhs, mask)
1523  // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1524  QualType resType = TheCall->getArg(0)->getType();
1525  unsigned numElements = 0;
1526
1527  if (!TheCall->getArg(0)->isTypeDependent() &&
1528      !TheCall->getArg(1)->isTypeDependent()) {
1529    QualType LHSType = TheCall->getArg(0)->getType();
1530    QualType RHSType = TheCall->getArg(1)->getType();
1531
1532    if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
1533      Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
1534        << SourceRange(TheCall->getArg(0)->getLocStart(),
1535                       TheCall->getArg(1)->getLocEnd());
1536      return ExprError();
1537    }
1538
1539    numElements = LHSType->getAs<VectorType>()->getNumElements();
1540    unsigned numResElements = TheCall->getNumArgs() - 2;
1541
1542    // Check to see if we have a call with 2 vector arguments, the unary shuffle
1543    // with mask.  If so, verify that RHS is an integer vector type with the
1544    // same number of elts as lhs.
1545    if (TheCall->getNumArgs() == 2) {
1546      if (!RHSType->hasIntegerRepresentation() ||
1547          RHSType->getAs<VectorType>()->getNumElements() != numElements)
1548        Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1549          << SourceRange(TheCall->getArg(1)->getLocStart(),
1550                         TheCall->getArg(1)->getLocEnd());
1551      numResElements = numElements;
1552    }
1553    else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1554      Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1555        << SourceRange(TheCall->getArg(0)->getLocStart(),
1556                       TheCall->getArg(1)->getLocEnd());
1557      return ExprError();
1558    } else if (numElements != numResElements) {
1559      QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1560      resType = Context.getVectorType(eltType, numResElements,
1561                                      VectorType::GenericVector);
1562    }
1563  }
1564
1565  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1566    if (TheCall->getArg(i)->isTypeDependent() ||
1567        TheCall->getArg(i)->isValueDependent())
1568      continue;
1569
1570    llvm::APSInt Result(32);
1571    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1572      return ExprError(Diag(TheCall->getLocStart(),
1573                  diag::err_shufflevector_nonconstant_argument)
1574                << TheCall->getArg(i)->getSourceRange());
1575
1576    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1577      return ExprError(Diag(TheCall->getLocStart(),
1578                  diag::err_shufflevector_argument_too_large)
1579               << TheCall->getArg(i)->getSourceRange());
1580  }
1581
1582  SmallVector<Expr*, 32> exprs;
1583
1584  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1585    exprs.push_back(TheCall->getArg(i));
1586    TheCall->setArg(i, 0);
1587  }
1588
1589  return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
1590                                            TheCall->getCallee()->getLocStart(),
1591                                            TheCall->getRParenLoc()));
1592}
1593
1594/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1595// This is declared to take (const void*, ...) and can take two
1596// optional constant int args.
1597bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1598  unsigned NumArgs = TheCall->getNumArgs();
1599
1600  if (NumArgs > 3)
1601    return Diag(TheCall->getLocEnd(),
1602             diag::err_typecheck_call_too_many_args_at_most)
1603             << 0 /*function call*/ << 3 << NumArgs
1604             << TheCall->getSourceRange();
1605
1606  // Argument 0 is checked for us and the remaining arguments must be
1607  // constant integers.
1608  for (unsigned i = 1; i != NumArgs; ++i) {
1609    Expr *Arg = TheCall->getArg(i);
1610
1611    // We can't check the value of a dependent argument.
1612    if (Arg->isTypeDependent() || Arg->isValueDependent())
1613      continue;
1614
1615    llvm::APSInt Result;
1616    if (SemaBuiltinConstantArg(TheCall, i, Result))
1617      return true;
1618
1619    // FIXME: gcc issues a warning and rewrites these to 0. These
1620    // seems especially odd for the third argument since the default
1621    // is 3.
1622    if (i == 1) {
1623      if (Result.getLimitedValue() > 1)
1624        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1625             << "0" << "1" << Arg->getSourceRange();
1626    } else {
1627      if (Result.getLimitedValue() > 3)
1628        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1629            << "0" << "3" << Arg->getSourceRange();
1630    }
1631  }
1632
1633  return false;
1634}
1635
1636/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1637/// TheCall is a constant expression.
1638bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1639                                  llvm::APSInt &Result) {
1640  Expr *Arg = TheCall->getArg(ArgNum);
1641  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1642  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1643
1644  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1645
1646  if (!Arg->isIntegerConstantExpr(Result, Context))
1647    return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1648                << FDecl->getDeclName() <<  Arg->getSourceRange();
1649
1650  return false;
1651}
1652
1653/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1654/// int type). This simply type checks that type is one of the defined
1655/// constants (0-3).
1656// For compatibility check 0-3, llvm only handles 0 and 2.
1657bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1658  llvm::APSInt Result;
1659
1660  // We can't check the value of a dependent argument.
1661  if (TheCall->getArg(1)->isTypeDependent() ||
1662      TheCall->getArg(1)->isValueDependent())
1663    return false;
1664
1665  // Check constant-ness first.
1666  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1667    return true;
1668
1669  Expr *Arg = TheCall->getArg(1);
1670  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1671    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1672             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1673  }
1674
1675  return false;
1676}
1677
1678/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1679/// This checks that val is a constant 1.
1680bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1681  Expr *Arg = TheCall->getArg(1);
1682  llvm::APSInt Result;
1683
1684  // TODO: This is less than ideal. Overload this to take a value.
1685  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1686    return true;
1687
1688  if (Result != 1)
1689    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1690             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1691
1692  return false;
1693}
1694
1695// Determine if an expression is a string literal or constant string.
1696// If this function returns false on the arguments to a function expecting a
1697// format string, we will usually need to emit a warning.
1698// True string literals are then checked by CheckFormatString.
1699Sema::StringLiteralCheckType
1700Sema::checkFormatStringExpr(const Expr *E, ArrayRef<const Expr *> Args,
1701                            bool HasVAListArg,
1702                            unsigned format_idx, unsigned firstDataArg,
1703                            FormatStringType Type, VariadicCallType CallType,
1704                            bool inFunctionCall) {
1705 tryAgain:
1706  if (E->isTypeDependent() || E->isValueDependent())
1707    return SLCT_NotALiteral;
1708
1709  E = E->IgnoreParenCasts();
1710
1711  if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1712    // Technically -Wformat-nonliteral does not warn about this case.
1713    // The behavior of printf and friends in this case is implementation
1714    // dependent.  Ideally if the format string cannot be null then
1715    // it should have a 'nonnull' attribute in the function prototype.
1716    return SLCT_CheckedLiteral;
1717
1718  switch (E->getStmtClass()) {
1719  case Stmt::BinaryConditionalOperatorClass:
1720  case Stmt::ConditionalOperatorClass: {
1721    // The expression is a literal if both sub-expressions were, and it was
1722    // completely checked only if both sub-expressions were checked.
1723    const AbstractConditionalOperator *C =
1724        cast<AbstractConditionalOperator>(E);
1725    StringLiteralCheckType Left =
1726        checkFormatStringExpr(C->getTrueExpr(), Args,
1727                              HasVAListArg, format_idx, firstDataArg,
1728                              Type, CallType, inFunctionCall);
1729    if (Left == SLCT_NotALiteral)
1730      return SLCT_NotALiteral;
1731    StringLiteralCheckType Right =
1732        checkFormatStringExpr(C->getFalseExpr(), Args,
1733                              HasVAListArg, format_idx, firstDataArg,
1734                              Type, CallType, inFunctionCall);
1735    return Left < Right ? Left : Right;
1736  }
1737
1738  case Stmt::ImplicitCastExprClass: {
1739    E = cast<ImplicitCastExpr>(E)->getSubExpr();
1740    goto tryAgain;
1741  }
1742
1743  case Stmt::OpaqueValueExprClass:
1744    if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1745      E = src;
1746      goto tryAgain;
1747    }
1748    return SLCT_NotALiteral;
1749
1750  case Stmt::PredefinedExprClass:
1751    // While __func__, etc., are technically not string literals, they
1752    // cannot contain format specifiers and thus are not a security
1753    // liability.
1754    return SLCT_UncheckedLiteral;
1755
1756  case Stmt::DeclRefExprClass: {
1757    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1758
1759    // As an exception, do not flag errors for variables binding to
1760    // const string literals.
1761    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1762      bool isConstant = false;
1763      QualType T = DR->getType();
1764
1765      if (const ArrayType *AT = Context.getAsArrayType(T)) {
1766        isConstant = AT->getElementType().isConstant(Context);
1767      } else if (const PointerType *PT = T->getAs<PointerType>()) {
1768        isConstant = T.isConstant(Context) &&
1769                     PT->getPointeeType().isConstant(Context);
1770      } else if (T->isObjCObjectPointerType()) {
1771        // In ObjC, there is usually no "const ObjectPointer" type,
1772        // so don't check if the pointee type is constant.
1773        isConstant = T.isConstant(Context);
1774      }
1775
1776      if (isConstant) {
1777        if (const Expr *Init = VD->getAnyInitializer()) {
1778          // Look through initializers like const char c[] = { "foo" }
1779          if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1780            if (InitList->isStringLiteralInit())
1781              Init = InitList->getInit(0)->IgnoreParenImpCasts();
1782          }
1783          return checkFormatStringExpr(Init, Args,
1784                                       HasVAListArg, format_idx,
1785                                       firstDataArg, Type, CallType,
1786                                       /*inFunctionCall*/false);
1787        }
1788      }
1789
1790      // For vprintf* functions (i.e., HasVAListArg==true), we add a
1791      // special check to see if the format string is a function parameter
1792      // of the function calling the printf function.  If the function
1793      // has an attribute indicating it is a printf-like function, then we
1794      // should suppress warnings concerning non-literals being used in a call
1795      // to a vprintf function.  For example:
1796      //
1797      // void
1798      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1799      //      va_list ap;
1800      //      va_start(ap, fmt);
1801      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
1802      //      ...
1803      //
1804      if (HasVAListArg) {
1805        if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1806          if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1807            int PVIndex = PV->getFunctionScopeIndex() + 1;
1808            for (specific_attr_iterator<FormatAttr>
1809                 i = ND->specific_attr_begin<FormatAttr>(),
1810                 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1811              FormatAttr *PVFormat = *i;
1812              // adjust for implicit parameter
1813              if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1814                if (MD->isInstance())
1815                  ++PVIndex;
1816              // We also check if the formats are compatible.
1817              // We can't pass a 'scanf' string to a 'printf' function.
1818              if (PVIndex == PVFormat->getFormatIdx() &&
1819                  Type == GetFormatStringType(PVFormat))
1820                return SLCT_UncheckedLiteral;
1821            }
1822          }
1823        }
1824      }
1825    }
1826
1827    return SLCT_NotALiteral;
1828  }
1829
1830  case Stmt::CallExprClass:
1831  case Stmt::CXXMemberCallExprClass: {
1832    const CallExpr *CE = cast<CallExpr>(E);
1833    if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1834      if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1835        unsigned ArgIndex = FA->getFormatIdx();
1836        if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1837          if (MD->isInstance())
1838            --ArgIndex;
1839        const Expr *Arg = CE->getArg(ArgIndex - 1);
1840
1841        return checkFormatStringExpr(Arg, Args,
1842                                     HasVAListArg, format_idx, firstDataArg,
1843                                     Type, CallType, inFunctionCall);
1844      } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1845        unsigned BuiltinID = FD->getBuiltinID();
1846        if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1847            BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1848          const Expr *Arg = CE->getArg(0);
1849          return checkFormatStringExpr(Arg, Args,
1850                                       HasVAListArg, format_idx,
1851                                       firstDataArg, Type, CallType,
1852                                       inFunctionCall);
1853        }
1854      }
1855    }
1856
1857    return SLCT_NotALiteral;
1858  }
1859  case Stmt::ObjCStringLiteralClass:
1860  case Stmt::StringLiteralClass: {
1861    const StringLiteral *StrE = NULL;
1862
1863    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1864      StrE = ObjCFExpr->getString();
1865    else
1866      StrE = cast<StringLiteral>(E);
1867
1868    if (StrE) {
1869      CheckFormatString(StrE, E, Args, HasVAListArg, format_idx,
1870                        firstDataArg, Type, inFunctionCall, CallType);
1871      return SLCT_CheckedLiteral;
1872    }
1873
1874    return SLCT_NotALiteral;
1875  }
1876
1877  default:
1878    return SLCT_NotALiteral;
1879  }
1880}
1881
1882void
1883Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1884                            const Expr * const *ExprArgs,
1885                            SourceLocation CallSiteLoc) {
1886  for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1887                                  e = NonNull->args_end();
1888       i != e; ++i) {
1889    const Expr *ArgExpr = ExprArgs[*i];
1890
1891    // As a special case, transparent unions initialized with zero are
1892    // considered null for the purposes of the nonnull attribute.
1893    if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
1894      if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1895        if (const CompoundLiteralExpr *CLE =
1896            dyn_cast<CompoundLiteralExpr>(ArgExpr))
1897          if (const InitListExpr *ILE =
1898              dyn_cast<InitListExpr>(CLE->getInitializer()))
1899            ArgExpr = ILE->getInit(0);
1900    }
1901
1902    bool Result;
1903    if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
1904      Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1905  }
1906}
1907
1908Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1909  return llvm::StringSwitch<FormatStringType>(Format->getType())
1910  .Case("scanf", FST_Scanf)
1911  .Cases("printf", "printf0", FST_Printf)
1912  .Cases("NSString", "CFString", FST_NSString)
1913  .Case("strftime", FST_Strftime)
1914  .Case("strfmon", FST_Strfmon)
1915  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1916  .Default(FST_Unknown);
1917}
1918
1919/// CheckFormatArguments - Check calls to printf and scanf (and similar
1920/// functions) for correct use of format strings.
1921/// Returns true if a format string has been fully checked.
1922bool Sema::CheckFormatArguments(const FormatAttr *Format,
1923                                ArrayRef<const Expr *> Args,
1924                                bool IsCXXMember,
1925                                VariadicCallType CallType,
1926                                SourceLocation Loc, SourceRange Range) {
1927  FormatStringInfo FSI;
1928  if (getFormatStringInfo(Format, IsCXXMember, &FSI))
1929    return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
1930                                FSI.FirstDataArg, GetFormatStringType(Format),
1931                                CallType, Loc, Range);
1932  return false;
1933}
1934
1935bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
1936                                bool HasVAListArg, unsigned format_idx,
1937                                unsigned firstDataArg, FormatStringType Type,
1938                                VariadicCallType CallType,
1939                                SourceLocation Loc, SourceRange Range) {
1940  // CHECK: printf/scanf-like function is called with no format string.
1941  if (format_idx >= Args.size()) {
1942    Diag(Loc, diag::warn_missing_format_string) << Range;
1943    return false;
1944  }
1945
1946  const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
1947
1948  // CHECK: format string is not a string literal.
1949  //
1950  // Dynamically generated format strings are difficult to
1951  // automatically vet at compile time.  Requiring that format strings
1952  // are string literals: (1) permits the checking of format strings by
1953  // the compiler and thereby (2) can practically remove the source of
1954  // many format string exploits.
1955
1956  // Format string can be either ObjC string (e.g. @"%d") or
1957  // C string (e.g. "%d")
1958  // ObjC string uses the same format specifiers as C string, so we can use
1959  // the same format string checking logic for both ObjC and C strings.
1960  StringLiteralCheckType CT =
1961      checkFormatStringExpr(OrigFormatExpr, Args, HasVAListArg,
1962                            format_idx, firstDataArg, Type, CallType);
1963  if (CT != SLCT_NotALiteral)
1964    // Literal format string found, check done!
1965    return CT == SLCT_CheckedLiteral;
1966
1967  // Strftime is particular as it always uses a single 'time' argument,
1968  // so it is safe to pass a non-literal string.
1969  if (Type == FST_Strftime)
1970    return false;
1971
1972  // Do not emit diag when the string param is a macro expansion and the
1973  // format is either NSString or CFString. This is a hack to prevent
1974  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1975  // which are usually used in place of NS and CF string literals.
1976  if (Type == FST_NSString &&
1977      SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
1978    return false;
1979
1980  // If there are no arguments specified, warn with -Wformat-security, otherwise
1981  // warn only with -Wformat-nonliteral.
1982  if (Args.size() == firstDataArg)
1983    Diag(Args[format_idx]->getLocStart(),
1984         diag::warn_format_nonliteral_noargs)
1985      << OrigFormatExpr->getSourceRange();
1986  else
1987    Diag(Args[format_idx]->getLocStart(),
1988         diag::warn_format_nonliteral)
1989           << OrigFormatExpr->getSourceRange();
1990  return false;
1991}
1992
1993namespace {
1994class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1995protected:
1996  Sema &S;
1997  const StringLiteral *FExpr;
1998  const Expr *OrigFormatExpr;
1999  const unsigned FirstDataArg;
2000  const unsigned NumDataArgs;
2001  const char *Beg; // Start of format string.
2002  const bool HasVAListArg;
2003  ArrayRef<const Expr *> Args;
2004  unsigned FormatIdx;
2005  llvm::BitVector CoveredArgs;
2006  bool usesPositionalArgs;
2007  bool atFirstArg;
2008  bool inFunctionCall;
2009  Sema::VariadicCallType CallType;
2010public:
2011  CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2012                     const Expr *origFormatExpr, unsigned firstDataArg,
2013                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
2014                     ArrayRef<const Expr *> Args,
2015                     unsigned formatIdx, bool inFunctionCall,
2016                     Sema::VariadicCallType callType)
2017    : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2018      FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2019      Beg(beg), HasVAListArg(hasVAListArg),
2020      Args(Args), FormatIdx(formatIdx),
2021      usesPositionalArgs(false), atFirstArg(true),
2022      inFunctionCall(inFunctionCall), CallType(callType) {
2023        CoveredArgs.resize(numDataArgs);
2024        CoveredArgs.reset();
2025      }
2026
2027  void DoneProcessing();
2028
2029  void HandleIncompleteSpecifier(const char *startSpecifier,
2030                                 unsigned specifierLen);
2031
2032  void HandleInvalidLengthModifier(
2033      const analyze_format_string::FormatSpecifier &FS,
2034      const analyze_format_string::ConversionSpecifier &CS,
2035      const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
2036
2037  void HandleNonStandardLengthModifier(
2038      const analyze_format_string::FormatSpecifier &FS,
2039      const char *startSpecifier, unsigned specifierLen);
2040
2041  void HandleNonStandardConversionSpecifier(
2042      const analyze_format_string::ConversionSpecifier &CS,
2043      const char *startSpecifier, unsigned specifierLen);
2044
2045  virtual void HandlePosition(const char *startPos, unsigned posLen);
2046
2047  virtual void HandleInvalidPosition(const char *startSpecifier,
2048                                     unsigned specifierLen,
2049                                     analyze_format_string::PositionContext p);
2050
2051  virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2052
2053  void HandleNullChar(const char *nullCharacter);
2054
2055  template <typename Range>
2056  static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2057                                   const Expr *ArgumentExpr,
2058                                   PartialDiagnostic PDiag,
2059                                   SourceLocation StringLoc,
2060                                   bool IsStringLocation, Range StringRange,
2061                                   ArrayRef<FixItHint> Fixit = None);
2062
2063protected:
2064  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2065                                        const char *startSpec,
2066                                        unsigned specifierLen,
2067                                        const char *csStart, unsigned csLen);
2068
2069  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2070                                         const char *startSpec,
2071                                         unsigned specifierLen);
2072
2073  SourceRange getFormatStringRange();
2074  CharSourceRange getSpecifierRange(const char *startSpecifier,
2075                                    unsigned specifierLen);
2076  SourceLocation getLocationOfByte(const char *x);
2077
2078  const Expr *getDataArg(unsigned i) const;
2079
2080  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2081                    const analyze_format_string::ConversionSpecifier &CS,
2082                    const char *startSpecifier, unsigned specifierLen,
2083                    unsigned argIndex);
2084
2085  template <typename Range>
2086  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2087                            bool IsStringLocation, Range StringRange,
2088                            ArrayRef<FixItHint> Fixit = None);
2089
2090  void CheckPositionalAndNonpositionalArgs(
2091      const analyze_format_string::FormatSpecifier *FS);
2092};
2093}
2094
2095SourceRange CheckFormatHandler::getFormatStringRange() {
2096  return OrigFormatExpr->getSourceRange();
2097}
2098
2099CharSourceRange CheckFormatHandler::
2100getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2101  SourceLocation Start = getLocationOfByte(startSpecifier);
2102  SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
2103
2104  // Advance the end SourceLocation by one due to half-open ranges.
2105  End = End.getLocWithOffset(1);
2106
2107  return CharSourceRange::getCharRange(Start, End);
2108}
2109
2110SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2111  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2112}
2113
2114void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2115                                                   unsigned specifierLen){
2116  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2117                       getLocationOfByte(startSpecifier),
2118                       /*IsStringLocation*/true,
2119                       getSpecifierRange(startSpecifier, specifierLen));
2120}
2121
2122void CheckFormatHandler::HandleInvalidLengthModifier(
2123    const analyze_format_string::FormatSpecifier &FS,
2124    const analyze_format_string::ConversionSpecifier &CS,
2125    const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2126  using namespace analyze_format_string;
2127
2128  const LengthModifier &LM = FS.getLengthModifier();
2129  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2130
2131  // See if we know how to fix this length modifier.
2132  Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2133  if (FixedLM) {
2134    EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2135                         getLocationOfByte(LM.getStart()),
2136                         /*IsStringLocation*/true,
2137                         getSpecifierRange(startSpecifier, specifierLen));
2138
2139    S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2140      << FixedLM->toString()
2141      << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2142
2143  } else {
2144    FixItHint Hint;
2145    if (DiagID == diag::warn_format_nonsensical_length)
2146      Hint = FixItHint::CreateRemoval(LMRange);
2147
2148    EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2149                         getLocationOfByte(LM.getStart()),
2150                         /*IsStringLocation*/true,
2151                         getSpecifierRange(startSpecifier, specifierLen),
2152                         Hint);
2153  }
2154}
2155
2156void CheckFormatHandler::HandleNonStandardLengthModifier(
2157    const analyze_format_string::FormatSpecifier &FS,
2158    const char *startSpecifier, unsigned specifierLen) {
2159  using namespace analyze_format_string;
2160
2161  const LengthModifier &LM = FS.getLengthModifier();
2162  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2163
2164  // See if we know how to fix this length modifier.
2165  Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2166  if (FixedLM) {
2167    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2168                           << LM.toString() << 0,
2169                         getLocationOfByte(LM.getStart()),
2170                         /*IsStringLocation*/true,
2171                         getSpecifierRange(startSpecifier, specifierLen));
2172
2173    S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2174      << FixedLM->toString()
2175      << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2176
2177  } else {
2178    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2179                           << LM.toString() << 0,
2180                         getLocationOfByte(LM.getStart()),
2181                         /*IsStringLocation*/true,
2182                         getSpecifierRange(startSpecifier, specifierLen));
2183  }
2184}
2185
2186void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2187    const analyze_format_string::ConversionSpecifier &CS,
2188    const char *startSpecifier, unsigned specifierLen) {
2189  using namespace analyze_format_string;
2190
2191  // See if we know how to fix this conversion specifier.
2192  Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2193  if (FixedCS) {
2194    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2195                          << CS.toString() << /*conversion specifier*/1,
2196                         getLocationOfByte(CS.getStart()),
2197                         /*IsStringLocation*/true,
2198                         getSpecifierRange(startSpecifier, specifierLen));
2199
2200    CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2201    S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2202      << FixedCS->toString()
2203      << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2204  } else {
2205    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2206                          << CS.toString() << /*conversion specifier*/1,
2207                         getLocationOfByte(CS.getStart()),
2208                         /*IsStringLocation*/true,
2209                         getSpecifierRange(startSpecifier, specifierLen));
2210  }
2211}
2212
2213void CheckFormatHandler::HandlePosition(const char *startPos,
2214                                        unsigned posLen) {
2215  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2216                               getLocationOfByte(startPos),
2217                               /*IsStringLocation*/true,
2218                               getSpecifierRange(startPos, posLen));
2219}
2220
2221void
2222CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2223                                     analyze_format_string::PositionContext p) {
2224  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2225                         << (unsigned) p,
2226                       getLocationOfByte(startPos), /*IsStringLocation*/true,
2227                       getSpecifierRange(startPos, posLen));
2228}
2229
2230void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2231                                            unsigned posLen) {
2232  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2233                               getLocationOfByte(startPos),
2234                               /*IsStringLocation*/true,
2235                               getSpecifierRange(startPos, posLen));
2236}
2237
2238void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2239  if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2240    // The presence of a null character is likely an error.
2241    EmitFormatDiagnostic(
2242      S.PDiag(diag::warn_printf_format_string_contains_null_char),
2243      getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2244      getFormatStringRange());
2245  }
2246}
2247
2248// Note that this may return NULL if there was an error parsing or building
2249// one of the argument expressions.
2250const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2251  return Args[FirstDataArg + i];
2252}
2253
2254void CheckFormatHandler::DoneProcessing() {
2255    // Does the number of data arguments exceed the number of
2256    // format conversions in the format string?
2257  if (!HasVAListArg) {
2258      // Find any arguments that weren't covered.
2259    CoveredArgs.flip();
2260    signed notCoveredArg = CoveredArgs.find_first();
2261    if (notCoveredArg >= 0) {
2262      assert((unsigned)notCoveredArg < NumDataArgs);
2263      if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2264        SourceLocation Loc = E->getLocStart();
2265        if (!S.getSourceManager().isInSystemMacro(Loc)) {
2266          EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2267                               Loc, /*IsStringLocation*/false,
2268                               getFormatStringRange());
2269        }
2270      }
2271    }
2272  }
2273}
2274
2275bool
2276CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2277                                                     SourceLocation Loc,
2278                                                     const char *startSpec,
2279                                                     unsigned specifierLen,
2280                                                     const char *csStart,
2281                                                     unsigned csLen) {
2282
2283  bool keepGoing = true;
2284  if (argIndex < NumDataArgs) {
2285    // Consider the argument coverered, even though the specifier doesn't
2286    // make sense.
2287    CoveredArgs.set(argIndex);
2288  }
2289  else {
2290    // If argIndex exceeds the number of data arguments we
2291    // don't issue a warning because that is just a cascade of warnings (and
2292    // they may have intended '%%' anyway). We don't want to continue processing
2293    // the format string after this point, however, as we will like just get
2294    // gibberish when trying to match arguments.
2295    keepGoing = false;
2296  }
2297
2298  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2299                         << StringRef(csStart, csLen),
2300                       Loc, /*IsStringLocation*/true,
2301                       getSpecifierRange(startSpec, specifierLen));
2302
2303  return keepGoing;
2304}
2305
2306void
2307CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2308                                                      const char *startSpec,
2309                                                      unsigned specifierLen) {
2310  EmitFormatDiagnostic(
2311    S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2312    Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2313}
2314
2315bool
2316CheckFormatHandler::CheckNumArgs(
2317  const analyze_format_string::FormatSpecifier &FS,
2318  const analyze_format_string::ConversionSpecifier &CS,
2319  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2320
2321  if (argIndex >= NumDataArgs) {
2322    PartialDiagnostic PDiag = FS.usesPositionalArg()
2323      ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2324           << (argIndex+1) << NumDataArgs)
2325      : S.PDiag(diag::warn_printf_insufficient_data_args);
2326    EmitFormatDiagnostic(
2327      PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2328      getSpecifierRange(startSpecifier, specifierLen));
2329    return false;
2330  }
2331  return true;
2332}
2333
2334template<typename Range>
2335void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2336                                              SourceLocation Loc,
2337                                              bool IsStringLocation,
2338                                              Range StringRange,
2339                                              ArrayRef<FixItHint> FixIt) {
2340  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
2341                       Loc, IsStringLocation, StringRange, FixIt);
2342}
2343
2344/// \brief If the format string is not within the funcion call, emit a note
2345/// so that the function call and string are in diagnostic messages.
2346///
2347/// \param InFunctionCall if true, the format string is within the function
2348/// call and only one diagnostic message will be produced.  Otherwise, an
2349/// extra note will be emitted pointing to location of the format string.
2350///
2351/// \param ArgumentExpr the expression that is passed as the format string
2352/// argument in the function call.  Used for getting locations when two
2353/// diagnostics are emitted.
2354///
2355/// \param PDiag the callee should already have provided any strings for the
2356/// diagnostic message.  This function only adds locations and fixits
2357/// to diagnostics.
2358///
2359/// \param Loc primary location for diagnostic.  If two diagnostics are
2360/// required, one will be at Loc and a new SourceLocation will be created for
2361/// the other one.
2362///
2363/// \param IsStringLocation if true, Loc points to the format string should be
2364/// used for the note.  Otherwise, Loc points to the argument list and will
2365/// be used with PDiag.
2366///
2367/// \param StringRange some or all of the string to highlight.  This is
2368/// templated so it can accept either a CharSourceRange or a SourceRange.
2369///
2370/// \param FixIt optional fix it hint for the format string.
2371template<typename Range>
2372void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2373                                              const Expr *ArgumentExpr,
2374                                              PartialDiagnostic PDiag,
2375                                              SourceLocation Loc,
2376                                              bool IsStringLocation,
2377                                              Range StringRange,
2378                                              ArrayRef<FixItHint> FixIt) {
2379  if (InFunctionCall) {
2380    const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2381    D << StringRange;
2382    for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2383         I != E; ++I) {
2384      D << *I;
2385    }
2386  } else {
2387    S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2388      << ArgumentExpr->getSourceRange();
2389
2390    const Sema::SemaDiagnosticBuilder &Note =
2391      S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2392             diag::note_format_string_defined);
2393
2394    Note << StringRange;
2395    for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2396         I != E; ++I) {
2397      Note << *I;
2398    }
2399  }
2400}
2401
2402//===--- CHECK: Printf format string checking ------------------------------===//
2403
2404namespace {
2405class CheckPrintfHandler : public CheckFormatHandler {
2406  bool ObjCContext;
2407public:
2408  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2409                     const Expr *origFormatExpr, unsigned firstDataArg,
2410                     unsigned numDataArgs, bool isObjC,
2411                     const char *beg, bool hasVAListArg,
2412                     ArrayRef<const Expr *> Args,
2413                     unsigned formatIdx, bool inFunctionCall,
2414                     Sema::VariadicCallType CallType)
2415  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2416                       numDataArgs, beg, hasVAListArg, Args,
2417                       formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2418  {}
2419
2420
2421  bool HandleInvalidPrintfConversionSpecifier(
2422                                      const analyze_printf::PrintfSpecifier &FS,
2423                                      const char *startSpecifier,
2424                                      unsigned specifierLen);
2425
2426  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2427                             const char *startSpecifier,
2428                             unsigned specifierLen);
2429  bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2430                       const char *StartSpecifier,
2431                       unsigned SpecifierLen,
2432                       const Expr *E);
2433
2434  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2435                    const char *startSpecifier, unsigned specifierLen);
2436  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2437                           const analyze_printf::OptionalAmount &Amt,
2438                           unsigned type,
2439                           const char *startSpecifier, unsigned specifierLen);
2440  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2441                  const analyze_printf::OptionalFlag &flag,
2442                  const char *startSpecifier, unsigned specifierLen);
2443  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2444                         const analyze_printf::OptionalFlag &ignoredFlag,
2445                         const analyze_printf::OptionalFlag &flag,
2446                         const char *startSpecifier, unsigned specifierLen);
2447  bool checkForCStrMembers(const analyze_printf::ArgType &AT,
2448                           const Expr *E, const CharSourceRange &CSR);
2449
2450};
2451}
2452
2453bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2454                                      const analyze_printf::PrintfSpecifier &FS,
2455                                      const char *startSpecifier,
2456                                      unsigned specifierLen) {
2457  const analyze_printf::PrintfConversionSpecifier &CS =
2458    FS.getConversionSpecifier();
2459
2460  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2461                                          getLocationOfByte(CS.getStart()),
2462                                          startSpecifier, specifierLen,
2463                                          CS.getStart(), CS.getLength());
2464}
2465
2466bool CheckPrintfHandler::HandleAmount(
2467                               const analyze_format_string::OptionalAmount &Amt,
2468                               unsigned k, const char *startSpecifier,
2469                               unsigned specifierLen) {
2470
2471  if (Amt.hasDataArgument()) {
2472    if (!HasVAListArg) {
2473      unsigned argIndex = Amt.getArgIndex();
2474      if (argIndex >= NumDataArgs) {
2475        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2476                               << k,
2477                             getLocationOfByte(Amt.getStart()),
2478                             /*IsStringLocation*/true,
2479                             getSpecifierRange(startSpecifier, specifierLen));
2480        // Don't do any more checking.  We will just emit
2481        // spurious errors.
2482        return false;
2483      }
2484
2485      // Type check the data argument.  It should be an 'int'.
2486      // Although not in conformance with C99, we also allow the argument to be
2487      // an 'unsigned int' as that is a reasonably safe case.  GCC also
2488      // doesn't emit a warning for that case.
2489      CoveredArgs.set(argIndex);
2490      const Expr *Arg = getDataArg(argIndex);
2491      if (!Arg)
2492        return false;
2493
2494      QualType T = Arg->getType();
2495
2496      const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2497      assert(AT.isValid());
2498
2499      if (!AT.matchesType(S.Context, T)) {
2500        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2501                               << k << AT.getRepresentativeTypeName(S.Context)
2502                               << T << Arg->getSourceRange(),
2503                             getLocationOfByte(Amt.getStart()),
2504                             /*IsStringLocation*/true,
2505                             getSpecifierRange(startSpecifier, specifierLen));
2506        // Don't do any more checking.  We will just emit
2507        // spurious errors.
2508        return false;
2509      }
2510    }
2511  }
2512  return true;
2513}
2514
2515void CheckPrintfHandler::HandleInvalidAmount(
2516                                      const analyze_printf::PrintfSpecifier &FS,
2517                                      const analyze_printf::OptionalAmount &Amt,
2518                                      unsigned type,
2519                                      const char *startSpecifier,
2520                                      unsigned specifierLen) {
2521  const analyze_printf::PrintfConversionSpecifier &CS =
2522    FS.getConversionSpecifier();
2523
2524  FixItHint fixit =
2525    Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2526      ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2527                                 Amt.getConstantLength()))
2528      : FixItHint();
2529
2530  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2531                         << type << CS.toString(),
2532                       getLocationOfByte(Amt.getStart()),
2533                       /*IsStringLocation*/true,
2534                       getSpecifierRange(startSpecifier, specifierLen),
2535                       fixit);
2536}
2537
2538void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2539                                    const analyze_printf::OptionalFlag &flag,
2540                                    const char *startSpecifier,
2541                                    unsigned specifierLen) {
2542  // Warn about pointless flag with a fixit removal.
2543  const analyze_printf::PrintfConversionSpecifier &CS =
2544    FS.getConversionSpecifier();
2545  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2546                         << flag.toString() << CS.toString(),
2547                       getLocationOfByte(flag.getPosition()),
2548                       /*IsStringLocation*/true,
2549                       getSpecifierRange(startSpecifier, specifierLen),
2550                       FixItHint::CreateRemoval(
2551                         getSpecifierRange(flag.getPosition(), 1)));
2552}
2553
2554void CheckPrintfHandler::HandleIgnoredFlag(
2555                                const analyze_printf::PrintfSpecifier &FS,
2556                                const analyze_printf::OptionalFlag &ignoredFlag,
2557                                const analyze_printf::OptionalFlag &flag,
2558                                const char *startSpecifier,
2559                                unsigned specifierLen) {
2560  // Warn about ignored flag with a fixit removal.
2561  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2562                         << ignoredFlag.toString() << flag.toString(),
2563                       getLocationOfByte(ignoredFlag.getPosition()),
2564                       /*IsStringLocation*/true,
2565                       getSpecifierRange(startSpecifier, specifierLen),
2566                       FixItHint::CreateRemoval(
2567                         getSpecifierRange(ignoredFlag.getPosition(), 1)));
2568}
2569
2570// Determines if the specified is a C++ class or struct containing
2571// a member with the specified name and kind (e.g. a CXXMethodDecl named
2572// "c_str()").
2573template<typename MemberKind>
2574static llvm::SmallPtrSet<MemberKind*, 1>
2575CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2576  const RecordType *RT = Ty->getAs<RecordType>();
2577  llvm::SmallPtrSet<MemberKind*, 1> Results;
2578
2579  if (!RT)
2580    return Results;
2581  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2582  if (!RD)
2583    return Results;
2584
2585  LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2586                 Sema::LookupMemberName);
2587
2588  // We just need to include all members of the right kind turned up by the
2589  // filter, at this point.
2590  if (S.LookupQualifiedName(R, RT->getDecl()))
2591    for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2592      NamedDecl *decl = (*I)->getUnderlyingDecl();
2593      if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2594        Results.insert(FK);
2595    }
2596  return Results;
2597}
2598
2599// Check if a (w)string was passed when a (w)char* was needed, and offer a
2600// better diagnostic if so. AT is assumed to be valid.
2601// Returns true when a c_str() conversion method is found.
2602bool CheckPrintfHandler::checkForCStrMembers(
2603    const analyze_printf::ArgType &AT, const Expr *E,
2604    const CharSourceRange &CSR) {
2605  typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2606
2607  MethodSet Results =
2608      CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2609
2610  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2611       MI != ME; ++MI) {
2612    const CXXMethodDecl *Method = *MI;
2613    if (Method->getNumParams() == 0 &&
2614          AT.matchesType(S.Context, Method->getResultType())) {
2615      // FIXME: Suggest parens if the expression needs them.
2616      SourceLocation EndLoc =
2617          S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2618      S.Diag(E->getLocStart(), diag::note_printf_c_str)
2619          << "c_str()"
2620          << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2621      return true;
2622    }
2623  }
2624
2625  return false;
2626}
2627
2628bool
2629CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2630                                            &FS,
2631                                          const char *startSpecifier,
2632                                          unsigned specifierLen) {
2633
2634  using namespace analyze_format_string;
2635  using namespace analyze_printf;
2636  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2637
2638  if (FS.consumesDataArgument()) {
2639    if (atFirstArg) {
2640        atFirstArg = false;
2641        usesPositionalArgs = FS.usesPositionalArg();
2642    }
2643    else if (usesPositionalArgs != FS.usesPositionalArg()) {
2644      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2645                                        startSpecifier, specifierLen);
2646      return false;
2647    }
2648  }
2649
2650  // First check if the field width, precision, and conversion specifier
2651  // have matching data arguments.
2652  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2653                    startSpecifier, specifierLen)) {
2654    return false;
2655  }
2656
2657  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2658                    startSpecifier, specifierLen)) {
2659    return false;
2660  }
2661
2662  if (!CS.consumesDataArgument()) {
2663    // FIXME: Technically specifying a precision or field width here
2664    // makes no sense.  Worth issuing a warning at some point.
2665    return true;
2666  }
2667
2668  // Consume the argument.
2669  unsigned argIndex = FS.getArgIndex();
2670  if (argIndex < NumDataArgs) {
2671    // The check to see if the argIndex is valid will come later.
2672    // We set the bit here because we may exit early from this
2673    // function if we encounter some other error.
2674    CoveredArgs.set(argIndex);
2675  }
2676
2677  // Check for using an Objective-C specific conversion specifier
2678  // in a non-ObjC literal.
2679  if (!ObjCContext && CS.isObjCArg()) {
2680    return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2681                                                  specifierLen);
2682  }
2683
2684  // Check for invalid use of field width
2685  if (!FS.hasValidFieldWidth()) {
2686    HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
2687        startSpecifier, specifierLen);
2688  }
2689
2690  // Check for invalid use of precision
2691  if (!FS.hasValidPrecision()) {
2692    HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2693        startSpecifier, specifierLen);
2694  }
2695
2696  // Check each flag does not conflict with any other component.
2697  if (!FS.hasValidThousandsGroupingPrefix())
2698    HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
2699  if (!FS.hasValidLeadingZeros())
2700    HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2701  if (!FS.hasValidPlusPrefix())
2702    HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
2703  if (!FS.hasValidSpacePrefix())
2704    HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
2705  if (!FS.hasValidAlternativeForm())
2706    HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2707  if (!FS.hasValidLeftJustified())
2708    HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2709
2710  // Check that flags are not ignored by another flag
2711  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2712    HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2713        startSpecifier, specifierLen);
2714  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2715    HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2716            startSpecifier, specifierLen);
2717
2718  // Check the length modifier is valid with the given conversion specifier.
2719  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
2720    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2721                                diag::warn_format_nonsensical_length);
2722  else if (!FS.hasStandardLengthModifier())
2723    HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
2724  else if (!FS.hasStandardLengthConversionCombination())
2725    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2726                                diag::warn_format_non_standard_conversion_spec);
2727
2728  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2729    HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2730
2731  // The remaining checks depend on the data arguments.
2732  if (HasVAListArg)
2733    return true;
2734
2735  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2736    return false;
2737
2738  const Expr *Arg = getDataArg(argIndex);
2739  if (!Arg)
2740    return true;
2741
2742  return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
2743}
2744
2745static bool requiresParensToAddCast(const Expr *E) {
2746  // FIXME: We should have a general way to reason about operator
2747  // precedence and whether parens are actually needed here.
2748  // Take care of a few common cases where they aren't.
2749  const Expr *Inside = E->IgnoreImpCasts();
2750  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2751    Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2752
2753  switch (Inside->getStmtClass()) {
2754  case Stmt::ArraySubscriptExprClass:
2755  case Stmt::CallExprClass:
2756  case Stmt::CharacterLiteralClass:
2757  case Stmt::CXXBoolLiteralExprClass:
2758  case Stmt::DeclRefExprClass:
2759  case Stmt::FloatingLiteralClass:
2760  case Stmt::IntegerLiteralClass:
2761  case Stmt::MemberExprClass:
2762  case Stmt::ObjCArrayLiteralClass:
2763  case Stmt::ObjCBoolLiteralExprClass:
2764  case Stmt::ObjCBoxedExprClass:
2765  case Stmt::ObjCDictionaryLiteralClass:
2766  case Stmt::ObjCEncodeExprClass:
2767  case Stmt::ObjCIvarRefExprClass:
2768  case Stmt::ObjCMessageExprClass:
2769  case Stmt::ObjCPropertyRefExprClass:
2770  case Stmt::ObjCStringLiteralClass:
2771  case Stmt::ObjCSubscriptRefExprClass:
2772  case Stmt::ParenExprClass:
2773  case Stmt::StringLiteralClass:
2774  case Stmt::UnaryOperatorClass:
2775    return false;
2776  default:
2777    return true;
2778  }
2779}
2780
2781bool
2782CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2783                                    const char *StartSpecifier,
2784                                    unsigned SpecifierLen,
2785                                    const Expr *E) {
2786  using namespace analyze_format_string;
2787  using namespace analyze_printf;
2788  // Now type check the data expression that matches the
2789  // format specifier.
2790  const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2791                                                    ObjCContext);
2792  if (!AT.isValid())
2793    return true;
2794
2795  QualType ExprTy = E->getType();
2796  while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
2797    ExprTy = TET->getUnderlyingExpr()->getType();
2798  }
2799
2800  if (AT.matchesType(S.Context, ExprTy))
2801    return true;
2802
2803  // Look through argument promotions for our error message's reported type.
2804  // This includes the integral and floating promotions, but excludes array
2805  // and function pointer decay; seeing that an argument intended to be a
2806  // string has type 'char [6]' is probably more confusing than 'char *'.
2807  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2808    if (ICE->getCastKind() == CK_IntegralCast ||
2809        ICE->getCastKind() == CK_FloatingCast) {
2810      E = ICE->getSubExpr();
2811      ExprTy = E->getType();
2812
2813      // Check if we didn't match because of an implicit cast from a 'char'
2814      // or 'short' to an 'int'.  This is done because printf is a varargs
2815      // function.
2816      if (ICE->getType() == S.Context.IntTy ||
2817          ICE->getType() == S.Context.UnsignedIntTy) {
2818        // All further checking is done on the subexpression.
2819        if (AT.matchesType(S.Context, ExprTy))
2820          return true;
2821      }
2822    }
2823  } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2824    // Special case for 'a', which has type 'int' in C.
2825    // Note, however, that we do /not/ want to treat multibyte constants like
2826    // 'MooV' as characters! This form is deprecated but still exists.
2827    if (ExprTy == S.Context.IntTy)
2828      if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2829        ExprTy = S.Context.CharTy;
2830  }
2831
2832  // %C in an Objective-C context prints a unichar, not a wchar_t.
2833  // If the argument is an integer of some kind, believe the %C and suggest
2834  // a cast instead of changing the conversion specifier.
2835  QualType IntendedTy = ExprTy;
2836  if (ObjCContext &&
2837      FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2838    if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2839        !ExprTy->isCharType()) {
2840      // 'unichar' is defined as a typedef of unsigned short, but we should
2841      // prefer using the typedef if it is visible.
2842      IntendedTy = S.Context.UnsignedShortTy;
2843
2844      LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2845                          Sema::LookupOrdinaryName);
2846      if (S.LookupName(Result, S.getCurScope())) {
2847        NamedDecl *ND = Result.getFoundDecl();
2848        if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2849          if (TD->getUnderlyingType() == IntendedTy)
2850            IntendedTy = S.Context.getTypedefType(TD);
2851      }
2852    }
2853  }
2854
2855  // Special-case some of Darwin's platform-independence types by suggesting
2856  // casts to primitive types that are known to be large enough.
2857  bool ShouldNotPrintDirectly = false;
2858  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
2859    // Use a 'while' to peel off layers of typedefs.
2860    QualType TyTy = IntendedTy;
2861    while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
2862      StringRef Name = UserTy->getDecl()->getName();
2863      QualType CastTy = llvm::StringSwitch<QualType>(Name)
2864        .Case("NSInteger", S.Context.LongTy)
2865        .Case("NSUInteger", S.Context.UnsignedLongTy)
2866        .Case("SInt32", S.Context.IntTy)
2867        .Case("UInt32", S.Context.UnsignedIntTy)
2868        .Default(QualType());
2869
2870      if (!CastTy.isNull()) {
2871        ShouldNotPrintDirectly = true;
2872        IntendedTy = CastTy;
2873        break;
2874      }
2875      TyTy = UserTy->desugar();
2876    }
2877  }
2878
2879  // We may be able to offer a FixItHint if it is a supported type.
2880  PrintfSpecifier fixedFS = FS;
2881  bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
2882                                 S.Context, ObjCContext);
2883
2884  if (success) {
2885    // Get the fix string from the fixed format specifier
2886    SmallString<16> buf;
2887    llvm::raw_svector_ostream os(buf);
2888    fixedFS.toString(os);
2889
2890    CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2891
2892    if (IntendedTy == ExprTy) {
2893      // In this case, the specifier is wrong and should be changed to match
2894      // the argument.
2895      EmitFormatDiagnostic(
2896        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2897          << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2898          << E->getSourceRange(),
2899        E->getLocStart(),
2900        /*IsStringLocation*/false,
2901        SpecRange,
2902        FixItHint::CreateReplacement(SpecRange, os.str()));
2903
2904    } else {
2905      // The canonical type for formatting this value is different from the
2906      // actual type of the expression. (This occurs, for example, with Darwin's
2907      // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2908      // should be printed as 'long' for 64-bit compatibility.)
2909      // Rather than emitting a normal format/argument mismatch, we want to
2910      // add a cast to the recommended type (and correct the format string
2911      // if necessary).
2912      SmallString<16> CastBuf;
2913      llvm::raw_svector_ostream CastFix(CastBuf);
2914      CastFix << "(";
2915      IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2916      CastFix << ")";
2917
2918      SmallVector<FixItHint,4> Hints;
2919      if (!AT.matchesType(S.Context, IntendedTy))
2920        Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2921
2922      if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2923        // If there's already a cast present, just replace it.
2924        SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2925        Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2926
2927      } else if (!requiresParensToAddCast(E)) {
2928        // If the expression has high enough precedence,
2929        // just write the C-style cast.
2930        Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2931                                                   CastFix.str()));
2932      } else {
2933        // Otherwise, add parens around the expression as well as the cast.
2934        CastFix << "(";
2935        Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2936                                                   CastFix.str()));
2937
2938        SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2939        Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2940      }
2941
2942      if (ShouldNotPrintDirectly) {
2943        // The expression has a type that should not be printed directly.
2944        // We extract the name from the typedef because we don't want to show
2945        // the underlying type in the diagnostic.
2946        StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
2947
2948        EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2949                               << Name << IntendedTy
2950                               << E->getSourceRange(),
2951                             E->getLocStart(), /*IsStringLocation=*/false,
2952                             SpecRange, Hints);
2953      } else {
2954        // In this case, the expression could be printed using a different
2955        // specifier, but we've decided that the specifier is probably correct
2956        // and we should cast instead. Just use the normal warning message.
2957        EmitFormatDiagnostic(
2958          S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2959            << AT.getRepresentativeTypeName(S.Context) << ExprTy
2960            << E->getSourceRange(),
2961          E->getLocStart(), /*IsStringLocation*/false,
2962          SpecRange, Hints);
2963      }
2964    }
2965  } else {
2966    const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2967                                                   SpecifierLen);
2968    // Since the warning for passing non-POD types to variadic functions
2969    // was deferred until now, we emit a warning for non-POD
2970    // arguments here.
2971    if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
2972      unsigned DiagKind;
2973      if (ExprTy->isObjCObjectType())
2974        DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2975      else
2976        DiagKind = diag::warn_non_pod_vararg_with_format_string;
2977
2978      EmitFormatDiagnostic(
2979        S.PDiag(DiagKind)
2980          << S.getLangOpts().CPlusPlus11
2981          << ExprTy
2982          << CallType
2983          << AT.getRepresentativeTypeName(S.Context)
2984          << CSR
2985          << E->getSourceRange(),
2986        E->getLocStart(), /*IsStringLocation*/false, CSR);
2987
2988      checkForCStrMembers(AT, E, CSR);
2989    } else
2990      EmitFormatDiagnostic(
2991        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2992          << AT.getRepresentativeTypeName(S.Context) << ExprTy
2993          << CSR
2994          << E->getSourceRange(),
2995        E->getLocStart(), /*IsStringLocation*/false, CSR);
2996  }
2997
2998  return true;
2999}
3000
3001//===--- CHECK: Scanf format string checking ------------------------------===//
3002
3003namespace {
3004class CheckScanfHandler : public CheckFormatHandler {
3005public:
3006  CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3007                    const Expr *origFormatExpr, unsigned firstDataArg,
3008                    unsigned numDataArgs, const char *beg, bool hasVAListArg,
3009                    ArrayRef<const Expr *> Args,
3010                    unsigned formatIdx, bool inFunctionCall,
3011                    Sema::VariadicCallType CallType)
3012  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3013                       numDataArgs, beg, hasVAListArg,
3014                       Args, formatIdx, inFunctionCall, CallType)
3015  {}
3016
3017  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3018                            const char *startSpecifier,
3019                            unsigned specifierLen);
3020
3021  bool HandleInvalidScanfConversionSpecifier(
3022          const analyze_scanf::ScanfSpecifier &FS,
3023          const char *startSpecifier,
3024          unsigned specifierLen);
3025
3026  void HandleIncompleteScanList(const char *start, const char *end);
3027};
3028}
3029
3030void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3031                                                 const char *end) {
3032  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3033                       getLocationOfByte(end), /*IsStringLocation*/true,
3034                       getSpecifierRange(start, end - start));
3035}
3036
3037bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3038                                        const analyze_scanf::ScanfSpecifier &FS,
3039                                        const char *startSpecifier,
3040                                        unsigned specifierLen) {
3041
3042  const analyze_scanf::ScanfConversionSpecifier &CS =
3043    FS.getConversionSpecifier();
3044
3045  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3046                                          getLocationOfByte(CS.getStart()),
3047                                          startSpecifier, specifierLen,
3048                                          CS.getStart(), CS.getLength());
3049}
3050
3051bool CheckScanfHandler::HandleScanfSpecifier(
3052                                       const analyze_scanf::ScanfSpecifier &FS,
3053                                       const char *startSpecifier,
3054                                       unsigned specifierLen) {
3055
3056  using namespace analyze_scanf;
3057  using namespace analyze_format_string;
3058
3059  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3060
3061  // Handle case where '%' and '*' don't consume an argument.  These shouldn't
3062  // be used to decide if we are using positional arguments consistently.
3063  if (FS.consumesDataArgument()) {
3064    if (atFirstArg) {
3065      atFirstArg = false;
3066      usesPositionalArgs = FS.usesPositionalArg();
3067    }
3068    else if (usesPositionalArgs != FS.usesPositionalArg()) {
3069      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3070                                        startSpecifier, specifierLen);
3071      return false;
3072    }
3073  }
3074
3075  // Check if the field with is non-zero.
3076  const OptionalAmount &Amt = FS.getFieldWidth();
3077  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3078    if (Amt.getConstantAmount() == 0) {
3079      const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3080                                                   Amt.getConstantLength());
3081      EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3082                           getLocationOfByte(Amt.getStart()),
3083                           /*IsStringLocation*/true, R,
3084                           FixItHint::CreateRemoval(R));
3085    }
3086  }
3087
3088  if (!FS.consumesDataArgument()) {
3089    // FIXME: Technically specifying a precision or field width here
3090    // makes no sense.  Worth issuing a warning at some point.
3091    return true;
3092  }
3093
3094  // Consume the argument.
3095  unsigned argIndex = FS.getArgIndex();
3096  if (argIndex < NumDataArgs) {
3097      // The check to see if the argIndex is valid will come later.
3098      // We set the bit here because we may exit early from this
3099      // function if we encounter some other error.
3100    CoveredArgs.set(argIndex);
3101  }
3102
3103  // Check the length modifier is valid with the given conversion specifier.
3104  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3105    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3106                                diag::warn_format_nonsensical_length);
3107  else if (!FS.hasStandardLengthModifier())
3108    HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3109  else if (!FS.hasStandardLengthConversionCombination())
3110    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3111                                diag::warn_format_non_standard_conversion_spec);
3112
3113  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3114    HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3115
3116  // The remaining checks depend on the data arguments.
3117  if (HasVAListArg)
3118    return true;
3119
3120  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3121    return false;
3122
3123  // Check that the argument type matches the format specifier.
3124  const Expr *Ex = getDataArg(argIndex);
3125  if (!Ex)
3126    return true;
3127
3128  const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3129  if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3130    ScanfSpecifier fixedFS = FS;
3131    bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
3132                                   S.Context);
3133
3134    if (success) {
3135      // Get the fix string from the fixed format specifier.
3136      SmallString<128> buf;
3137      llvm::raw_svector_ostream os(buf);
3138      fixedFS.toString(os);
3139
3140      EmitFormatDiagnostic(
3141        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3142          << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3143          << Ex->getSourceRange(),
3144        Ex->getLocStart(),
3145        /*IsStringLocation*/false,
3146        getSpecifierRange(startSpecifier, specifierLen),
3147        FixItHint::CreateReplacement(
3148          getSpecifierRange(startSpecifier, specifierLen),
3149          os.str()));
3150    } else {
3151      EmitFormatDiagnostic(
3152        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3153          << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3154          << Ex->getSourceRange(),
3155        Ex->getLocStart(),
3156        /*IsStringLocation*/false,
3157        getSpecifierRange(startSpecifier, specifierLen));
3158    }
3159  }
3160
3161  return true;
3162}
3163
3164void Sema::CheckFormatString(const StringLiteral *FExpr,
3165                             const Expr *OrigFormatExpr,
3166                             ArrayRef<const Expr *> Args,
3167                             bool HasVAListArg, unsigned format_idx,
3168                             unsigned firstDataArg, FormatStringType Type,
3169                             bool inFunctionCall, VariadicCallType CallType) {
3170
3171  // CHECK: is the format string a wide literal?
3172  if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3173    CheckFormatHandler::EmitFormatDiagnostic(
3174      *this, inFunctionCall, Args[format_idx],
3175      PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3176      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3177    return;
3178  }
3179
3180  // Str - The format string.  NOTE: this is NOT null-terminated!
3181  StringRef StrRef = FExpr->getString();
3182  const char *Str = StrRef.data();
3183  unsigned StrLen = StrRef.size();
3184  const unsigned numDataArgs = Args.size() - firstDataArg;
3185
3186  // CHECK: empty format string?
3187  if (StrLen == 0 && numDataArgs > 0) {
3188    CheckFormatHandler::EmitFormatDiagnostic(
3189      *this, inFunctionCall, Args[format_idx],
3190      PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3191      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3192    return;
3193  }
3194
3195  if (Type == FST_Printf || Type == FST_NSString) {
3196    CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3197                         numDataArgs, (Type == FST_NSString),
3198                         Str, HasVAListArg, Args, format_idx,
3199                         inFunctionCall, CallType);
3200
3201    if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3202                                                  getLangOpts(),
3203                                                  Context.getTargetInfo()))
3204      H.DoneProcessing();
3205  } else if (Type == FST_Scanf) {
3206    CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3207                        Str, HasVAListArg, Args, format_idx,
3208                        inFunctionCall, CallType);
3209
3210    if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
3211                                                 getLangOpts(),
3212                                                 Context.getTargetInfo()))
3213      H.DoneProcessing();
3214  } // TODO: handle other formats
3215}
3216
3217//===--- CHECK: Standard memory functions ---------------------------------===//
3218
3219/// \brief Determine whether the given type is a dynamic class type (e.g.,
3220/// whether it has a vtable).
3221static bool isDynamicClassType(QualType T) {
3222  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3223    if (CXXRecordDecl *Definition = Record->getDefinition())
3224      if (Definition->isDynamicClass())
3225        return true;
3226
3227  return false;
3228}
3229
3230/// \brief If E is a sizeof expression, returns its argument expression,
3231/// otherwise returns NULL.
3232static const Expr *getSizeOfExprArg(const Expr* E) {
3233  if (const UnaryExprOrTypeTraitExpr *SizeOf =
3234      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3235    if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3236      return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
3237
3238  return 0;
3239}
3240
3241/// \brief If E is a sizeof expression, returns its argument type.
3242static QualType getSizeOfArgType(const Expr* E) {
3243  if (const UnaryExprOrTypeTraitExpr *SizeOf =
3244      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3245    if (SizeOf->getKind() == clang::UETT_SizeOf)
3246      return SizeOf->getTypeOfArgument();
3247
3248  return QualType();
3249}
3250
3251/// \brief Check for dangerous or invalid arguments to memset().
3252///
3253/// This issues warnings on known problematic, dangerous or unspecified
3254/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3255/// function calls.
3256///
3257/// \param Call The call expression to diagnose.
3258void Sema::CheckMemaccessArguments(const CallExpr *Call,
3259                                   unsigned BId,
3260                                   IdentifierInfo *FnName) {
3261  assert(BId != 0);
3262
3263  // It is possible to have a non-standard definition of memset.  Validate
3264  // we have enough arguments, and if not, abort further checking.
3265  unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
3266  if (Call->getNumArgs() < ExpectedNumArgs)
3267    return;
3268
3269  unsigned LastArg = (BId == Builtin::BImemset ||
3270                      BId == Builtin::BIstrndup ? 1 : 2);
3271  unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
3272  const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
3273
3274  // We have special checking when the length is a sizeof expression.
3275  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3276  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3277  llvm::FoldingSetNodeID SizeOfArgID;
3278
3279  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3280    const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
3281    SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
3282
3283    QualType DestTy = Dest->getType();
3284    if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3285      QualType PointeeTy = DestPtrTy->getPointeeType();
3286
3287      // Never warn about void type pointers. This can be used to suppress
3288      // false positives.
3289      if (PointeeTy->isVoidType())
3290        continue;
3291
3292      // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3293      // actually comparing the expressions for equality. Because computing the
3294      // expression IDs can be expensive, we only do this if the diagnostic is
3295      // enabled.
3296      if (SizeOfArg &&
3297          Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3298                                   SizeOfArg->getExprLoc())) {
3299        // We only compute IDs for expressions if the warning is enabled, and
3300        // cache the sizeof arg's ID.
3301        if (SizeOfArgID == llvm::FoldingSetNodeID())
3302          SizeOfArg->Profile(SizeOfArgID, Context, true);
3303        llvm::FoldingSetNodeID DestID;
3304        Dest->Profile(DestID, Context, true);
3305        if (DestID == SizeOfArgID) {
3306          // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3307          //       over sizeof(src) as well.
3308          unsigned ActionIdx = 0; // Default is to suggest dereferencing.
3309          StringRef ReadableName = FnName->getName();
3310
3311          if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
3312            if (UnaryOp->getOpcode() == UO_AddrOf)
3313              ActionIdx = 1; // If its an address-of operator, just remove it.
3314          if (!PointeeTy->isIncompleteType() &&
3315              (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
3316            ActionIdx = 2; // If the pointee's size is sizeof(char),
3317                           // suggest an explicit length.
3318
3319          // If the function is defined as a builtin macro, do not show macro
3320          // expansion.
3321          SourceLocation SL = SizeOfArg->getExprLoc();
3322          SourceRange DSR = Dest->getSourceRange();
3323          SourceRange SSR = SizeOfArg->getSourceRange();
3324          SourceManager &SM  = PP.getSourceManager();
3325
3326          if (SM.isMacroArgExpansion(SL)) {
3327            ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3328            SL = SM.getSpellingLoc(SL);
3329            DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3330                             SM.getSpellingLoc(DSR.getEnd()));
3331            SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3332                             SM.getSpellingLoc(SSR.getEnd()));
3333          }
3334
3335          DiagRuntimeBehavior(SL, SizeOfArg,
3336                              PDiag(diag::warn_sizeof_pointer_expr_memaccess)
3337                                << ReadableName
3338                                << PointeeTy
3339                                << DestTy
3340                                << DSR
3341                                << SSR);
3342          DiagRuntimeBehavior(SL, SizeOfArg,
3343                         PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3344                                << ActionIdx
3345                                << SSR);
3346
3347          break;
3348        }
3349      }
3350
3351      // Also check for cases where the sizeof argument is the exact same
3352      // type as the memory argument, and where it points to a user-defined
3353      // record type.
3354      if (SizeOfArgTy != QualType()) {
3355        if (PointeeTy->isRecordType() &&
3356            Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3357          DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3358                              PDiag(diag::warn_sizeof_pointer_type_memaccess)
3359                                << FnName << SizeOfArgTy << ArgIdx
3360                                << PointeeTy << Dest->getSourceRange()
3361                                << LenExpr->getSourceRange());
3362          break;
3363        }
3364      }
3365
3366      // Always complain about dynamic classes.
3367      if (isDynamicClassType(PointeeTy)) {
3368
3369        unsigned OperationType = 0;
3370        // "overwritten" if we're warning about the destination for any call
3371        // but memcmp; otherwise a verb appropriate to the call.
3372        if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3373          if (BId == Builtin::BImemcpy)
3374            OperationType = 1;
3375          else if(BId == Builtin::BImemmove)
3376            OperationType = 2;
3377          else if (BId == Builtin::BImemcmp)
3378            OperationType = 3;
3379        }
3380
3381        DiagRuntimeBehavior(
3382          Dest->getExprLoc(), Dest,
3383          PDiag(diag::warn_dyn_class_memaccess)
3384            << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
3385            << FnName << PointeeTy
3386            << OperationType
3387            << Call->getCallee()->getSourceRange());
3388      } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3389               BId != Builtin::BImemset)
3390        DiagRuntimeBehavior(
3391          Dest->getExprLoc(), Dest,
3392          PDiag(diag::warn_arc_object_memaccess)
3393            << ArgIdx << FnName << PointeeTy
3394            << Call->getCallee()->getSourceRange());
3395      else
3396        continue;
3397
3398      DiagRuntimeBehavior(
3399        Dest->getExprLoc(), Dest,
3400        PDiag(diag::note_bad_memaccess_silence)
3401          << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3402      break;
3403    }
3404  }
3405}
3406
3407// A little helper routine: ignore addition and subtraction of integer literals.
3408// This intentionally does not ignore all integer constant expressions because
3409// we don't want to remove sizeof().
3410static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3411  Ex = Ex->IgnoreParenCasts();
3412
3413  for (;;) {
3414    const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3415    if (!BO || !BO->isAdditiveOp())
3416      break;
3417
3418    const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3419    const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3420
3421    if (isa<IntegerLiteral>(RHS))
3422      Ex = LHS;
3423    else if (isa<IntegerLiteral>(LHS))
3424      Ex = RHS;
3425    else
3426      break;
3427  }
3428
3429  return Ex;
3430}
3431
3432static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3433                                                      ASTContext &Context) {
3434  // Only handle constant-sized or VLAs, but not flexible members.
3435  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3436    // Only issue the FIXIT for arrays of size > 1.
3437    if (CAT->getSize().getSExtValue() <= 1)
3438      return false;
3439  } else if (!Ty->isVariableArrayType()) {
3440    return false;
3441  }
3442  return true;
3443}
3444
3445// Warn if the user has made the 'size' argument to strlcpy or strlcat
3446// be the size of the source, instead of the destination.
3447void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3448                                    IdentifierInfo *FnName) {
3449
3450  // Don't crash if the user has the wrong number of arguments
3451  if (Call->getNumArgs() != 3)
3452    return;
3453
3454  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3455  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3456  const Expr *CompareWithSrc = NULL;
3457
3458  // Look for 'strlcpy(dst, x, sizeof(x))'
3459  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3460    CompareWithSrc = Ex;
3461  else {
3462    // Look for 'strlcpy(dst, x, strlen(x))'
3463    if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
3464      if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
3465          && SizeCall->getNumArgs() == 1)
3466        CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3467    }
3468  }
3469
3470  if (!CompareWithSrc)
3471    return;
3472
3473  // Determine if the argument to sizeof/strlen is equal to the source
3474  // argument.  In principle there's all kinds of things you could do
3475  // here, for instance creating an == expression and evaluating it with
3476  // EvaluateAsBooleanCondition, but this uses a more direct technique:
3477  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3478  if (!SrcArgDRE)
3479    return;
3480
3481  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3482  if (!CompareWithSrcDRE ||
3483      SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3484    return;
3485
3486  const Expr *OriginalSizeArg = Call->getArg(2);
3487  Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3488    << OriginalSizeArg->getSourceRange() << FnName;
3489
3490  // Output a FIXIT hint if the destination is an array (rather than a
3491  // pointer to an array).  This could be enhanced to handle some
3492  // pointers if we know the actual size, like if DstArg is 'array+2'
3493  // we could say 'sizeof(array)-2'.
3494  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
3495  if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
3496    return;
3497
3498  SmallString<128> sizeString;
3499  llvm::raw_svector_ostream OS(sizeString);
3500  OS << "sizeof(";
3501  DstArg->printPretty(OS, 0, getPrintingPolicy());
3502  OS << ")";
3503
3504  Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3505    << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3506                                    OS.str());
3507}
3508
3509/// Check if two expressions refer to the same declaration.
3510static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3511  if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3512    if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3513      return D1->getDecl() == D2->getDecl();
3514  return false;
3515}
3516
3517static const Expr *getStrlenExprArg(const Expr *E) {
3518  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3519    const FunctionDecl *FD = CE->getDirectCallee();
3520    if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3521      return 0;
3522    return CE->getArg(0)->IgnoreParenCasts();
3523  }
3524  return 0;
3525}
3526
3527// Warn on anti-patterns as the 'size' argument to strncat.
3528// The correct size argument should look like following:
3529//   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3530void Sema::CheckStrncatArguments(const CallExpr *CE,
3531                                 IdentifierInfo *FnName) {
3532  // Don't crash if the user has the wrong number of arguments.
3533  if (CE->getNumArgs() < 3)
3534    return;
3535  const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3536  const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3537  const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3538
3539  // Identify common expressions, which are wrongly used as the size argument
3540  // to strncat and may lead to buffer overflows.
3541  unsigned PatternType = 0;
3542  if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3543    // - sizeof(dst)
3544    if (referToTheSameDecl(SizeOfArg, DstArg))
3545      PatternType = 1;
3546    // - sizeof(src)
3547    else if (referToTheSameDecl(SizeOfArg, SrcArg))
3548      PatternType = 2;
3549  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3550    if (BE->getOpcode() == BO_Sub) {
3551      const Expr *L = BE->getLHS()->IgnoreParenCasts();
3552      const Expr *R = BE->getRHS()->IgnoreParenCasts();
3553      // - sizeof(dst) - strlen(dst)
3554      if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3555          referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3556        PatternType = 1;
3557      // - sizeof(src) - (anything)
3558      else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3559        PatternType = 2;
3560    }
3561  }
3562
3563  if (PatternType == 0)
3564    return;
3565
3566  // Generate the diagnostic.
3567  SourceLocation SL = LenArg->getLocStart();
3568  SourceRange SR = LenArg->getSourceRange();
3569  SourceManager &SM  = PP.getSourceManager();
3570
3571  // If the function is defined as a builtin macro, do not show macro expansion.
3572  if (SM.isMacroArgExpansion(SL)) {
3573    SL = SM.getSpellingLoc(SL);
3574    SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3575                     SM.getSpellingLoc(SR.getEnd()));
3576  }
3577
3578  // Check if the destination is an array (rather than a pointer to an array).
3579  QualType DstTy = DstArg->getType();
3580  bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3581                                                                    Context);
3582  if (!isKnownSizeArray) {
3583    if (PatternType == 1)
3584      Diag(SL, diag::warn_strncat_wrong_size) << SR;
3585    else
3586      Diag(SL, diag::warn_strncat_src_size) << SR;
3587    return;
3588  }
3589
3590  if (PatternType == 1)
3591    Diag(SL, diag::warn_strncat_large_size) << SR;
3592  else
3593    Diag(SL, diag::warn_strncat_src_size) << SR;
3594
3595  SmallString<128> sizeString;
3596  llvm::raw_svector_ostream OS(sizeString);
3597  OS << "sizeof(";
3598  DstArg->printPretty(OS, 0, getPrintingPolicy());
3599  OS << ") - ";
3600  OS << "strlen(";
3601  DstArg->printPretty(OS, 0, getPrintingPolicy());
3602  OS << ") - 1";
3603
3604  Diag(SL, diag::note_strncat_wrong_size)
3605    << FixItHint::CreateReplacement(SR, OS.str());
3606}
3607
3608//===--- CHECK: Return Address of Stack Variable --------------------------===//
3609
3610static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3611                     Decl *ParentDecl);
3612static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3613                      Decl *ParentDecl);
3614
3615/// CheckReturnStackAddr - Check if a return statement returns the address
3616///   of a stack variable.
3617void
3618Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3619                           SourceLocation ReturnLoc) {
3620
3621  Expr *stackE = 0;
3622  SmallVector<DeclRefExpr *, 8> refVars;
3623
3624  // Perform checking for returned stack addresses, local blocks,
3625  // label addresses or references to temporaries.
3626  if (lhsType->isPointerType() ||
3627      (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
3628    stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
3629  } else if (lhsType->isReferenceType()) {
3630    stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
3631  }
3632
3633  if (stackE == 0)
3634    return; // Nothing suspicious was found.
3635
3636  SourceLocation diagLoc;
3637  SourceRange diagRange;
3638  if (refVars.empty()) {
3639    diagLoc = stackE->getLocStart();
3640    diagRange = stackE->getSourceRange();
3641  } else {
3642    // We followed through a reference variable. 'stackE' contains the
3643    // problematic expression but we will warn at the return statement pointing
3644    // at the reference variable. We will later display the "trail" of
3645    // reference variables using notes.
3646    diagLoc = refVars[0]->getLocStart();
3647    diagRange = refVars[0]->getSourceRange();
3648  }
3649
3650  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3651    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3652                                             : diag::warn_ret_stack_addr)
3653     << DR->getDecl()->getDeclName() << diagRange;
3654  } else if (isa<BlockExpr>(stackE)) { // local block.
3655    Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3656  } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3657    Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3658  } else { // local temporary.
3659    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3660                                             : diag::warn_ret_local_temp_addr)
3661     << diagRange;
3662  }
3663
3664  // Display the "trail" of reference variables that we followed until we
3665  // found the problematic expression using notes.
3666  for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3667    VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3668    // If this var binds to another reference var, show the range of the next
3669    // var, otherwise the var binds to the problematic expression, in which case
3670    // show the range of the expression.
3671    SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3672                                  : stackE->getSourceRange();
3673    Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3674      << VD->getDeclName() << range;
3675  }
3676}
3677
3678/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3679///  check if the expression in a return statement evaluates to an address
3680///  to a location on the stack, a local block, an address of a label, or a
3681///  reference to local temporary. The recursion is used to traverse the
3682///  AST of the return expression, with recursion backtracking when we
3683///  encounter a subexpression that (1) clearly does not lead to one of the
3684///  above problematic expressions (2) is something we cannot determine leads to
3685///  a problematic expression based on such local checking.
3686///
3687///  Both EvalAddr and EvalVal follow through reference variables to evaluate
3688///  the expression that they point to. Such variables are added to the
3689///  'refVars' vector so that we know what the reference variable "trail" was.
3690///
3691///  EvalAddr processes expressions that are pointers that are used as
3692///  references (and not L-values).  EvalVal handles all other values.
3693///  At the base case of the recursion is a check for the above problematic
3694///  expressions.
3695///
3696///  This implementation handles:
3697///
3698///   * pointer-to-pointer casts
3699///   * implicit conversions from array references to pointers
3700///   * taking the address of fields
3701///   * arbitrary interplay between "&" and "*" operators
3702///   * pointer arithmetic from an address of a stack variable
3703///   * taking the address of an array element where the array is on the stack
3704static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3705                      Decl *ParentDecl) {
3706  if (E->isTypeDependent())
3707      return NULL;
3708
3709  // We should only be called for evaluating pointer expressions.
3710  assert((E->getType()->isAnyPointerType() ||
3711          E->getType()->isBlockPointerType() ||
3712          E->getType()->isObjCQualifiedIdType()) &&
3713         "EvalAddr only works on pointers");
3714
3715  E = E->IgnoreParens();
3716
3717  // Our "symbolic interpreter" is just a dispatch off the currently
3718  // viewed AST node.  We then recursively traverse the AST by calling
3719  // EvalAddr and EvalVal appropriately.
3720  switch (E->getStmtClass()) {
3721  case Stmt::DeclRefExprClass: {
3722    DeclRefExpr *DR = cast<DeclRefExpr>(E);
3723
3724    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3725      // If this is a reference variable, follow through to the expression that
3726      // it points to.
3727      if (V->hasLocalStorage() &&
3728          V->getType()->isReferenceType() && V->hasInit()) {
3729        // Add the reference variable to the "trail".
3730        refVars.push_back(DR);
3731        return EvalAddr(V->getInit(), refVars, ParentDecl);
3732      }
3733
3734    return NULL;
3735  }
3736
3737  case Stmt::UnaryOperatorClass: {
3738    // The only unary operator that make sense to handle here
3739    // is AddrOf.  All others don't make sense as pointers.
3740    UnaryOperator *U = cast<UnaryOperator>(E);
3741
3742    if (U->getOpcode() == UO_AddrOf)
3743      return EvalVal(U->getSubExpr(), refVars, ParentDecl);
3744    else
3745      return NULL;
3746  }
3747
3748  case Stmt::BinaryOperatorClass: {
3749    // Handle pointer arithmetic.  All other binary operators are not valid
3750    // in this context.
3751    BinaryOperator *B = cast<BinaryOperator>(E);
3752    BinaryOperatorKind op = B->getOpcode();
3753
3754    if (op != BO_Add && op != BO_Sub)
3755      return NULL;
3756
3757    Expr *Base = B->getLHS();
3758
3759    // Determine which argument is the real pointer base.  It could be
3760    // the RHS argument instead of the LHS.
3761    if (!Base->getType()->isPointerType()) Base = B->getRHS();
3762
3763    assert (Base->getType()->isPointerType());
3764    return EvalAddr(Base, refVars, ParentDecl);
3765  }
3766
3767  // For conditional operators we need to see if either the LHS or RHS are
3768  // valid DeclRefExpr*s.  If one of them is valid, we return it.
3769  case Stmt::ConditionalOperatorClass: {
3770    ConditionalOperator *C = cast<ConditionalOperator>(E);
3771
3772    // Handle the GNU extension for missing LHS.
3773    if (Expr *lhsExpr = C->getLHS()) {
3774    // In C++, we can have a throw-expression, which has 'void' type.
3775      if (!lhsExpr->getType()->isVoidType())
3776        if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
3777          return LHS;
3778    }
3779
3780    // In C++, we can have a throw-expression, which has 'void' type.
3781    if (C->getRHS()->getType()->isVoidType())
3782      return NULL;
3783
3784    return EvalAddr(C->getRHS(), refVars, ParentDecl);
3785  }
3786
3787  case Stmt::BlockExprClass:
3788    if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
3789      return E; // local block.
3790    return NULL;
3791
3792  case Stmt::AddrLabelExprClass:
3793    return E; // address of label.
3794
3795  case Stmt::ExprWithCleanupsClass:
3796    return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3797                    ParentDecl);
3798
3799  // For casts, we need to handle conversions from arrays to
3800  // pointer values, and pointer-to-pointer conversions.
3801  case Stmt::ImplicitCastExprClass:
3802  case Stmt::CStyleCastExprClass:
3803  case Stmt::CXXFunctionalCastExprClass:
3804  case Stmt::ObjCBridgedCastExprClass:
3805  case Stmt::CXXStaticCastExprClass:
3806  case Stmt::CXXDynamicCastExprClass:
3807  case Stmt::CXXConstCastExprClass:
3808  case Stmt::CXXReinterpretCastExprClass: {
3809    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3810    switch (cast<CastExpr>(E)->getCastKind()) {
3811    case CK_BitCast:
3812    case CK_LValueToRValue:
3813    case CK_NoOp:
3814    case CK_BaseToDerived:
3815    case CK_DerivedToBase:
3816    case CK_UncheckedDerivedToBase:
3817    case CK_Dynamic:
3818    case CK_CPointerToObjCPointerCast:
3819    case CK_BlockPointerToObjCPointerCast:
3820    case CK_AnyPointerToBlockPointerCast:
3821      return EvalAddr(SubExpr, refVars, ParentDecl);
3822
3823    case CK_ArrayToPointerDecay:
3824      return EvalVal(SubExpr, refVars, ParentDecl);
3825
3826    default:
3827      return 0;
3828    }
3829  }
3830
3831  case Stmt::MaterializeTemporaryExprClass:
3832    if (Expr *Result = EvalAddr(
3833                         cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3834                                refVars, ParentDecl))
3835      return Result;
3836
3837    return E;
3838
3839  // Everything else: we simply don't reason about them.
3840  default:
3841    return NULL;
3842  }
3843}
3844
3845
3846///  EvalVal - This function is complements EvalAddr in the mutual recursion.
3847///   See the comments for EvalAddr for more details.
3848static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3849                     Decl *ParentDecl) {
3850do {
3851  // We should only be called for evaluating non-pointer expressions, or
3852  // expressions with a pointer type that are not used as references but instead
3853  // are l-values (e.g., DeclRefExpr with a pointer type).
3854
3855  // Our "symbolic interpreter" is just a dispatch off the currently
3856  // viewed AST node.  We then recursively traverse the AST by calling
3857  // EvalAddr and EvalVal appropriately.
3858
3859  E = E->IgnoreParens();
3860  switch (E->getStmtClass()) {
3861  case Stmt::ImplicitCastExprClass: {
3862    ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
3863    if (IE->getValueKind() == VK_LValue) {
3864      E = IE->getSubExpr();
3865      continue;
3866    }
3867    return NULL;
3868  }
3869
3870  case Stmt::ExprWithCleanupsClass:
3871    return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
3872
3873  case Stmt::DeclRefExprClass: {
3874    // When we hit a DeclRefExpr we are looking at code that refers to a
3875    // variable's name. If it's not a reference variable we check if it has
3876    // local storage within the function, and if so, return the expression.
3877    DeclRefExpr *DR = cast<DeclRefExpr>(E);
3878
3879    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3880      // Check if it refers to itself, e.g. "int& i = i;".
3881      if (V == ParentDecl)
3882        return DR;
3883
3884      if (V->hasLocalStorage()) {
3885        if (!V->getType()->isReferenceType())
3886          return DR;
3887
3888        // Reference variable, follow through to the expression that
3889        // it points to.
3890        if (V->hasInit()) {
3891          // Add the reference variable to the "trail".
3892          refVars.push_back(DR);
3893          return EvalVal(V->getInit(), refVars, V);
3894        }
3895      }
3896    }
3897
3898    return NULL;
3899  }
3900
3901  case Stmt::UnaryOperatorClass: {
3902    // The only unary operator that make sense to handle here
3903    // is Deref.  All others don't resolve to a "name."  This includes
3904    // handling all sorts of rvalues passed to a unary operator.
3905    UnaryOperator *U = cast<UnaryOperator>(E);
3906
3907    if (U->getOpcode() == UO_Deref)
3908      return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
3909
3910    return NULL;
3911  }
3912
3913  case Stmt::ArraySubscriptExprClass: {
3914    // Array subscripts are potential references to data on the stack.  We
3915    // retrieve the DeclRefExpr* for the array variable if it indeed
3916    // has local storage.
3917    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
3918  }
3919
3920  case Stmt::ConditionalOperatorClass: {
3921    // For conditional operators we need to see if either the LHS or RHS are
3922    // non-NULL Expr's.  If one is non-NULL, we return it.
3923    ConditionalOperator *C = cast<ConditionalOperator>(E);
3924
3925    // Handle the GNU extension for missing LHS.
3926    if (Expr *lhsExpr = C->getLHS())
3927      if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
3928        return LHS;
3929
3930    return EvalVal(C->getRHS(), refVars, ParentDecl);
3931  }
3932
3933  // Accesses to members are potential references to data on the stack.
3934  case Stmt::MemberExprClass: {
3935    MemberExpr *M = cast<MemberExpr>(E);
3936
3937    // Check for indirect access.  We only want direct field accesses.
3938    if (M->isArrow())
3939      return NULL;
3940
3941    // Check whether the member type is itself a reference, in which case
3942    // we're not going to refer to the member, but to what the member refers to.
3943    if (M->getMemberDecl()->getType()->isReferenceType())
3944      return NULL;
3945
3946    return EvalVal(M->getBase(), refVars, ParentDecl);
3947  }
3948
3949  case Stmt::MaterializeTemporaryExprClass:
3950    if (Expr *Result = EvalVal(
3951                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3952                               refVars, ParentDecl))
3953      return Result;
3954
3955    return E;
3956
3957  default:
3958    // Check that we don't return or take the address of a reference to a
3959    // temporary. This is only useful in C++.
3960    if (!E->isTypeDependent() && E->isRValue())
3961      return E;
3962
3963    // Everything else: we simply don't reason about them.
3964    return NULL;
3965  }
3966} while (true);
3967}
3968
3969//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3970
3971/// Check for comparisons of floating point operands using != and ==.
3972/// Issue a warning if these are no self-comparisons, as they are not likely
3973/// to do what the programmer intended.
3974void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
3975  Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3976  Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
3977
3978  // Special case: check for x == x (which is OK).
3979  // Do not emit warnings for such cases.
3980  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3981    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3982      if (DRL->getDecl() == DRR->getDecl())
3983        return;
3984
3985
3986  // Special case: check for comparisons against literals that can be exactly
3987  //  represented by APFloat.  In such cases, do not emit a warning.  This
3988  //  is a heuristic: often comparison against such literals are used to
3989  //  detect if a value in a variable has not changed.  This clearly can
3990  //  lead to false negatives.
3991  if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3992    if (FLL->isExact())
3993      return;
3994  } else
3995    if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
3996      if (FLR->isExact())
3997        return;
3998
3999  // Check for comparisons with builtin types.
4000  if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4001    if (CL->isBuiltinCall())
4002      return;
4003
4004  if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4005    if (CR->isBuiltinCall())
4006      return;
4007
4008  // Emit the diagnostic.
4009  Diag(Loc, diag::warn_floatingpoint_eq)
4010    << LHS->getSourceRange() << RHS->getSourceRange();
4011}
4012
4013//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4014//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
4015
4016namespace {
4017
4018/// Structure recording the 'active' range of an integer-valued
4019/// expression.
4020struct IntRange {
4021  /// The number of bits active in the int.
4022  unsigned Width;
4023
4024  /// True if the int is known not to have negative values.
4025  bool NonNegative;
4026
4027  IntRange(unsigned Width, bool NonNegative)
4028    : Width(Width), NonNegative(NonNegative)
4029  {}
4030
4031  /// Returns the range of the bool type.
4032  static IntRange forBoolType() {
4033    return IntRange(1, true);
4034  }
4035
4036  /// Returns the range of an opaque value of the given integral type.
4037  static IntRange forValueOfType(ASTContext &C, QualType T) {
4038    return forValueOfCanonicalType(C,
4039                          T->getCanonicalTypeInternal().getTypePtr());
4040  }
4041
4042  /// Returns the range of an opaque value of a canonical integral type.
4043  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
4044    assert(T->isCanonicalUnqualified());
4045
4046    if (const VectorType *VT = dyn_cast<VectorType>(T))
4047      T = VT->getElementType().getTypePtr();
4048    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4049      T = CT->getElementType().getTypePtr();
4050
4051    // For enum types, use the known bit width of the enumerators.
4052    if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4053      EnumDecl *Enum = ET->getDecl();
4054      if (!Enum->isCompleteDefinition())
4055        return IntRange(C.getIntWidth(QualType(T, 0)), false);
4056
4057      unsigned NumPositive = Enum->getNumPositiveBits();
4058      unsigned NumNegative = Enum->getNumNegativeBits();
4059
4060      if (NumNegative == 0)
4061        return IntRange(NumPositive, true/*NonNegative*/);
4062      else
4063        return IntRange(std::max(NumPositive + 1, NumNegative),
4064                        false/*NonNegative*/);
4065    }
4066
4067    const BuiltinType *BT = cast<BuiltinType>(T);
4068    assert(BT->isInteger());
4069
4070    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4071  }
4072
4073  /// Returns the "target" range of a canonical integral type, i.e.
4074  /// the range of values expressible in the type.
4075  ///
4076  /// This matches forValueOfCanonicalType except that enums have the
4077  /// full range of their type, not the range of their enumerators.
4078  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4079    assert(T->isCanonicalUnqualified());
4080
4081    if (const VectorType *VT = dyn_cast<VectorType>(T))
4082      T = VT->getElementType().getTypePtr();
4083    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4084      T = CT->getElementType().getTypePtr();
4085    if (const EnumType *ET = dyn_cast<EnumType>(T))
4086      T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
4087
4088    const BuiltinType *BT = cast<BuiltinType>(T);
4089    assert(BT->isInteger());
4090
4091    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4092  }
4093
4094  /// Returns the supremum of two ranges: i.e. their conservative merge.
4095  static IntRange join(IntRange L, IntRange R) {
4096    return IntRange(std::max(L.Width, R.Width),
4097                    L.NonNegative && R.NonNegative);
4098  }
4099
4100  /// Returns the infinum of two ranges: i.e. their aggressive merge.
4101  static IntRange meet(IntRange L, IntRange R) {
4102    return IntRange(std::min(L.Width, R.Width),
4103                    L.NonNegative || R.NonNegative);
4104  }
4105};
4106
4107static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4108                              unsigned MaxWidth) {
4109  if (value.isSigned() && value.isNegative())
4110    return IntRange(value.getMinSignedBits(), false);
4111
4112  if (value.getBitWidth() > MaxWidth)
4113    value = value.trunc(MaxWidth);
4114
4115  // isNonNegative() just checks the sign bit without considering
4116  // signedness.
4117  return IntRange(value.getActiveBits(), true);
4118}
4119
4120static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4121                              unsigned MaxWidth) {
4122  if (result.isInt())
4123    return GetValueRange(C, result.getInt(), MaxWidth);
4124
4125  if (result.isVector()) {
4126    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4127    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4128      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4129      R = IntRange::join(R, El);
4130    }
4131    return R;
4132  }
4133
4134  if (result.isComplexInt()) {
4135    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4136    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4137    return IntRange::join(R, I);
4138  }
4139
4140  // This can happen with lossless casts to intptr_t of "based" lvalues.
4141  // Assume it might use arbitrary bits.
4142  // FIXME: The only reason we need to pass the type in here is to get
4143  // the sign right on this one case.  It would be nice if APValue
4144  // preserved this.
4145  assert(result.isLValue() || result.isAddrLabelDiff());
4146  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
4147}
4148
4149/// Pseudo-evaluate the given integer expression, estimating the
4150/// range of values it might take.
4151///
4152/// \param MaxWidth - the width to which the value will be truncated
4153static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
4154  E = E->IgnoreParens();
4155
4156  // Try a full evaluation first.
4157  Expr::EvalResult result;
4158  if (E->EvaluateAsRValue(result, C))
4159    return GetValueRange(C, result.Val, E->getType(), MaxWidth);
4160
4161  // I think we only want to look through implicit casts here; if the
4162  // user has an explicit widening cast, we should treat the value as
4163  // being of the new, wider type.
4164  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
4165    if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
4166      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4167
4168    IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
4169
4170    bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
4171
4172    // Assume that non-integer casts can span the full range of the type.
4173    if (!isIntegerCast)
4174      return OutputTypeRange;
4175
4176    IntRange SubRange
4177      = GetExprRange(C, CE->getSubExpr(),
4178                     std::min(MaxWidth, OutputTypeRange.Width));
4179
4180    // Bail out if the subexpr's range is as wide as the cast type.
4181    if (SubRange.Width >= OutputTypeRange.Width)
4182      return OutputTypeRange;
4183
4184    // Otherwise, we take the smaller width, and we're non-negative if
4185    // either the output type or the subexpr is.
4186    return IntRange(SubRange.Width,
4187                    SubRange.NonNegative || OutputTypeRange.NonNegative);
4188  }
4189
4190  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4191    // If we can fold the condition, just take that operand.
4192    bool CondResult;
4193    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4194      return GetExprRange(C, CondResult ? CO->getTrueExpr()
4195                                        : CO->getFalseExpr(),
4196                          MaxWidth);
4197
4198    // Otherwise, conservatively merge.
4199    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4200    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4201    return IntRange::join(L, R);
4202  }
4203
4204  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4205    switch (BO->getOpcode()) {
4206
4207    // Boolean-valued operations are single-bit and positive.
4208    case BO_LAnd:
4209    case BO_LOr:
4210    case BO_LT:
4211    case BO_GT:
4212    case BO_LE:
4213    case BO_GE:
4214    case BO_EQ:
4215    case BO_NE:
4216      return IntRange::forBoolType();
4217
4218    // The type of the assignments is the type of the LHS, so the RHS
4219    // is not necessarily the same type.
4220    case BO_MulAssign:
4221    case BO_DivAssign:
4222    case BO_RemAssign:
4223    case BO_AddAssign:
4224    case BO_SubAssign:
4225    case BO_XorAssign:
4226    case BO_OrAssign:
4227      // TODO: bitfields?
4228      return IntRange::forValueOfType(C, E->getType());
4229
4230    // Simple assignments just pass through the RHS, which will have
4231    // been coerced to the LHS type.
4232    case BO_Assign:
4233      // TODO: bitfields?
4234      return GetExprRange(C, BO->getRHS(), MaxWidth);
4235
4236    // Operations with opaque sources are black-listed.
4237    case BO_PtrMemD:
4238    case BO_PtrMemI:
4239      return IntRange::forValueOfType(C, E->getType());
4240
4241    // Bitwise-and uses the *infinum* of the two source ranges.
4242    case BO_And:
4243    case BO_AndAssign:
4244      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4245                            GetExprRange(C, BO->getRHS(), MaxWidth));
4246
4247    // Left shift gets black-listed based on a judgement call.
4248    case BO_Shl:
4249      // ...except that we want to treat '1 << (blah)' as logically
4250      // positive.  It's an important idiom.
4251      if (IntegerLiteral *I
4252            = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4253        if (I->getValue() == 1) {
4254          IntRange R = IntRange::forValueOfType(C, E->getType());
4255          return IntRange(R.Width, /*NonNegative*/ true);
4256        }
4257      }
4258      // fallthrough
4259
4260    case BO_ShlAssign:
4261      return IntRange::forValueOfType(C, E->getType());
4262
4263    // Right shift by a constant can narrow its left argument.
4264    case BO_Shr:
4265    case BO_ShrAssign: {
4266      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4267
4268      // If the shift amount is a positive constant, drop the width by
4269      // that much.
4270      llvm::APSInt shift;
4271      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4272          shift.isNonNegative()) {
4273        unsigned zext = shift.getZExtValue();
4274        if (zext >= L.Width)
4275          L.Width = (L.NonNegative ? 0 : 1);
4276        else
4277          L.Width -= zext;
4278      }
4279
4280      return L;
4281    }
4282
4283    // Comma acts as its right operand.
4284    case BO_Comma:
4285      return GetExprRange(C, BO->getRHS(), MaxWidth);
4286
4287    // Black-list pointer subtractions.
4288    case BO_Sub:
4289      if (BO->getLHS()->getType()->isPointerType())
4290        return IntRange::forValueOfType(C, E->getType());
4291      break;
4292
4293    // The width of a division result is mostly determined by the size
4294    // of the LHS.
4295    case BO_Div: {
4296      // Don't 'pre-truncate' the operands.
4297      unsigned opWidth = C.getIntWidth(E->getType());
4298      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4299
4300      // If the divisor is constant, use that.
4301      llvm::APSInt divisor;
4302      if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4303        unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4304        if (log2 >= L.Width)
4305          L.Width = (L.NonNegative ? 0 : 1);
4306        else
4307          L.Width = std::min(L.Width - log2, MaxWidth);
4308        return L;
4309      }
4310
4311      // Otherwise, just use the LHS's width.
4312      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4313      return IntRange(L.Width, L.NonNegative && R.NonNegative);
4314    }
4315
4316    // The result of a remainder can't be larger than the result of
4317    // either side.
4318    case BO_Rem: {
4319      // Don't 'pre-truncate' the operands.
4320      unsigned opWidth = C.getIntWidth(E->getType());
4321      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4322      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4323
4324      IntRange meet = IntRange::meet(L, R);
4325      meet.Width = std::min(meet.Width, MaxWidth);
4326      return meet;
4327    }
4328
4329    // The default behavior is okay for these.
4330    case BO_Mul:
4331    case BO_Add:
4332    case BO_Xor:
4333    case BO_Or:
4334      break;
4335    }
4336
4337    // The default case is to treat the operation as if it were closed
4338    // on the narrowest type that encompasses both operands.
4339    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4340    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4341    return IntRange::join(L, R);
4342  }
4343
4344  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4345    switch (UO->getOpcode()) {
4346    // Boolean-valued operations are white-listed.
4347    case UO_LNot:
4348      return IntRange::forBoolType();
4349
4350    // Operations with opaque sources are black-listed.
4351    case UO_Deref:
4352    case UO_AddrOf: // should be impossible
4353      return IntRange::forValueOfType(C, E->getType());
4354
4355    default:
4356      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4357    }
4358  }
4359
4360  if (dyn_cast<OffsetOfExpr>(E)) {
4361    IntRange::forValueOfType(C, E->getType());
4362  }
4363
4364  if (FieldDecl *BitField = E->getSourceBitField())
4365    return IntRange(BitField->getBitWidthValue(C),
4366                    BitField->getType()->isUnsignedIntegerOrEnumerationType());
4367
4368  return IntRange::forValueOfType(C, E->getType());
4369}
4370
4371static IntRange GetExprRange(ASTContext &C, Expr *E) {
4372  return GetExprRange(C, E, C.getIntWidth(E->getType()));
4373}
4374
4375/// Checks whether the given value, which currently has the given
4376/// source semantics, has the same value when coerced through the
4377/// target semantics.
4378static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4379                                 const llvm::fltSemantics &Src,
4380                                 const llvm::fltSemantics &Tgt) {
4381  llvm::APFloat truncated = value;
4382
4383  bool ignored;
4384  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4385  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4386
4387  return truncated.bitwiseIsEqual(value);
4388}
4389
4390/// Checks whether the given value, which currently has the given
4391/// source semantics, has the same value when coerced through the
4392/// target semantics.
4393///
4394/// The value might be a vector of floats (or a complex number).
4395static bool IsSameFloatAfterCast(const APValue &value,
4396                                 const llvm::fltSemantics &Src,
4397                                 const llvm::fltSemantics &Tgt) {
4398  if (value.isFloat())
4399    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4400
4401  if (value.isVector()) {
4402    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4403      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4404        return false;
4405    return true;
4406  }
4407
4408  assert(value.isComplexFloat());
4409  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4410          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4411}
4412
4413static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
4414
4415static bool IsZero(Sema &S, Expr *E) {
4416  // Suppress cases where we are comparing against an enum constant.
4417  if (const DeclRefExpr *DR =
4418      dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4419    if (isa<EnumConstantDecl>(DR->getDecl()))
4420      return false;
4421
4422  // Suppress cases where the '0' value is expanded from a macro.
4423  if (E->getLocStart().isMacroID())
4424    return false;
4425
4426  llvm::APSInt Value;
4427  return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4428}
4429
4430static bool HasEnumType(Expr *E) {
4431  // Strip off implicit integral promotions.
4432  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4433    if (ICE->getCastKind() != CK_IntegralCast &&
4434        ICE->getCastKind() != CK_NoOp)
4435      break;
4436    E = ICE->getSubExpr();
4437  }
4438
4439  return E->getType()->isEnumeralType();
4440}
4441
4442static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
4443  BinaryOperatorKind op = E->getOpcode();
4444  if (E->isValueDependent())
4445    return;
4446
4447  if (op == BO_LT && IsZero(S, E->getRHS())) {
4448    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4449      << "< 0" << "false" << HasEnumType(E->getLHS())
4450      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4451  } else if (op == BO_GE && IsZero(S, E->getRHS())) {
4452    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4453      << ">= 0" << "true" << HasEnumType(E->getLHS())
4454      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4455  } else if (op == BO_GT && IsZero(S, E->getLHS())) {
4456    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4457      << "0 >" << "false" << HasEnumType(E->getRHS())
4458      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4459  } else if (op == BO_LE && IsZero(S, E->getLHS())) {
4460    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4461      << "0 <=" << "true" << HasEnumType(E->getRHS())
4462      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4463  }
4464}
4465
4466static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
4467                                         Expr *Constant, Expr *Other,
4468                                         llvm::APSInt Value,
4469                                         bool RhsConstant) {
4470  // 0 values are handled later by CheckTrivialUnsignedComparison().
4471  if (Value == 0)
4472    return;
4473
4474  BinaryOperatorKind op = E->getOpcode();
4475  QualType OtherT = Other->getType();
4476  QualType ConstantT = Constant->getType();
4477  QualType CommonT = E->getLHS()->getType();
4478  if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
4479    return;
4480  assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
4481         && "comparison with non-integer type");
4482
4483  bool ConstantSigned = ConstantT->isSignedIntegerType();
4484  bool CommonSigned = CommonT->isSignedIntegerType();
4485
4486  bool EqualityOnly = false;
4487
4488  // TODO: Investigate using GetExprRange() to get tighter bounds on
4489  // on the bit ranges.
4490  IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
4491  unsigned OtherWidth = OtherRange.Width;
4492
4493  if (CommonSigned) {
4494    // The common type is signed, therefore no signed to unsigned conversion.
4495    if (!OtherRange.NonNegative) {
4496      // Check that the constant is representable in type OtherT.
4497      if (ConstantSigned) {
4498        if (OtherWidth >= Value.getMinSignedBits())
4499          return;
4500      } else { // !ConstantSigned
4501        if (OtherWidth >= Value.getActiveBits() + 1)
4502          return;
4503      }
4504    } else { // !OtherSigned
4505      // Check that the constant is representable in type OtherT.
4506      // Negative values are out of range.
4507      if (ConstantSigned) {
4508        if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4509          return;
4510      } else { // !ConstantSigned
4511        if (OtherWidth >= Value.getActiveBits())
4512          return;
4513      }
4514    }
4515  } else {  // !CommonSigned
4516    if (OtherRange.NonNegative) {
4517      if (OtherWidth >= Value.getActiveBits())
4518        return;
4519    } else if (!OtherRange.NonNegative && !ConstantSigned) {
4520      // Check to see if the constant is representable in OtherT.
4521      if (OtherWidth > Value.getActiveBits())
4522        return;
4523      // Check to see if the constant is equivalent to a negative value
4524      // cast to CommonT.
4525      if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
4526          Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
4527        return;
4528      // The constant value rests between values that OtherT can represent after
4529      // conversion.  Relational comparison still works, but equality
4530      // comparisons will be tautological.
4531      EqualityOnly = true;
4532    } else { // OtherSigned && ConstantSigned
4533      assert(0 && "Two signed types converted to unsigned types.");
4534    }
4535  }
4536
4537  bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4538
4539  bool IsTrue = true;
4540  if (op == BO_EQ || op == BO_NE) {
4541    IsTrue = op == BO_NE;
4542  } else if (EqualityOnly) {
4543    return;
4544  } else if (RhsConstant) {
4545    if (op == BO_GT || op == BO_GE)
4546      IsTrue = !PositiveConstant;
4547    else // op == BO_LT || op == BO_LE
4548      IsTrue = PositiveConstant;
4549  } else {
4550    if (op == BO_LT || op == BO_LE)
4551      IsTrue = !PositiveConstant;
4552    else // op == BO_GT || op == BO_GE
4553      IsTrue = PositiveConstant;
4554  }
4555
4556  // If this is a comparison to an enum constant, include that
4557  // constant in the diagnostic.
4558  const EnumConstantDecl *ED = 0;
4559  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4560    ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4561
4562  SmallString<64> PrettySourceValue;
4563  llvm::raw_svector_ostream OS(PrettySourceValue);
4564  if (ED)
4565    OS << '\'' << *ED << "' (" << Value << ")";
4566  else
4567    OS << Value;
4568
4569  S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
4570      << OS.str() << OtherT << IsTrue
4571      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4572}
4573
4574/// Analyze the operands of the given comparison.  Implements the
4575/// fallback case from AnalyzeComparison.
4576static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
4577  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4578  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4579}
4580
4581/// \brief Implements -Wsign-compare.
4582///
4583/// \param E the binary operator to check for warnings
4584static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
4585  // The type the comparison is being performed in.
4586  QualType T = E->getLHS()->getType();
4587  assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4588         && "comparison with mismatched types");
4589  if (E->isValueDependent())
4590    return AnalyzeImpConvsInComparison(S, E);
4591
4592  Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4593  Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
4594
4595  bool IsComparisonConstant = false;
4596
4597  // Check whether an integer constant comparison results in a value
4598  // of 'true' or 'false'.
4599  if (T->isIntegralType(S.Context)) {
4600    llvm::APSInt RHSValue;
4601    bool IsRHSIntegralLiteral =
4602      RHS->isIntegerConstantExpr(RHSValue, S.Context);
4603    llvm::APSInt LHSValue;
4604    bool IsLHSIntegralLiteral =
4605      LHS->isIntegerConstantExpr(LHSValue, S.Context);
4606    if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4607        DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4608    else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4609      DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4610    else
4611      IsComparisonConstant =
4612        (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
4613  } else if (!T->hasUnsignedIntegerRepresentation())
4614      IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
4615
4616  // We don't do anything special if this isn't an unsigned integral
4617  // comparison:  we're only interested in integral comparisons, and
4618  // signed comparisons only happen in cases we don't care to warn about.
4619  //
4620  // We also don't care about value-dependent expressions or expressions
4621  // whose result is a constant.
4622  if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
4623    return AnalyzeImpConvsInComparison(S, E);
4624
4625  // Check to see if one of the (unmodified) operands is of different
4626  // signedness.
4627  Expr *signedOperand, *unsignedOperand;
4628  if (LHS->getType()->hasSignedIntegerRepresentation()) {
4629    assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
4630           "unsigned comparison between two signed integer expressions?");
4631    signedOperand = LHS;
4632    unsignedOperand = RHS;
4633  } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4634    signedOperand = RHS;
4635    unsignedOperand = LHS;
4636  } else {
4637    CheckTrivialUnsignedComparison(S, E);
4638    return AnalyzeImpConvsInComparison(S, E);
4639  }
4640
4641  // Otherwise, calculate the effective range of the signed operand.
4642  IntRange signedRange = GetExprRange(S.Context, signedOperand);
4643
4644  // Go ahead and analyze implicit conversions in the operands.  Note
4645  // that we skip the implicit conversions on both sides.
4646  AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4647  AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
4648
4649  // If the signed range is non-negative, -Wsign-compare won't fire,
4650  // but we should still check for comparisons which are always true
4651  // or false.
4652  if (signedRange.NonNegative)
4653    return CheckTrivialUnsignedComparison(S, E);
4654
4655  // For (in)equality comparisons, if the unsigned operand is a
4656  // constant which cannot collide with a overflowed signed operand,
4657  // then reinterpreting the signed operand as unsigned will not
4658  // change the result of the comparison.
4659  if (E->isEqualityOp()) {
4660    unsigned comparisonWidth = S.Context.getIntWidth(T);
4661    IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
4662
4663    // We should never be unable to prove that the unsigned operand is
4664    // non-negative.
4665    assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4666
4667    if (unsignedRange.Width < comparisonWidth)
4668      return;
4669  }
4670
4671  S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4672    S.PDiag(diag::warn_mixed_sign_comparison)
4673      << LHS->getType() << RHS->getType()
4674      << LHS->getSourceRange() << RHS->getSourceRange());
4675}
4676
4677/// Analyzes an attempt to assign the given value to a bitfield.
4678///
4679/// Returns true if there was something fishy about the attempt.
4680static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4681                                      SourceLocation InitLoc) {
4682  assert(Bitfield->isBitField());
4683  if (Bitfield->isInvalidDecl())
4684    return false;
4685
4686  // White-list bool bitfields.
4687  if (Bitfield->getType()->isBooleanType())
4688    return false;
4689
4690  // Ignore value- or type-dependent expressions.
4691  if (Bitfield->getBitWidth()->isValueDependent() ||
4692      Bitfield->getBitWidth()->isTypeDependent() ||
4693      Init->isValueDependent() ||
4694      Init->isTypeDependent())
4695    return false;
4696
4697  Expr *OriginalInit = Init->IgnoreParenImpCasts();
4698
4699  llvm::APSInt Value;
4700  if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
4701    return false;
4702
4703  unsigned OriginalWidth = Value.getBitWidth();
4704  unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
4705
4706  if (OriginalWidth <= FieldWidth)
4707    return false;
4708
4709  // Compute the value which the bitfield will contain.
4710  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
4711  TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
4712
4713  // Check whether the stored value is equal to the original value.
4714  TruncatedValue = TruncatedValue.extend(OriginalWidth);
4715  if (llvm::APSInt::isSameValue(Value, TruncatedValue))
4716    return false;
4717
4718  // Special-case bitfields of width 1: booleans are naturally 0/1, and
4719  // therefore don't strictly fit into a signed bitfield of width 1.
4720  if (FieldWidth == 1 && Value == 1)
4721    return false;
4722
4723  std::string PrettyValue = Value.toString(10);
4724  std::string PrettyTrunc = TruncatedValue.toString(10);
4725
4726  S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4727    << PrettyValue << PrettyTrunc << OriginalInit->getType()
4728    << Init->getSourceRange();
4729
4730  return true;
4731}
4732
4733/// Analyze the given simple or compound assignment for warning-worthy
4734/// operations.
4735static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
4736  // Just recurse on the LHS.
4737  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4738
4739  // We want to recurse on the RHS as normal unless we're assigning to
4740  // a bitfield.
4741  if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
4742    if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
4743                                  E->getOperatorLoc())) {
4744      // Recurse, ignoring any implicit conversions on the RHS.
4745      return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4746                                        E->getOperatorLoc());
4747    }
4748  }
4749
4750  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4751}
4752
4753/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
4754static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
4755                            SourceLocation CContext, unsigned diag,
4756                            bool pruneControlFlow = false) {
4757  if (pruneControlFlow) {
4758    S.DiagRuntimeBehavior(E->getExprLoc(), E,
4759                          S.PDiag(diag)
4760                            << SourceType << T << E->getSourceRange()
4761                            << SourceRange(CContext));
4762    return;
4763  }
4764  S.Diag(E->getExprLoc(), diag)
4765    << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4766}
4767
4768/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
4769static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
4770                            SourceLocation CContext, unsigned diag,
4771                            bool pruneControlFlow = false) {
4772  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
4773}
4774
4775/// Diagnose an implicit cast from a literal expression. Does not warn when the
4776/// cast wouldn't lose information.
4777void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4778                                    SourceLocation CContext) {
4779  // Try to convert the literal exactly to an integer. If we can, don't warn.
4780  bool isExact = false;
4781  const llvm::APFloat &Value = FL->getValue();
4782  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4783                            T->hasUnsignedIntegerRepresentation());
4784  if (Value.convertToInteger(IntegerValue,
4785                             llvm::APFloat::rmTowardZero, &isExact)
4786      == llvm::APFloat::opOK && isExact)
4787    return;
4788
4789  SmallString<16> PrettySourceValue;
4790  Value.toString(PrettySourceValue);
4791  SmallString<16> PrettyTargetValue;
4792  if (T->isSpecificBuiltinType(BuiltinType::Bool))
4793    PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4794  else
4795    IntegerValue.toString(PrettyTargetValue);
4796
4797  S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
4798    << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4799    << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
4800}
4801
4802std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4803  if (!Range.Width) return "0";
4804
4805  llvm::APSInt ValueInRange = Value;
4806  ValueInRange.setIsSigned(!Range.NonNegative);
4807  ValueInRange = ValueInRange.trunc(Range.Width);
4808  return ValueInRange.toString(10);
4809}
4810
4811static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4812  if (!isa<ImplicitCastExpr>(Ex))
4813    return false;
4814
4815  Expr *InnerE = Ex->IgnoreParenImpCasts();
4816  const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4817  const Type *Source =
4818    S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4819  if (Target->isDependentType())
4820    return false;
4821
4822  const BuiltinType *FloatCandidateBT =
4823    dyn_cast<BuiltinType>(ToBool ? Source : Target);
4824  const Type *BoolCandidateType = ToBool ? Target : Source;
4825
4826  return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4827          FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4828}
4829
4830void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4831                                      SourceLocation CC) {
4832  unsigned NumArgs = TheCall->getNumArgs();
4833  for (unsigned i = 0; i < NumArgs; ++i) {
4834    Expr *CurrA = TheCall->getArg(i);
4835    if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4836      continue;
4837
4838    bool IsSwapped = ((i > 0) &&
4839        IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4840    IsSwapped |= ((i < (NumArgs - 1)) &&
4841        IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4842    if (IsSwapped) {
4843      // Warn on this floating-point to bool conversion.
4844      DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4845                      CurrA->getType(), CC,
4846                      diag::warn_impcast_floating_point_to_bool);
4847    }
4848  }
4849}
4850
4851void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
4852                             SourceLocation CC, bool *ICContext = 0) {
4853  if (E->isTypeDependent() || E->isValueDependent()) return;
4854
4855  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4856  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4857  if (Source == Target) return;
4858  if (Target->isDependentType()) return;
4859
4860  // If the conversion context location is invalid don't complain. We also
4861  // don't want to emit a warning if the issue occurs from the expansion of
4862  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4863  // delay this check as long as possible. Once we detect we are in that
4864  // scenario, we just return.
4865  if (CC.isInvalid())
4866    return;
4867
4868  // Diagnose implicit casts to bool.
4869  if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4870    if (isa<StringLiteral>(E))
4871      // Warn on string literal to bool.  Checks for string literals in logical
4872      // expressions, for instances, assert(0 && "error here"), is prevented
4873      // by a check in AnalyzeImplicitConversions().
4874      return DiagnoseImpCast(S, E, T, CC,
4875                             diag::warn_impcast_string_literal_to_bool);
4876    if (Source->isFunctionType()) {
4877      // Warn on function to bool. Checks free functions and static member
4878      // functions. Weakly imported functions are excluded from the check,
4879      // since it's common to test their value to check whether the linker
4880      // found a definition for them.
4881      ValueDecl *D = 0;
4882      if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4883        D = R->getDecl();
4884      } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4885        D = M->getMemberDecl();
4886      }
4887
4888      if (D && !D->isWeak()) {
4889        if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4890          S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4891            << F << E->getSourceRange() << SourceRange(CC);
4892          S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4893            << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4894          QualType ReturnType;
4895          UnresolvedSet<4> NonTemplateOverloads;
4896          S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
4897          if (!ReturnType.isNull()
4898              && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4899            S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4900              << FixItHint::CreateInsertion(
4901                 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
4902          return;
4903        }
4904      }
4905    }
4906  }
4907
4908  // Strip vector types.
4909  if (isa<VectorType>(Source)) {
4910    if (!isa<VectorType>(Target)) {
4911      if (S.SourceMgr.isInSystemMacro(CC))
4912        return;
4913      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
4914    }
4915
4916    // If the vector cast is cast between two vectors of the same size, it is
4917    // a bitcast, not a conversion.
4918    if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4919      return;
4920
4921    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4922    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4923  }
4924
4925  // Strip complex types.
4926  if (isa<ComplexType>(Source)) {
4927    if (!isa<ComplexType>(Target)) {
4928      if (S.SourceMgr.isInSystemMacro(CC))
4929        return;
4930
4931      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
4932    }
4933
4934    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4935    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4936  }
4937
4938  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4939  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4940
4941  // If the source is floating point...
4942  if (SourceBT && SourceBT->isFloatingPoint()) {
4943    // ...and the target is floating point...
4944    if (TargetBT && TargetBT->isFloatingPoint()) {
4945      // ...then warn if we're dropping FP rank.
4946
4947      // Builtin FP kinds are ordered by increasing FP rank.
4948      if (SourceBT->getKind() > TargetBT->getKind()) {
4949        // Don't warn about float constants that are precisely
4950        // representable in the target type.
4951        Expr::EvalResult result;
4952        if (E->EvaluateAsRValue(result, S.Context)) {
4953          // Value might be a float, a float vector, or a float complex.
4954          if (IsSameFloatAfterCast(result.Val,
4955                   S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4956                   S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
4957            return;
4958        }
4959
4960        if (S.SourceMgr.isInSystemMacro(CC))
4961          return;
4962
4963        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
4964      }
4965      return;
4966    }
4967
4968    // If the target is integral, always warn.
4969    if (TargetBT && TargetBT->isInteger()) {
4970      if (S.SourceMgr.isInSystemMacro(CC))
4971        return;
4972
4973      Expr *InnerE = E->IgnoreParenImpCasts();
4974      // We also want to warn on, e.g., "int i = -1.234"
4975      if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4976        if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4977          InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4978
4979      if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4980        DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
4981      } else {
4982        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4983      }
4984    }
4985
4986    // If the target is bool, warn if expr is a function or method call.
4987    if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
4988        isa<CallExpr>(E)) {
4989      // Check last argument of function call to see if it is an
4990      // implicit cast from a type matching the type the result
4991      // is being cast to.
4992      CallExpr *CEx = cast<CallExpr>(E);
4993      unsigned NumArgs = CEx->getNumArgs();
4994      if (NumArgs > 0) {
4995        Expr *LastA = CEx->getArg(NumArgs - 1);
4996        Expr *InnerE = LastA->IgnoreParenImpCasts();
4997        const Type *InnerType =
4998          S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4999        if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5000          // Warn on this floating-point to bool conversion
5001          DiagnoseImpCast(S, E, T, CC,
5002                          diag::warn_impcast_floating_point_to_bool);
5003        }
5004      }
5005    }
5006    return;
5007  }
5008
5009  if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
5010           == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
5011      && !Target->isBlockPointerType() && !Target->isMemberPointerType()
5012      && Target->isScalarType() && !Target->isNullPtrType()) {
5013    SourceLocation Loc = E->getSourceRange().getBegin();
5014    if (Loc.isMacroID())
5015      Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
5016    if (!Loc.isMacroID() || CC.isMacroID())
5017      S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5018          << T << clang::SourceRange(CC)
5019          << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
5020  }
5021
5022  if (!Source->isIntegerType() || !Target->isIntegerType())
5023    return;
5024
5025  // TODO: remove this early return once the false positives for constant->bool
5026  // in templates, macros, etc, are reduced or removed.
5027  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5028    return;
5029
5030  IntRange SourceRange = GetExprRange(S.Context, E);
5031  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
5032
5033  if (SourceRange.Width > TargetRange.Width) {
5034    // If the source is a constant, use a default-on diagnostic.
5035    // TODO: this should happen for bitfield stores, too.
5036    llvm::APSInt Value(32);
5037    if (E->isIntegerConstantExpr(Value, S.Context)) {
5038      if (S.SourceMgr.isInSystemMacro(CC))
5039        return;
5040
5041      std::string PrettySourceValue = Value.toString(10);
5042      std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
5043
5044      S.DiagRuntimeBehavior(E->getExprLoc(), E,
5045        S.PDiag(diag::warn_impcast_integer_precision_constant)
5046            << PrettySourceValue << PrettyTargetValue
5047            << E->getType() << T << E->getSourceRange()
5048            << clang::SourceRange(CC));
5049      return;
5050    }
5051
5052    // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5053    if (S.SourceMgr.isInSystemMacro(CC))
5054      return;
5055
5056    if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
5057      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5058                             /* pruneControlFlow */ true);
5059    return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
5060  }
5061
5062  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5063      (!TargetRange.NonNegative && SourceRange.NonNegative &&
5064       SourceRange.Width == TargetRange.Width)) {
5065
5066    if (S.SourceMgr.isInSystemMacro(CC))
5067      return;
5068
5069    unsigned DiagID = diag::warn_impcast_integer_sign;
5070
5071    // Traditionally, gcc has warned about this under -Wsign-compare.
5072    // We also want to warn about it in -Wconversion.
5073    // So if -Wconversion is off, use a completely identical diagnostic
5074    // in the sign-compare group.
5075    // The conditional-checking code will
5076    if (ICContext) {
5077      DiagID = diag::warn_impcast_integer_sign_conditional;
5078      *ICContext = true;
5079    }
5080
5081    return DiagnoseImpCast(S, E, T, CC, DiagID);
5082  }
5083
5084  // Diagnose conversions between different enumeration types.
5085  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5086  // type, to give us better diagnostics.
5087  QualType SourceType = E->getType();
5088  if (!S.getLangOpts().CPlusPlus) {
5089    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5090      if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5091        EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5092        SourceType = S.Context.getTypeDeclType(Enum);
5093        Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5094      }
5095  }
5096
5097  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5098    if (const EnumType *TargetEnum = Target->getAs<EnumType>())
5099      if (SourceEnum->getDecl()->hasNameForLinkage() &&
5100          TargetEnum->getDecl()->hasNameForLinkage() &&
5101          SourceEnum != TargetEnum) {
5102        if (S.SourceMgr.isInSystemMacro(CC))
5103          return;
5104
5105        return DiagnoseImpCast(S, E, SourceType, T, CC,
5106                               diag::warn_impcast_different_enum_types);
5107      }
5108
5109  return;
5110}
5111
5112void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5113                              SourceLocation CC, QualType T);
5114
5115void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
5116                             SourceLocation CC, bool &ICContext) {
5117  E = E->IgnoreParenImpCasts();
5118
5119  if (isa<ConditionalOperator>(E))
5120    return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
5121
5122  AnalyzeImplicitConversions(S, E, CC);
5123  if (E->getType() != T)
5124    return CheckImplicitConversion(S, E, T, CC, &ICContext);
5125  return;
5126}
5127
5128void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5129                              SourceLocation CC, QualType T) {
5130  AnalyzeImplicitConversions(S, E->getCond(), CC);
5131
5132  bool Suspicious = false;
5133  CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5134  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
5135
5136  // If -Wconversion would have warned about either of the candidates
5137  // for a signedness conversion to the context type...
5138  if (!Suspicious) return;
5139
5140  // ...but it's currently ignored...
5141  if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5142                                 CC))
5143    return;
5144
5145  // ...then check whether it would have warned about either of the
5146  // candidates for a signedness conversion to the condition type.
5147  if (E->getType() == T) return;
5148
5149  Suspicious = false;
5150  CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5151                          E->getType(), CC, &Suspicious);
5152  if (!Suspicious)
5153    CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
5154                            E->getType(), CC, &Suspicious);
5155}
5156
5157/// AnalyzeImplicitConversions - Find and report any interesting
5158/// implicit conversions in the given expression.  There are a couple
5159/// of competing diagnostics here, -Wconversion and -Wsign-compare.
5160void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
5161  QualType T = OrigE->getType();
5162  Expr *E = OrigE->IgnoreParenImpCasts();
5163
5164  if (E->isTypeDependent() || E->isValueDependent())
5165    return;
5166
5167  // For conditional operators, we analyze the arguments as if they
5168  // were being fed directly into the output.
5169  if (isa<ConditionalOperator>(E)) {
5170    ConditionalOperator *CO = cast<ConditionalOperator>(E);
5171    CheckConditionalOperator(S, CO, CC, T);
5172    return;
5173  }
5174
5175  // Check implicit argument conversions for function calls.
5176  if (CallExpr *Call = dyn_cast<CallExpr>(E))
5177    CheckImplicitArgumentConversions(S, Call, CC);
5178
5179  // Go ahead and check any implicit conversions we might have skipped.
5180  // The non-canonical typecheck is just an optimization;
5181  // CheckImplicitConversion will filter out dead implicit conversions.
5182  if (E->getType() != T)
5183    CheckImplicitConversion(S, E, T, CC);
5184
5185  // Now continue drilling into this expression.
5186
5187  if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
5188    if (POE->getResultExpr())
5189      E = POE->getResultExpr();
5190  }
5191
5192  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5193    return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5194
5195  // Skip past explicit casts.
5196  if (isa<ExplicitCastExpr>(E)) {
5197    E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
5198    return AnalyzeImplicitConversions(S, E, CC);
5199  }
5200
5201  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5202    // Do a somewhat different check with comparison operators.
5203    if (BO->isComparisonOp())
5204      return AnalyzeComparison(S, BO);
5205
5206    // And with simple assignments.
5207    if (BO->getOpcode() == BO_Assign)
5208      return AnalyzeAssignment(S, BO);
5209  }
5210
5211  // These break the otherwise-useful invariant below.  Fortunately,
5212  // we don't really need to recurse into them, because any internal
5213  // expressions should have been analyzed already when they were
5214  // built into statements.
5215  if (isa<StmtExpr>(E)) return;
5216
5217  // Don't descend into unevaluated contexts.
5218  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
5219
5220  // Now just recurse over the expression's children.
5221  CC = E->getExprLoc();
5222  BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5223  bool IsLogicalOperator = BO && BO->isLogicalOp();
5224  for (Stmt::child_range I = E->children(); I; ++I) {
5225    Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
5226    if (!ChildExpr)
5227      continue;
5228
5229    if (IsLogicalOperator &&
5230        isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5231      // Ignore checking string literals that are in logical operators.
5232      continue;
5233    AnalyzeImplicitConversions(S, ChildExpr, CC);
5234  }
5235}
5236
5237} // end anonymous namespace
5238
5239/// Diagnoses "dangerous" implicit conversions within the given
5240/// expression (which is a full expression).  Implements -Wconversion
5241/// and -Wsign-compare.
5242///
5243/// \param CC the "context" location of the implicit conversion, i.e.
5244///   the most location of the syntactic entity requiring the implicit
5245///   conversion
5246void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
5247  // Don't diagnose in unevaluated contexts.
5248  if (isUnevaluatedContext())
5249    return;
5250
5251  // Don't diagnose for value- or type-dependent expressions.
5252  if (E->isTypeDependent() || E->isValueDependent())
5253    return;
5254
5255  // Check for array bounds violations in cases where the check isn't triggered
5256  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5257  // ArraySubscriptExpr is on the RHS of a variable initialization.
5258  CheckArrayAccess(E);
5259
5260  // This is not the right CC for (e.g.) a variable initialization.
5261  AnalyzeImplicitConversions(*this, E, CC);
5262}
5263
5264/// Diagnose when expression is an integer constant expression and its evaluation
5265/// results in integer overflow
5266void Sema::CheckForIntOverflow (Expr *E) {
5267  if (isa<BinaryOperator>(E->IgnoreParens())) {
5268    llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5269    E->EvaluateForOverflow(Context, &Diags);
5270  }
5271}
5272
5273namespace {
5274/// \brief Visitor for expressions which looks for unsequenced operations on the
5275/// same object.
5276class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
5277  /// \brief A tree of sequenced regions within an expression. Two regions are
5278  /// unsequenced if one is an ancestor or a descendent of the other. When we
5279  /// finish processing an expression with sequencing, such as a comma
5280  /// expression, we fold its tree nodes into its parent, since they are
5281  /// unsequenced with respect to nodes we will visit later.
5282  class SequenceTree {
5283    struct Value {
5284      explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5285      unsigned Parent : 31;
5286      bool Merged : 1;
5287    };
5288    llvm::SmallVector<Value, 8> Values;
5289
5290  public:
5291    /// \brief A region within an expression which may be sequenced with respect
5292    /// to some other region.
5293    class Seq {
5294      explicit Seq(unsigned N) : Index(N) {}
5295      unsigned Index;
5296      friend class SequenceTree;
5297    public:
5298      Seq() : Index(0) {}
5299    };
5300
5301    SequenceTree() { Values.push_back(Value(0)); }
5302    Seq root() const { return Seq(0); }
5303
5304    /// \brief Create a new sequence of operations, which is an unsequenced
5305    /// subset of \p Parent. This sequence of operations is sequenced with
5306    /// respect to other children of \p Parent.
5307    Seq allocate(Seq Parent) {
5308      Values.push_back(Value(Parent.Index));
5309      return Seq(Values.size() - 1);
5310    }
5311
5312    /// \brief Merge a sequence of operations into its parent.
5313    void merge(Seq S) {
5314      Values[S.Index].Merged = true;
5315    }
5316
5317    /// \brief Determine whether two operations are unsequenced. This operation
5318    /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5319    /// should have been merged into its parent as appropriate.
5320    bool isUnsequenced(Seq Cur, Seq Old) {
5321      unsigned C = representative(Cur.Index);
5322      unsigned Target = representative(Old.Index);
5323      while (C >= Target) {
5324        if (C == Target)
5325          return true;
5326        C = Values[C].Parent;
5327      }
5328      return false;
5329    }
5330
5331  private:
5332    /// \brief Pick a representative for a sequence.
5333    unsigned representative(unsigned K) {
5334      if (Values[K].Merged)
5335        // Perform path compression as we go.
5336        return Values[K].Parent = representative(Values[K].Parent);
5337      return K;
5338    }
5339  };
5340
5341  /// An object for which we can track unsequenced uses.
5342  typedef NamedDecl *Object;
5343
5344  /// Different flavors of object usage which we track. We only track the
5345  /// least-sequenced usage of each kind.
5346  enum UsageKind {
5347    /// A read of an object. Multiple unsequenced reads are OK.
5348    UK_Use,
5349    /// A modification of an object which is sequenced before the value
5350    /// computation of the expression, such as ++n.
5351    UK_ModAsValue,
5352    /// A modification of an object which is not sequenced before the value
5353    /// computation of the expression, such as n++.
5354    UK_ModAsSideEffect,
5355
5356    UK_Count = UK_ModAsSideEffect + 1
5357  };
5358
5359  struct Usage {
5360    Usage() : Use(0), Seq() {}
5361    Expr *Use;
5362    SequenceTree::Seq Seq;
5363  };
5364
5365  struct UsageInfo {
5366    UsageInfo() : Diagnosed(false) {}
5367    Usage Uses[UK_Count];
5368    /// Have we issued a diagnostic for this variable already?
5369    bool Diagnosed;
5370  };
5371  typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5372
5373  Sema &SemaRef;
5374  /// Sequenced regions within the expression.
5375  SequenceTree Tree;
5376  /// Declaration modifications and references which we have seen.
5377  UsageInfoMap UsageMap;
5378  /// The region we are currently within.
5379  SequenceTree::Seq Region;
5380  /// Filled in with declarations which were modified as a side-effect
5381  /// (that is, post-increment operations).
5382  llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
5383  /// Expressions to check later. We defer checking these to reduce
5384  /// stack usage.
5385  llvm::SmallVectorImpl<Expr*> &WorkList;
5386
5387  /// RAII object wrapping the visitation of a sequenced subexpression of an
5388  /// expression. At the end of this process, the side-effects of the evaluation
5389  /// become sequenced with respect to the value computation of the result, so
5390  /// we downgrade any UK_ModAsSideEffect within the evaluation to
5391  /// UK_ModAsValue.
5392  struct SequencedSubexpression {
5393    SequencedSubexpression(SequenceChecker &Self)
5394      : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5395      Self.ModAsSideEffect = &ModAsSideEffect;
5396    }
5397    ~SequencedSubexpression() {
5398      for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5399        UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5400        U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5401        Self.addUsage(U, ModAsSideEffect[I].first,
5402                      ModAsSideEffect[I].second.Use, UK_ModAsValue);
5403      }
5404      Self.ModAsSideEffect = OldModAsSideEffect;
5405    }
5406
5407    SequenceChecker &Self;
5408    llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5409    llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5410  };
5411
5412  /// RAII object wrapping the visitation of a subexpression which we might
5413  /// choose to evaluate as a constant. If any subexpression is evaluated and
5414  /// found to be non-constant, this allows us to suppress the evaluation of
5415  /// the outer expression.
5416  class EvaluationTracker {
5417  public:
5418    EvaluationTracker(SequenceChecker &Self)
5419        : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5420      Self.EvalTracker = this;
5421    }
5422    ~EvaluationTracker() {
5423      Self.EvalTracker = Prev;
5424      if (Prev)
5425        Prev->EvalOK &= EvalOK;
5426    }
5427
5428    bool evaluate(const Expr *E, bool &Result) {
5429      if (!EvalOK || E->isValueDependent())
5430        return false;
5431      EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5432      return EvalOK;
5433    }
5434
5435  private:
5436    SequenceChecker &Self;
5437    EvaluationTracker *Prev;
5438    bool EvalOK;
5439  } *EvalTracker;
5440
5441  /// \brief Find the object which is produced by the specified expression,
5442  /// if any.
5443  Object getObject(Expr *E, bool Mod) const {
5444    E = E->IgnoreParenCasts();
5445    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5446      if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5447        return getObject(UO->getSubExpr(), Mod);
5448    } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5449      if (BO->getOpcode() == BO_Comma)
5450        return getObject(BO->getRHS(), Mod);
5451      if (Mod && BO->isAssignmentOp())
5452        return getObject(BO->getLHS(), Mod);
5453    } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5454      // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5455      if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5456        return ME->getMemberDecl();
5457    } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5458      // FIXME: If this is a reference, map through to its value.
5459      return DRE->getDecl();
5460    return 0;
5461  }
5462
5463  /// \brief Note that an object was modified or used by an expression.
5464  void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5465    Usage &U = UI.Uses[UK];
5466    if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5467      if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5468        ModAsSideEffect->push_back(std::make_pair(O, U));
5469      U.Use = Ref;
5470      U.Seq = Region;
5471    }
5472  }
5473  /// \brief Check whether a modification or use conflicts with a prior usage.
5474  void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5475                  bool IsModMod) {
5476    if (UI.Diagnosed)
5477      return;
5478
5479    const Usage &U = UI.Uses[OtherKind];
5480    if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5481      return;
5482
5483    Expr *Mod = U.Use;
5484    Expr *ModOrUse = Ref;
5485    if (OtherKind == UK_Use)
5486      std::swap(Mod, ModOrUse);
5487
5488    SemaRef.Diag(Mod->getExprLoc(),
5489                 IsModMod ? diag::warn_unsequenced_mod_mod
5490                          : diag::warn_unsequenced_mod_use)
5491      << O << SourceRange(ModOrUse->getExprLoc());
5492    UI.Diagnosed = true;
5493  }
5494
5495  void notePreUse(Object O, Expr *Use) {
5496    UsageInfo &U = UsageMap[O];
5497    // Uses conflict with other modifications.
5498    checkUsage(O, U, Use, UK_ModAsValue, false);
5499  }
5500  void notePostUse(Object O, Expr *Use) {
5501    UsageInfo &U = UsageMap[O];
5502    checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5503    addUsage(U, O, Use, UK_Use);
5504  }
5505
5506  void notePreMod(Object O, Expr *Mod) {
5507    UsageInfo &U = UsageMap[O];
5508    // Modifications conflict with other modifications and with uses.
5509    checkUsage(O, U, Mod, UK_ModAsValue, true);
5510    checkUsage(O, U, Mod, UK_Use, false);
5511  }
5512  void notePostMod(Object O, Expr *Use, UsageKind UK) {
5513    UsageInfo &U = UsageMap[O];
5514    checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5515    addUsage(U, O, Use, UK);
5516  }
5517
5518public:
5519  SequenceChecker(Sema &S, Expr *E,
5520                  llvm::SmallVectorImpl<Expr*> &WorkList)
5521    : EvaluatedExprVisitor<SequenceChecker>(S.Context), SemaRef(S),
5522      Region(Tree.root()), ModAsSideEffect(0), WorkList(WorkList),
5523      EvalTracker(0) {
5524    Visit(E);
5525  }
5526
5527  void VisitStmt(Stmt *S) {
5528    // Skip all statements which aren't expressions for now.
5529  }
5530
5531  void VisitExpr(Expr *E) {
5532    // By default, just recurse to evaluated subexpressions.
5533    EvaluatedExprVisitor<SequenceChecker>::VisitStmt(E);
5534  }
5535
5536  void VisitCastExpr(CastExpr *E) {
5537    Object O = Object();
5538    if (E->getCastKind() == CK_LValueToRValue)
5539      O = getObject(E->getSubExpr(), false);
5540
5541    if (O)
5542      notePreUse(O, E);
5543    VisitExpr(E);
5544    if (O)
5545      notePostUse(O, E);
5546  }
5547
5548  void VisitBinComma(BinaryOperator *BO) {
5549    // C++11 [expr.comma]p1:
5550    //   Every value computation and side effect associated with the left
5551    //   expression is sequenced before every value computation and side
5552    //   effect associated with the right expression.
5553    SequenceTree::Seq LHS = Tree.allocate(Region);
5554    SequenceTree::Seq RHS = Tree.allocate(Region);
5555    SequenceTree::Seq OldRegion = Region;
5556
5557    {
5558      SequencedSubexpression SeqLHS(*this);
5559      Region = LHS;
5560      Visit(BO->getLHS());
5561    }
5562
5563    Region = RHS;
5564    Visit(BO->getRHS());
5565
5566    Region = OldRegion;
5567
5568    // Forget that LHS and RHS are sequenced. They are both unsequenced
5569    // with respect to other stuff.
5570    Tree.merge(LHS);
5571    Tree.merge(RHS);
5572  }
5573
5574  void VisitBinAssign(BinaryOperator *BO) {
5575    // The modification is sequenced after the value computation of the LHS
5576    // and RHS, so check it before inspecting the operands and update the
5577    // map afterwards.
5578    Object O = getObject(BO->getLHS(), true);
5579    if (!O)
5580      return VisitExpr(BO);
5581
5582    notePreMod(O, BO);
5583
5584    // C++11 [expr.ass]p7:
5585    //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5586    //   only once.
5587    //
5588    // Therefore, for a compound assignment operator, O is considered used
5589    // everywhere except within the evaluation of E1 itself.
5590    if (isa<CompoundAssignOperator>(BO))
5591      notePreUse(O, BO);
5592
5593    Visit(BO->getLHS());
5594
5595    if (isa<CompoundAssignOperator>(BO))
5596      notePostUse(O, BO);
5597
5598    Visit(BO->getRHS());
5599
5600    notePostMod(O, BO, UK_ModAsValue);
5601  }
5602  void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5603    VisitBinAssign(CAO);
5604  }
5605
5606  void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5607  void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5608  void VisitUnaryPreIncDec(UnaryOperator *UO) {
5609    Object O = getObject(UO->getSubExpr(), true);
5610    if (!O)
5611      return VisitExpr(UO);
5612
5613    notePreMod(O, UO);
5614    Visit(UO->getSubExpr());
5615    notePostMod(O, UO, UK_ModAsValue);
5616  }
5617
5618  void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5619  void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5620  void VisitUnaryPostIncDec(UnaryOperator *UO) {
5621    Object O = getObject(UO->getSubExpr(), true);
5622    if (!O)
5623      return VisitExpr(UO);
5624
5625    notePreMod(O, UO);
5626    Visit(UO->getSubExpr());
5627    notePostMod(O, UO, UK_ModAsSideEffect);
5628  }
5629
5630  /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5631  void VisitBinLOr(BinaryOperator *BO) {
5632    // The side-effects of the LHS of an '&&' are sequenced before the
5633    // value computation of the RHS, and hence before the value computation
5634    // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5635    // as if they were unconditionally sequenced.
5636    EvaluationTracker Eval(*this);
5637    {
5638      SequencedSubexpression Sequenced(*this);
5639      Visit(BO->getLHS());
5640    }
5641
5642    bool Result;
5643    if (Eval.evaluate(BO->getLHS(), Result)) {
5644      if (!Result)
5645        Visit(BO->getRHS());
5646    } else {
5647      // Check for unsequenced operations in the RHS, treating it as an
5648      // entirely separate evaluation.
5649      //
5650      // FIXME: If there are operations in the RHS which are unsequenced
5651      // with respect to operations outside the RHS, and those operations
5652      // are unconditionally evaluated, diagnose them.
5653      WorkList.push_back(BO->getRHS());
5654    }
5655  }
5656  void VisitBinLAnd(BinaryOperator *BO) {
5657    EvaluationTracker Eval(*this);
5658    {
5659      SequencedSubexpression Sequenced(*this);
5660      Visit(BO->getLHS());
5661    }
5662
5663    bool Result;
5664    if (Eval.evaluate(BO->getLHS(), Result)) {
5665      if (Result)
5666        Visit(BO->getRHS());
5667    } else {
5668      WorkList.push_back(BO->getRHS());
5669    }
5670  }
5671
5672  // Only visit the condition, unless we can be sure which subexpression will
5673  // be chosen.
5674  void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
5675    EvaluationTracker Eval(*this);
5676    SequencedSubexpression Sequenced(*this);
5677    Visit(CO->getCond());
5678
5679    bool Result;
5680    if (Eval.evaluate(CO->getCond(), Result))
5681      Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
5682    else {
5683      WorkList.push_back(CO->getTrueExpr());
5684      WorkList.push_back(CO->getFalseExpr());
5685    }
5686  }
5687
5688  void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
5689    if (!CCE->isListInitialization())
5690      return VisitExpr(CCE);
5691
5692    // In C++11, list initializations are sequenced.
5693    llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5694    SequenceTree::Seq Parent = Region;
5695    for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5696                                        E = CCE->arg_end();
5697         I != E; ++I) {
5698      Region = Tree.allocate(Parent);
5699      Elts.push_back(Region);
5700      Visit(*I);
5701    }
5702
5703    // Forget that the initializers are sequenced.
5704    Region = Parent;
5705    for (unsigned I = 0; I < Elts.size(); ++I)
5706      Tree.merge(Elts[I]);
5707  }
5708
5709  void VisitInitListExpr(InitListExpr *ILE) {
5710    if (!SemaRef.getLangOpts().CPlusPlus11)
5711      return VisitExpr(ILE);
5712
5713    // In C++11, list initializations are sequenced.
5714    llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5715    SequenceTree::Seq Parent = Region;
5716    for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5717      Expr *E = ILE->getInit(I);
5718      if (!E) continue;
5719      Region = Tree.allocate(Parent);
5720      Elts.push_back(Region);
5721      Visit(E);
5722    }
5723
5724    // Forget that the initializers are sequenced.
5725    Region = Parent;
5726    for (unsigned I = 0; I < Elts.size(); ++I)
5727      Tree.merge(Elts[I]);
5728  }
5729};
5730}
5731
5732void Sema::CheckUnsequencedOperations(Expr *E) {
5733  llvm::SmallVector<Expr*, 8> WorkList;
5734  WorkList.push_back(E);
5735  while (!WorkList.empty()) {
5736    Expr *Item = WorkList.back();
5737    WorkList.pop_back();
5738    SequenceChecker(*this, Item, WorkList);
5739  }
5740}
5741
5742void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5743                              bool IsConstexpr) {
5744  CheckImplicitConversions(E, CheckLoc);
5745  CheckUnsequencedOperations(E);
5746  if (!IsConstexpr && !E->isValueDependent())
5747    CheckForIntOverflow(E);
5748}
5749
5750void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5751                                       FieldDecl *BitField,
5752                                       Expr *Init) {
5753  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5754}
5755
5756/// CheckParmsForFunctionDef - Check that the parameters of the given
5757/// function are appropriate for the definition of a function. This
5758/// takes care of any checks that cannot be performed on the
5759/// declaration itself, e.g., that the types of each of the function
5760/// parameters are complete.
5761bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
5762                                    bool CheckParameterNames) {
5763  bool HasInvalidParm = false;
5764  for (; P != PEnd; ++P) {
5765    ParmVarDecl *Param = *P;
5766
5767    // C99 6.7.5.3p4: the parameters in a parameter type list in a
5768    // function declarator that is part of a function definition of
5769    // that function shall not have incomplete type.
5770    //
5771    // This is also C++ [dcl.fct]p6.
5772    if (!Param->isInvalidDecl() &&
5773        RequireCompleteType(Param->getLocation(), Param->getType(),
5774                            diag::err_typecheck_decl_incomplete_type)) {
5775      Param->setInvalidDecl();
5776      HasInvalidParm = true;
5777    }
5778
5779    // C99 6.9.1p5: If the declarator includes a parameter type list, the
5780    // declaration of each parameter shall include an identifier.
5781    if (CheckParameterNames &&
5782        Param->getIdentifier() == 0 &&
5783        !Param->isImplicit() &&
5784        !getLangOpts().CPlusPlus)
5785      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
5786
5787    // C99 6.7.5.3p12:
5788    //   If the function declarator is not part of a definition of that
5789    //   function, parameters may have incomplete type and may use the [*]
5790    //   notation in their sequences of declarator specifiers to specify
5791    //   variable length array types.
5792    QualType PType = Param->getOriginalType();
5793    while (const ArrayType *AT = Context.getAsArrayType(PType)) {
5794      if (AT->getSizeModifier() == ArrayType::Star) {
5795        // FIXME: This diagnostic should point the '[*]' if source-location
5796        // information is added for it.
5797        Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
5798        break;
5799      }
5800      PType= AT->getElementType();
5801    }
5802
5803    // MSVC destroys objects passed by value in the callee.  Therefore a
5804    // function definition which takes such a parameter must be able to call the
5805    // object's destructor.
5806    if (getLangOpts().CPlusPlus &&
5807        Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
5808      if (const RecordType *RT = Param->getType()->getAs<RecordType>())
5809        FinalizeVarWithDestructor(Param, RT);
5810    }
5811  }
5812
5813  return HasInvalidParm;
5814}
5815
5816/// CheckCastAlign - Implements -Wcast-align, which warns when a
5817/// pointer cast increases the alignment requirements.
5818void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5819  // This is actually a lot of work to potentially be doing on every
5820  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
5821  if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5822                                          TRange.getBegin())
5823        == DiagnosticsEngine::Ignored)
5824    return;
5825
5826  // Ignore dependent types.
5827  if (T->isDependentType() || Op->getType()->isDependentType())
5828    return;
5829
5830  // Require that the destination be a pointer type.
5831  const PointerType *DestPtr = T->getAs<PointerType>();
5832  if (!DestPtr) return;
5833
5834  // If the destination has alignment 1, we're done.
5835  QualType DestPointee = DestPtr->getPointeeType();
5836  if (DestPointee->isIncompleteType()) return;
5837  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5838  if (DestAlign.isOne()) return;
5839
5840  // Require that the source be a pointer type.
5841  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5842  if (!SrcPtr) return;
5843  QualType SrcPointee = SrcPtr->getPointeeType();
5844
5845  // Whitelist casts from cv void*.  We already implicitly
5846  // whitelisted casts to cv void*, since they have alignment 1.
5847  // Also whitelist casts involving incomplete types, which implicitly
5848  // includes 'void'.
5849  if (SrcPointee->isIncompleteType()) return;
5850
5851  CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5852  if (SrcAlign >= DestAlign) return;
5853
5854  Diag(TRange.getBegin(), diag::warn_cast_align)
5855    << Op->getType() << T
5856    << static_cast<unsigned>(SrcAlign.getQuantity())
5857    << static_cast<unsigned>(DestAlign.getQuantity())
5858    << TRange << Op->getSourceRange();
5859}
5860
5861static const Type* getElementType(const Expr *BaseExpr) {
5862  const Type* EltType = BaseExpr->getType().getTypePtr();
5863  if (EltType->isAnyPointerType())
5864    return EltType->getPointeeType().getTypePtr();
5865  else if (EltType->isArrayType())
5866    return EltType->getBaseElementTypeUnsafe();
5867  return EltType;
5868}
5869
5870/// \brief Check whether this array fits the idiom of a size-one tail padded
5871/// array member of a struct.
5872///
5873/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5874/// commonly used to emulate flexible arrays in C89 code.
5875static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5876                                    const NamedDecl *ND) {
5877  if (Size != 1 || !ND) return false;
5878
5879  const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5880  if (!FD) return false;
5881
5882  // Don't consider sizes resulting from macro expansions or template argument
5883  // substitution to form C89 tail-padded arrays.
5884
5885  TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
5886  while (TInfo) {
5887    TypeLoc TL = TInfo->getTypeLoc();
5888    // Look through typedefs.
5889    if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
5890      const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
5891      TInfo = TDL->getTypeSourceInfo();
5892      continue;
5893    }
5894    if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
5895      const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
5896      if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5897        return false;
5898    }
5899    break;
5900  }
5901
5902  const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
5903  if (!RD) return false;
5904  if (RD->isUnion()) return false;
5905  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5906    if (!CRD->isStandardLayout()) return false;
5907  }
5908
5909  // See if this is the last field decl in the record.
5910  const Decl *D = FD;
5911  while ((D = D->getNextDeclInContext()))
5912    if (isa<FieldDecl>(D))
5913      return false;
5914  return true;
5915}
5916
5917void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
5918                            const ArraySubscriptExpr *ASE,
5919                            bool AllowOnePastEnd, bool IndexNegated) {
5920  IndexExpr = IndexExpr->IgnoreParenImpCasts();
5921  if (IndexExpr->isValueDependent())
5922    return;
5923
5924  const Type *EffectiveType = getElementType(BaseExpr);
5925  BaseExpr = BaseExpr->IgnoreParenCasts();
5926  const ConstantArrayType *ArrayTy =
5927    Context.getAsConstantArrayType(BaseExpr->getType());
5928  if (!ArrayTy)
5929    return;
5930
5931  llvm::APSInt index;
5932  if (!IndexExpr->EvaluateAsInt(index, Context))
5933    return;
5934  if (IndexNegated)
5935    index = -index;
5936
5937  const NamedDecl *ND = NULL;
5938  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5939    ND = dyn_cast<NamedDecl>(DRE->getDecl());
5940  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
5941    ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
5942
5943  if (index.isUnsigned() || !index.isNegative()) {
5944    llvm::APInt size = ArrayTy->getSize();
5945    if (!size.isStrictlyPositive())
5946      return;
5947
5948    const Type* BaseType = getElementType(BaseExpr);
5949    if (BaseType != EffectiveType) {
5950      // Make sure we're comparing apples to apples when comparing index to size
5951      uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
5952      uint64_t array_typesize = Context.getTypeSize(BaseType);
5953      // Handle ptrarith_typesize being zero, such as when casting to void*
5954      if (!ptrarith_typesize) ptrarith_typesize = 1;
5955      if (ptrarith_typesize != array_typesize) {
5956        // There's a cast to a different size type involved
5957        uint64_t ratio = array_typesize / ptrarith_typesize;
5958        // TODO: Be smarter about handling cases where array_typesize is not a
5959        // multiple of ptrarith_typesize
5960        if (ptrarith_typesize * ratio == array_typesize)
5961          size *= llvm::APInt(size.getBitWidth(), ratio);
5962      }
5963    }
5964
5965    if (size.getBitWidth() > index.getBitWidth())
5966      index = index.zext(size.getBitWidth());
5967    else if (size.getBitWidth() < index.getBitWidth())
5968      size = size.zext(index.getBitWidth());
5969
5970    // For array subscripting the index must be less than size, but for pointer
5971    // arithmetic also allow the index (offset) to be equal to size since
5972    // computing the next address after the end of the array is legal and
5973    // commonly done e.g. in C++ iterators and range-based for loops.
5974    if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
5975      return;
5976
5977    // Also don't warn for arrays of size 1 which are members of some
5978    // structure. These are often used to approximate flexible arrays in C89
5979    // code.
5980    if (IsTailPaddedMemberArray(*this, size, ND))
5981      return;
5982
5983    // Suppress the warning if the subscript expression (as identified by the
5984    // ']' location) and the index expression are both from macro expansions
5985    // within a system header.
5986    if (ASE) {
5987      SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
5988          ASE->getRBracketLoc());
5989      if (SourceMgr.isInSystemHeader(RBracketLoc)) {
5990        SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
5991            IndexExpr->getLocStart());
5992        if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
5993          return;
5994      }
5995    }
5996
5997    unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
5998    if (ASE)
5999      DiagID = diag::warn_array_index_exceeds_bounds;
6000
6001    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6002                        PDiag(DiagID) << index.toString(10, true)
6003                          << size.toString(10, true)
6004                          << (unsigned)size.getLimitedValue(~0U)
6005                          << IndexExpr->getSourceRange());
6006  } else {
6007    unsigned DiagID = diag::warn_array_index_precedes_bounds;
6008    if (!ASE) {
6009      DiagID = diag::warn_ptr_arith_precedes_bounds;
6010      if (index.isNegative()) index = -index;
6011    }
6012
6013    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6014                        PDiag(DiagID) << index.toString(10, true)
6015                          << IndexExpr->getSourceRange());
6016  }
6017
6018  if (!ND) {
6019    // Try harder to find a NamedDecl to point at in the note.
6020    while (const ArraySubscriptExpr *ASE =
6021           dyn_cast<ArraySubscriptExpr>(BaseExpr))
6022      BaseExpr = ASE->getBase()->IgnoreParenCasts();
6023    if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6024      ND = dyn_cast<NamedDecl>(DRE->getDecl());
6025    if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6026      ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6027  }
6028
6029  if (ND)
6030    DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6031                        PDiag(diag::note_array_index_out_of_bounds)
6032                          << ND->getDeclName());
6033}
6034
6035void Sema::CheckArrayAccess(const Expr *expr) {
6036  int AllowOnePastEnd = 0;
6037  while (expr) {
6038    expr = expr->IgnoreParenImpCasts();
6039    switch (expr->getStmtClass()) {
6040      case Stmt::ArraySubscriptExprClass: {
6041        const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
6042        CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
6043                         AllowOnePastEnd > 0);
6044        return;
6045      }
6046      case Stmt::UnaryOperatorClass: {
6047        // Only unwrap the * and & unary operators
6048        const UnaryOperator *UO = cast<UnaryOperator>(expr);
6049        expr = UO->getSubExpr();
6050        switch (UO->getOpcode()) {
6051          case UO_AddrOf:
6052            AllowOnePastEnd++;
6053            break;
6054          case UO_Deref:
6055            AllowOnePastEnd--;
6056            break;
6057          default:
6058            return;
6059        }
6060        break;
6061      }
6062      case Stmt::ConditionalOperatorClass: {
6063        const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6064        if (const Expr *lhs = cond->getLHS())
6065          CheckArrayAccess(lhs);
6066        if (const Expr *rhs = cond->getRHS())
6067          CheckArrayAccess(rhs);
6068        return;
6069      }
6070      default:
6071        return;
6072    }
6073  }
6074}
6075
6076//===--- CHECK: Objective-C retain cycles ----------------------------------//
6077
6078namespace {
6079  struct RetainCycleOwner {
6080    RetainCycleOwner() : Variable(0), Indirect(false) {}
6081    VarDecl *Variable;
6082    SourceRange Range;
6083    SourceLocation Loc;
6084    bool Indirect;
6085
6086    void setLocsFrom(Expr *e) {
6087      Loc = e->getExprLoc();
6088      Range = e->getSourceRange();
6089    }
6090  };
6091}
6092
6093/// Consider whether capturing the given variable can possibly lead to
6094/// a retain cycle.
6095static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
6096  // In ARC, it's captured strongly iff the variable has __strong
6097  // lifetime.  In MRR, it's captured strongly if the variable is
6098  // __block and has an appropriate type.
6099  if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6100    return false;
6101
6102  owner.Variable = var;
6103  if (ref)
6104    owner.setLocsFrom(ref);
6105  return true;
6106}
6107
6108static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
6109  while (true) {
6110    e = e->IgnoreParens();
6111    if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6112      switch (cast->getCastKind()) {
6113      case CK_BitCast:
6114      case CK_LValueBitCast:
6115      case CK_LValueToRValue:
6116      case CK_ARCReclaimReturnedObject:
6117        e = cast->getSubExpr();
6118        continue;
6119
6120      default:
6121        return false;
6122      }
6123    }
6124
6125    if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6126      ObjCIvarDecl *ivar = ref->getDecl();
6127      if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6128        return false;
6129
6130      // Try to find a retain cycle in the base.
6131      if (!findRetainCycleOwner(S, ref->getBase(), owner))
6132        return false;
6133
6134      if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6135      owner.Indirect = true;
6136      return true;
6137    }
6138
6139    if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6140      VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6141      if (!var) return false;
6142      return considerVariable(var, ref, owner);
6143    }
6144
6145    if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6146      if (member->isArrow()) return false;
6147
6148      // Don't count this as an indirect ownership.
6149      e = member->getBase();
6150      continue;
6151    }
6152
6153    if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6154      // Only pay attention to pseudo-objects on property references.
6155      ObjCPropertyRefExpr *pre
6156        = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6157                                              ->IgnoreParens());
6158      if (!pre) return false;
6159      if (pre->isImplicitProperty()) return false;
6160      ObjCPropertyDecl *property = pre->getExplicitProperty();
6161      if (!property->isRetaining() &&
6162          !(property->getPropertyIvarDecl() &&
6163            property->getPropertyIvarDecl()->getType()
6164              .getObjCLifetime() == Qualifiers::OCL_Strong))
6165          return false;
6166
6167      owner.Indirect = true;
6168      if (pre->isSuperReceiver()) {
6169        owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6170        if (!owner.Variable)
6171          return false;
6172        owner.Loc = pre->getLocation();
6173        owner.Range = pre->getSourceRange();
6174        return true;
6175      }
6176      e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6177                              ->getSourceExpr());
6178      continue;
6179    }
6180
6181    // Array ivars?
6182
6183    return false;
6184  }
6185}
6186
6187namespace {
6188  struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6189    FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6190      : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6191        Variable(variable), Capturer(0) {}
6192
6193    VarDecl *Variable;
6194    Expr *Capturer;
6195
6196    void VisitDeclRefExpr(DeclRefExpr *ref) {
6197      if (ref->getDecl() == Variable && !Capturer)
6198        Capturer = ref;
6199    }
6200
6201    void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6202      if (Capturer) return;
6203      Visit(ref->getBase());
6204      if (Capturer && ref->isFreeIvar())
6205        Capturer = ref;
6206    }
6207
6208    void VisitBlockExpr(BlockExpr *block) {
6209      // Look inside nested blocks
6210      if (block->getBlockDecl()->capturesVariable(Variable))
6211        Visit(block->getBlockDecl()->getBody());
6212    }
6213
6214    void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6215      if (Capturer) return;
6216      if (OVE->getSourceExpr())
6217        Visit(OVE->getSourceExpr());
6218    }
6219  };
6220}
6221
6222/// Check whether the given argument is a block which captures a
6223/// variable.
6224static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6225  assert(owner.Variable && owner.Loc.isValid());
6226
6227  e = e->IgnoreParenCasts();
6228
6229  // Look through [^{...} copy] and Block_copy(^{...}).
6230  if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6231    Selector Cmd = ME->getSelector();
6232    if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6233      e = ME->getInstanceReceiver();
6234      if (!e)
6235        return 0;
6236      e = e->IgnoreParenCasts();
6237    }
6238  } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6239    if (CE->getNumArgs() == 1) {
6240      FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
6241      if (Fn) {
6242        const IdentifierInfo *FnI = Fn->getIdentifier();
6243        if (FnI && FnI->isStr("_Block_copy")) {
6244          e = CE->getArg(0)->IgnoreParenCasts();
6245        }
6246      }
6247    }
6248  }
6249
6250  BlockExpr *block = dyn_cast<BlockExpr>(e);
6251  if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6252    return 0;
6253
6254  FindCaptureVisitor visitor(S.Context, owner.Variable);
6255  visitor.Visit(block->getBlockDecl()->getBody());
6256  return visitor.Capturer;
6257}
6258
6259static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6260                                RetainCycleOwner &owner) {
6261  assert(capturer);
6262  assert(owner.Variable && owner.Loc.isValid());
6263
6264  S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6265    << owner.Variable << capturer->getSourceRange();
6266  S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6267    << owner.Indirect << owner.Range;
6268}
6269
6270/// Check for a keyword selector that starts with the word 'add' or
6271/// 'set'.
6272static bool isSetterLikeSelector(Selector sel) {
6273  if (sel.isUnarySelector()) return false;
6274
6275  StringRef str = sel.getNameForSlot(0);
6276  while (!str.empty() && str.front() == '_') str = str.substr(1);
6277  if (str.startswith("set"))
6278    str = str.substr(3);
6279  else if (str.startswith("add")) {
6280    // Specially whitelist 'addOperationWithBlock:'.
6281    if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6282      return false;
6283    str = str.substr(3);
6284  }
6285  else
6286    return false;
6287
6288  if (str.empty()) return true;
6289  return !isLowercase(str.front());
6290}
6291
6292/// Check a message send to see if it's likely to cause a retain cycle.
6293void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6294  // Only check instance methods whose selector looks like a setter.
6295  if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6296    return;
6297
6298  // Try to find a variable that the receiver is strongly owned by.
6299  RetainCycleOwner owner;
6300  if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
6301    if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
6302      return;
6303  } else {
6304    assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6305    owner.Variable = getCurMethodDecl()->getSelfDecl();
6306    owner.Loc = msg->getSuperLoc();
6307    owner.Range = msg->getSuperLoc();
6308  }
6309
6310  // Check whether the receiver is captured by any of the arguments.
6311  for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6312    if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6313      return diagnoseRetainCycle(*this, capturer, owner);
6314}
6315
6316/// Check a property assign to see if it's likely to cause a retain cycle.
6317void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6318  RetainCycleOwner owner;
6319  if (!findRetainCycleOwner(*this, receiver, owner))
6320    return;
6321
6322  if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6323    diagnoseRetainCycle(*this, capturer, owner);
6324}
6325
6326void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6327  RetainCycleOwner Owner;
6328  if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6329    return;
6330
6331  // Because we don't have an expression for the variable, we have to set the
6332  // location explicitly here.
6333  Owner.Loc = Var->getLocation();
6334  Owner.Range = Var->getSourceRange();
6335
6336  if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6337    diagnoseRetainCycle(*this, Capturer, Owner);
6338}
6339
6340static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6341                                     Expr *RHS, bool isProperty) {
6342  // Check if RHS is an Objective-C object literal, which also can get
6343  // immediately zapped in a weak reference.  Note that we explicitly
6344  // allow ObjCStringLiterals, since those are designed to never really die.
6345  RHS = RHS->IgnoreParenImpCasts();
6346
6347  // This enum needs to match with the 'select' in
6348  // warn_objc_arc_literal_assign (off-by-1).
6349  Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6350  if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6351    return false;
6352
6353  S.Diag(Loc, diag::warn_arc_literal_assign)
6354    << (unsigned) Kind
6355    << (isProperty ? 0 : 1)
6356    << RHS->getSourceRange();
6357
6358  return true;
6359}
6360
6361static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6362                                    Qualifiers::ObjCLifetime LT,
6363                                    Expr *RHS, bool isProperty) {
6364  // Strip off any implicit cast added to get to the one ARC-specific.
6365  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6366    if (cast->getCastKind() == CK_ARCConsumeObject) {
6367      S.Diag(Loc, diag::warn_arc_retained_assign)
6368        << (LT == Qualifiers::OCL_ExplicitNone)
6369        << (isProperty ? 0 : 1)
6370        << RHS->getSourceRange();
6371      return true;
6372    }
6373    RHS = cast->getSubExpr();
6374  }
6375
6376  if (LT == Qualifiers::OCL_Weak &&
6377      checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6378    return true;
6379
6380  return false;
6381}
6382
6383bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6384                              QualType LHS, Expr *RHS) {
6385  Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6386
6387  if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6388    return false;
6389
6390  if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6391    return true;
6392
6393  return false;
6394}
6395
6396void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6397                              Expr *LHS, Expr *RHS) {
6398  QualType LHSType;
6399  // PropertyRef on LHS type need be directly obtained from
6400  // its declaration as it has a PsuedoType.
6401  ObjCPropertyRefExpr *PRE
6402    = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6403  if (PRE && !PRE->isImplicitProperty()) {
6404    const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6405    if (PD)
6406      LHSType = PD->getType();
6407  }
6408
6409  if (LHSType.isNull())
6410    LHSType = LHS->getType();
6411
6412  Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6413
6414  if (LT == Qualifiers::OCL_Weak) {
6415    DiagnosticsEngine::Level Level =
6416      Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6417    if (Level != DiagnosticsEngine::Ignored)
6418      getCurFunction()->markSafeWeakUse(LHS);
6419  }
6420
6421  if (checkUnsafeAssigns(Loc, LHSType, RHS))
6422    return;
6423
6424  // FIXME. Check for other life times.
6425  if (LT != Qualifiers::OCL_None)
6426    return;
6427
6428  if (PRE) {
6429    if (PRE->isImplicitProperty())
6430      return;
6431    const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6432    if (!PD)
6433      return;
6434
6435    unsigned Attributes = PD->getPropertyAttributes();
6436    if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
6437      // when 'assign' attribute was not explicitly specified
6438      // by user, ignore it and rely on property type itself
6439      // for lifetime info.
6440      unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6441      if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6442          LHSType->isObjCRetainableType())
6443        return;
6444
6445      while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6446        if (cast->getCastKind() == CK_ARCConsumeObject) {
6447          Diag(Loc, diag::warn_arc_retained_property_assign)
6448          << RHS->getSourceRange();
6449          return;
6450        }
6451        RHS = cast->getSubExpr();
6452      }
6453    }
6454    else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
6455      if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6456        return;
6457    }
6458  }
6459}
6460
6461//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6462
6463namespace {
6464bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6465                                 SourceLocation StmtLoc,
6466                                 const NullStmt *Body) {
6467  // Do not warn if the body is a macro that expands to nothing, e.g:
6468  //
6469  // #define CALL(x)
6470  // if (condition)
6471  //   CALL(0);
6472  //
6473  if (Body->hasLeadingEmptyMacro())
6474    return false;
6475
6476  // Get line numbers of statement and body.
6477  bool StmtLineInvalid;
6478  unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6479                                                      &StmtLineInvalid);
6480  if (StmtLineInvalid)
6481    return false;
6482
6483  bool BodyLineInvalid;
6484  unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6485                                                      &BodyLineInvalid);
6486  if (BodyLineInvalid)
6487    return false;
6488
6489  // Warn if null statement and body are on the same line.
6490  if (StmtLine != BodyLine)
6491    return false;
6492
6493  return true;
6494}
6495} // Unnamed namespace
6496
6497void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6498                                 const Stmt *Body,
6499                                 unsigned DiagID) {
6500  // Since this is a syntactic check, don't emit diagnostic for template
6501  // instantiations, this just adds noise.
6502  if (CurrentInstantiationScope)
6503    return;
6504
6505  // The body should be a null statement.
6506  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6507  if (!NBody)
6508    return;
6509
6510  // Do the usual checks.
6511  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6512    return;
6513
6514  Diag(NBody->getSemiLoc(), DiagID);
6515  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6516}
6517
6518void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6519                                 const Stmt *PossibleBody) {
6520  assert(!CurrentInstantiationScope); // Ensured by caller
6521
6522  SourceLocation StmtLoc;
6523  const Stmt *Body;
6524  unsigned DiagID;
6525  if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6526    StmtLoc = FS->getRParenLoc();
6527    Body = FS->getBody();
6528    DiagID = diag::warn_empty_for_body;
6529  } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6530    StmtLoc = WS->getCond()->getSourceRange().getEnd();
6531    Body = WS->getBody();
6532    DiagID = diag::warn_empty_while_body;
6533  } else
6534    return; // Neither `for' nor `while'.
6535
6536  // The body should be a null statement.
6537  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6538  if (!NBody)
6539    return;
6540
6541  // Skip expensive checks if diagnostic is disabled.
6542  if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6543          DiagnosticsEngine::Ignored)
6544    return;
6545
6546  // Do the usual checks.
6547  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6548    return;
6549
6550  // `for(...);' and `while(...);' are popular idioms, so in order to keep
6551  // noise level low, emit diagnostics only if for/while is followed by a
6552  // CompoundStmt, e.g.:
6553  //    for (int i = 0; i < n; i++);
6554  //    {
6555  //      a(i);
6556  //    }
6557  // or if for/while is followed by a statement with more indentation
6558  // than for/while itself:
6559  //    for (int i = 0; i < n; i++);
6560  //      a(i);
6561  bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6562  if (!ProbableTypo) {
6563    bool BodyColInvalid;
6564    unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6565                             PossibleBody->getLocStart(),
6566                             &BodyColInvalid);
6567    if (BodyColInvalid)
6568      return;
6569
6570    bool StmtColInvalid;
6571    unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6572                             S->getLocStart(),
6573                             &StmtColInvalid);
6574    if (StmtColInvalid)
6575      return;
6576
6577    if (BodyCol > StmtCol)
6578      ProbableTypo = true;
6579  }
6580
6581  if (ProbableTypo) {
6582    Diag(NBody->getSemiLoc(), DiagID);
6583    Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6584  }
6585}
6586
6587//===--- Layout compatibility ----------------------------------------------//
6588
6589namespace {
6590
6591bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6592
6593/// \brief Check if two enumeration types are layout-compatible.
6594bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6595  // C++11 [dcl.enum] p8:
6596  // Two enumeration types are layout-compatible if they have the same
6597  // underlying type.
6598  return ED1->isComplete() && ED2->isComplete() &&
6599         C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6600}
6601
6602/// \brief Check if two fields are layout-compatible.
6603bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6604  if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6605    return false;
6606
6607  if (Field1->isBitField() != Field2->isBitField())
6608    return false;
6609
6610  if (Field1->isBitField()) {
6611    // Make sure that the bit-fields are the same length.
6612    unsigned Bits1 = Field1->getBitWidthValue(C);
6613    unsigned Bits2 = Field2->getBitWidthValue(C);
6614
6615    if (Bits1 != Bits2)
6616      return false;
6617  }
6618
6619  return true;
6620}
6621
6622/// \brief Check if two standard-layout structs are layout-compatible.
6623/// (C++11 [class.mem] p17)
6624bool isLayoutCompatibleStruct(ASTContext &C,
6625                              RecordDecl *RD1,
6626                              RecordDecl *RD2) {
6627  // If both records are C++ classes, check that base classes match.
6628  if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6629    // If one of records is a CXXRecordDecl we are in C++ mode,
6630    // thus the other one is a CXXRecordDecl, too.
6631    const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6632    // Check number of base classes.
6633    if (D1CXX->getNumBases() != D2CXX->getNumBases())
6634      return false;
6635
6636    // Check the base classes.
6637    for (CXXRecordDecl::base_class_const_iterator
6638               Base1 = D1CXX->bases_begin(),
6639           BaseEnd1 = D1CXX->bases_end(),
6640              Base2 = D2CXX->bases_begin();
6641         Base1 != BaseEnd1;
6642         ++Base1, ++Base2) {
6643      if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6644        return false;
6645    }
6646  } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6647    // If only RD2 is a C++ class, it should have zero base classes.
6648    if (D2CXX->getNumBases() > 0)
6649      return false;
6650  }
6651
6652  // Check the fields.
6653  RecordDecl::field_iterator Field2 = RD2->field_begin(),
6654                             Field2End = RD2->field_end(),
6655                             Field1 = RD1->field_begin(),
6656                             Field1End = RD1->field_end();
6657  for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6658    if (!isLayoutCompatible(C, *Field1, *Field2))
6659      return false;
6660  }
6661  if (Field1 != Field1End || Field2 != Field2End)
6662    return false;
6663
6664  return true;
6665}
6666
6667/// \brief Check if two standard-layout unions are layout-compatible.
6668/// (C++11 [class.mem] p18)
6669bool isLayoutCompatibleUnion(ASTContext &C,
6670                             RecordDecl *RD1,
6671                             RecordDecl *RD2) {
6672  llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6673  for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6674                                  Field2End = RD2->field_end();
6675       Field2 != Field2End; ++Field2) {
6676    UnmatchedFields.insert(*Field2);
6677  }
6678
6679  for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6680                                  Field1End = RD1->field_end();
6681       Field1 != Field1End; ++Field1) {
6682    llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6683        I = UnmatchedFields.begin(),
6684        E = UnmatchedFields.end();
6685
6686    for ( ; I != E; ++I) {
6687      if (isLayoutCompatible(C, *Field1, *I)) {
6688        bool Result = UnmatchedFields.erase(*I);
6689        (void) Result;
6690        assert(Result);
6691        break;
6692      }
6693    }
6694    if (I == E)
6695      return false;
6696  }
6697
6698  return UnmatchedFields.empty();
6699}
6700
6701bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6702  if (RD1->isUnion() != RD2->isUnion())
6703    return false;
6704
6705  if (RD1->isUnion())
6706    return isLayoutCompatibleUnion(C, RD1, RD2);
6707  else
6708    return isLayoutCompatibleStruct(C, RD1, RD2);
6709}
6710
6711/// \brief Check if two types are layout-compatible in C++11 sense.
6712bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6713  if (T1.isNull() || T2.isNull())
6714    return false;
6715
6716  // C++11 [basic.types] p11:
6717  // If two types T1 and T2 are the same type, then T1 and T2 are
6718  // layout-compatible types.
6719  if (C.hasSameType(T1, T2))
6720    return true;
6721
6722  T1 = T1.getCanonicalType().getUnqualifiedType();
6723  T2 = T2.getCanonicalType().getUnqualifiedType();
6724
6725  const Type::TypeClass TC1 = T1->getTypeClass();
6726  const Type::TypeClass TC2 = T2->getTypeClass();
6727
6728  if (TC1 != TC2)
6729    return false;
6730
6731  if (TC1 == Type::Enum) {
6732    return isLayoutCompatible(C,
6733                              cast<EnumType>(T1)->getDecl(),
6734                              cast<EnumType>(T2)->getDecl());
6735  } else if (TC1 == Type::Record) {
6736    if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6737      return false;
6738
6739    return isLayoutCompatible(C,
6740                              cast<RecordType>(T1)->getDecl(),
6741                              cast<RecordType>(T2)->getDecl());
6742  }
6743
6744  return false;
6745}
6746}
6747
6748//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6749
6750namespace {
6751/// \brief Given a type tag expression find the type tag itself.
6752///
6753/// \param TypeExpr Type tag expression, as it appears in user's code.
6754///
6755/// \param VD Declaration of an identifier that appears in a type tag.
6756///
6757/// \param MagicValue Type tag magic value.
6758bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6759                     const ValueDecl **VD, uint64_t *MagicValue) {
6760  while(true) {
6761    if (!TypeExpr)
6762      return false;
6763
6764    TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6765
6766    switch (TypeExpr->getStmtClass()) {
6767    case Stmt::UnaryOperatorClass: {
6768      const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6769      if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6770        TypeExpr = UO->getSubExpr();
6771        continue;
6772      }
6773      return false;
6774    }
6775
6776    case Stmt::DeclRefExprClass: {
6777      const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6778      *VD = DRE->getDecl();
6779      return true;
6780    }
6781
6782    case Stmt::IntegerLiteralClass: {
6783      const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6784      llvm::APInt MagicValueAPInt = IL->getValue();
6785      if (MagicValueAPInt.getActiveBits() <= 64) {
6786        *MagicValue = MagicValueAPInt.getZExtValue();
6787        return true;
6788      } else
6789        return false;
6790    }
6791
6792    case Stmt::BinaryConditionalOperatorClass:
6793    case Stmt::ConditionalOperatorClass: {
6794      const AbstractConditionalOperator *ACO =
6795          cast<AbstractConditionalOperator>(TypeExpr);
6796      bool Result;
6797      if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6798        if (Result)
6799          TypeExpr = ACO->getTrueExpr();
6800        else
6801          TypeExpr = ACO->getFalseExpr();
6802        continue;
6803      }
6804      return false;
6805    }
6806
6807    case Stmt::BinaryOperatorClass: {
6808      const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6809      if (BO->getOpcode() == BO_Comma) {
6810        TypeExpr = BO->getRHS();
6811        continue;
6812      }
6813      return false;
6814    }
6815
6816    default:
6817      return false;
6818    }
6819  }
6820}
6821
6822/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6823///
6824/// \param TypeExpr Expression that specifies a type tag.
6825///
6826/// \param MagicValues Registered magic values.
6827///
6828/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6829///        kind.
6830///
6831/// \param TypeInfo Information about the corresponding C type.
6832///
6833/// \returns true if the corresponding C type was found.
6834bool GetMatchingCType(
6835        const IdentifierInfo *ArgumentKind,
6836        const Expr *TypeExpr, const ASTContext &Ctx,
6837        const llvm::DenseMap<Sema::TypeTagMagicValue,
6838                             Sema::TypeTagData> *MagicValues,
6839        bool &FoundWrongKind,
6840        Sema::TypeTagData &TypeInfo) {
6841  FoundWrongKind = false;
6842
6843  // Variable declaration that has type_tag_for_datatype attribute.
6844  const ValueDecl *VD = NULL;
6845
6846  uint64_t MagicValue;
6847
6848  if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6849    return false;
6850
6851  if (VD) {
6852    for (specific_attr_iterator<TypeTagForDatatypeAttr>
6853             I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6854             E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6855         I != E; ++I) {
6856      if (I->getArgumentKind() != ArgumentKind) {
6857        FoundWrongKind = true;
6858        return false;
6859      }
6860      TypeInfo.Type = I->getMatchingCType();
6861      TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6862      TypeInfo.MustBeNull = I->getMustBeNull();
6863      return true;
6864    }
6865    return false;
6866  }
6867
6868  if (!MagicValues)
6869    return false;
6870
6871  llvm::DenseMap<Sema::TypeTagMagicValue,
6872                 Sema::TypeTagData>::const_iterator I =
6873      MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6874  if (I == MagicValues->end())
6875    return false;
6876
6877  TypeInfo = I->second;
6878  return true;
6879}
6880} // unnamed namespace
6881
6882void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6883                                      uint64_t MagicValue, QualType Type,
6884                                      bool LayoutCompatible,
6885                                      bool MustBeNull) {
6886  if (!TypeTagForDatatypeMagicValues)
6887    TypeTagForDatatypeMagicValues.reset(
6888        new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6889
6890  TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6891  (*TypeTagForDatatypeMagicValues)[Magic] =
6892      TypeTagData(Type, LayoutCompatible, MustBeNull);
6893}
6894
6895namespace {
6896bool IsSameCharType(QualType T1, QualType T2) {
6897  const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6898  if (!BT1)
6899    return false;
6900
6901  const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6902  if (!BT2)
6903    return false;
6904
6905  BuiltinType::Kind T1Kind = BT1->getKind();
6906  BuiltinType::Kind T2Kind = BT2->getKind();
6907
6908  return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
6909         (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
6910         (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6911         (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6912}
6913} // unnamed namespace
6914
6915void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6916                                    const Expr * const *ExprArgs) {
6917  const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6918  bool IsPointerAttr = Attr->getIsPointer();
6919
6920  const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6921  bool FoundWrongKind;
6922  TypeTagData TypeInfo;
6923  if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6924                        TypeTagForDatatypeMagicValues.get(),
6925                        FoundWrongKind, TypeInfo)) {
6926    if (FoundWrongKind)
6927      Diag(TypeTagExpr->getExprLoc(),
6928           diag::warn_type_tag_for_datatype_wrong_kind)
6929        << TypeTagExpr->getSourceRange();
6930    return;
6931  }
6932
6933  const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6934  if (IsPointerAttr) {
6935    // Skip implicit cast of pointer to `void *' (as a function argument).
6936    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
6937      if (ICE->getType()->isVoidPointerType() &&
6938          ICE->getCastKind() == CK_BitCast)
6939        ArgumentExpr = ICE->getSubExpr();
6940  }
6941  QualType ArgumentType = ArgumentExpr->getType();
6942
6943  // Passing a `void*' pointer shouldn't trigger a warning.
6944  if (IsPointerAttr && ArgumentType->isVoidPointerType())
6945    return;
6946
6947  if (TypeInfo.MustBeNull) {
6948    // Type tag with matching void type requires a null pointer.
6949    if (!ArgumentExpr->isNullPointerConstant(Context,
6950                                             Expr::NPC_ValueDependentIsNotNull)) {
6951      Diag(ArgumentExpr->getExprLoc(),
6952           diag::warn_type_safety_null_pointer_required)
6953          << ArgumentKind->getName()
6954          << ArgumentExpr->getSourceRange()
6955          << TypeTagExpr->getSourceRange();
6956    }
6957    return;
6958  }
6959
6960  QualType RequiredType = TypeInfo.Type;
6961  if (IsPointerAttr)
6962    RequiredType = Context.getPointerType(RequiredType);
6963
6964  bool mismatch = false;
6965  if (!TypeInfo.LayoutCompatible) {
6966    mismatch = !Context.hasSameType(ArgumentType, RequiredType);
6967
6968    // C++11 [basic.fundamental] p1:
6969    // Plain char, signed char, and unsigned char are three distinct types.
6970    //
6971    // But we treat plain `char' as equivalent to `signed char' or `unsigned
6972    // char' depending on the current char signedness mode.
6973    if (mismatch)
6974      if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
6975                                           RequiredType->getPointeeType())) ||
6976          (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
6977        mismatch = false;
6978  } else
6979    if (IsPointerAttr)
6980      mismatch = !isLayoutCompatible(Context,
6981                                     ArgumentType->getPointeeType(),
6982                                     RequiredType->getPointeeType());
6983    else
6984      mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
6985
6986  if (mismatch)
6987    Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
6988        << ArgumentType << ArgumentKind->getName()
6989        << TypeInfo.LayoutCompatible << RequiredType
6990        << ArgumentExpr->getSourceRange()
6991        << TypeTagExpr->getSourceRange();
6992}
6993