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