clang 24.0.0git
FormatString.cpp
Go to the documentation of this file.
1// FormatString.cpp - Common stuff for handling printf/scanf formats -*- C++ -*-
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Shared details for processing format strings of printf and scanf
10// (and friends).
11//
12//===----------------------------------------------------------------------===//
13
14#include "FormatStringParsing.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Support/ConvertUTF.h"
19#include <optional>
20
28using namespace clang;
29
30// Key function to FormatStringHandler.
32
33//===----------------------------------------------------------------------===//
34// Functions for parsing format strings components in both printf and
35// scanf format strings.
36//===----------------------------------------------------------------------===//
37
39 const char *E) const {
40 const char *I = Beg;
41 UpdateOnReturn<const char *> UpdateBeg(Beg, I);
42
43 unsigned accumulator = 0;
44 bool hasDigits = false;
45
46 for (; I != E; ++I) {
47 char c = *I;
48 if (c >= '0' && c <= '9') {
49 hasDigits = true;
50 accumulator = (accumulator * 10) + (c - '0');
51 continue;
52 }
53
54 if (hasDigits)
55 return OptionalAmount(OptionalAmount::Constant, accumulator, Beg, I - Beg,
56 false);
57
58 break;
59 }
60
61 return OptionalAmount();
62}
63
64bool FormatStringParser::parseWidthModifier(const char *&I, const char *E,
65 unsigned &BitWidth,
66 unsigned &ModifierLength) const {
67 StringRef W = StringRef(I, E - I).take_while(llvm::isDigit);
68 if (W.empty() || W.front() == '0')
69 return false;
70
71 if (W.getAsInteger(10, BitWidth))
72 return false;
73
74 I = W.end();
75 ModifierLength += W.size();
76
77 return true;
78}
79
81FormatStringParser::parseNonPositionAmount(const char *&Beg, const char *E,
82 unsigned &argIndex) const {
83 if (*Beg == '*') {
84 ++Beg;
85 return OptionalAmount(OptionalAmount::Arg, argIndex++, Beg, 0, false);
86 }
87
88 return parseAmount(Beg, E);
89}
90
92FormatStringParser::parsePositionAmount(const char *Start, const char *&Beg,
93 const char *E,
94 PositionContext p) const {
95 if (*Beg == '*') {
96 const char *I = Beg + 1;
97 const OptionalAmount &Amt = parseAmount(I, E);
98
100 H.HandleInvalidPosition(Beg, I - Beg, p);
101 return OptionalAmount(false);
102 }
103
104 if (I == E) {
105 // No more characters left?
106 H.HandleIncompleteSpecifier(Start, E - Start);
107 return OptionalAmount(false);
108 }
109
111
112 if (*I == '$') {
113 // Handle positional arguments
114
115 // Special case: '*0$', since this is an easy mistake.
116 if (Amt.getConstantAmount() == 0) {
117 H.HandleZeroPosition(Beg, I - Beg + 1);
118 return OptionalAmount(false);
119 }
120
121 const char *Tmp = Beg;
122 Beg = ++I;
123
125 Tmp, 0, true);
126 }
127
128 H.HandleInvalidPosition(Beg, I - Beg, p);
129 return OptionalAmount(false);
130 }
131
132 return parseAmount(Beg, E);
133}
134
136 const char *&Beg, const char *E,
137 unsigned *argIndex) const {
138 // FIXME: Support negative field widths.
139 if (argIndex) {
140 CS.setFieldWidth(parseNonPositionAmount(Beg, E, *argIndex));
141 } else {
144
145 if (Amt.isInvalid())
146 return true;
147 CS.setFieldWidth(Amt);
148 }
149 return false;
150}
151
153 const char *Start, const char *&Beg,
154 const char *E) const {
155 const char *I = Beg;
156
157 const OptionalAmount &Amt = parseAmount(I, E);
158
159 if (I == E) {
160 // No more characters left?
161 H.HandleIncompleteSpecifier(Start, E - Start);
162 return true;
163 }
164
165 if (Amt.getHowSpecified() == OptionalAmount::Constant && *(I++) == '$') {
166 // Warn that positional arguments are non-standard.
167 H.HandlePosition(Start, I - Start);
168
169 // Special case: '%0$', since this is an easy mistake.
170 if (Amt.getConstantAmount() == 0) {
171 H.HandleZeroPosition(Start, I - Start);
172 return true;
173 }
174
175 FS.setArgIndex(Amt.getConstantAmount() - 1);
177 // Update the caller's pointer if we decided to consume
178 // these characters.
179 Beg = I;
180 return false;
181 }
182
183 return false;
184}
185
187 const char *&I,
188 const char *E) const {
189 if (!LO.OpenCL)
190 return false;
191
192 const char *Start = I;
193 if (*I == 'v') {
194 ++I;
195
196 if (I == E) {
197 H.HandleIncompleteSpecifier(Start, E - Start);
198 return true;
199 }
200
201 OptionalAmount NumElts = parseAmount(I, E);
202 if (NumElts.getHowSpecified() != OptionalAmount::Constant) {
203 H.HandleIncompleteSpecifier(Start, E - Start);
204 return true;
205 }
206
207 FS.setVectorNumElts(NumElts);
208 }
209
210 return false;
211}
212
214 const char *&I,
215 const char *E) const {
217 const char *lmPosition = I;
218 switch (*I) {
219 default:
220 return false;
221 case 'h':
222 ++I;
223 if (I != E && *I == 'h') {
224 ++I;
225 lmKind = LengthModifier::AsChar;
226 } else if (I != E && *I == 'l' && LO.OpenCL) {
227 ++I;
229 } else {
231 }
232 break;
233 case 'l':
234 ++I;
235 if (I != E && *I == 'l') {
236 ++I;
238 } else {
239 lmKind = LengthModifier::AsLong;
240 }
241 break;
242 case 'j':
244 ++I;
245 break;
246 case 'z':
248 ++I;
249 break;
250 case 't':
252 ++I;
253 break;
254 case 'L':
256 ++I;
257 break;
258 case 'q':
259 lmKind = LengthModifier::AsQuad;
260 ++I;
261 break;
262 case 'a':
263 if (IsScanf && !LO.C99 && !LO.CPlusPlus11) {
264 // For scanf in C90, look at the next character to see if this should
265 // be parsed as the GNU extension 'a' length modifier. If not, this
266 // will be parsed as a conversion specifier.
267 ++I;
268 if (I != E && (*I == 's' || *I == 'S' || *I == '[')) {
270 break;
271 }
272 --I;
273 }
274 return false;
275 case 'm':
276 if (IsScanf) {
278 ++I;
279 break;
280 }
281 return false;
282 // printf: AsInt64, AsInt32, AsInt3264
283 // scanf: AsInt64
284 case 'I':
285 if (I + 1 != E && I + 2 != E) {
286 if (I[1] == '6' && I[2] == '4') {
287 I += 3;
289 break;
290 }
291 if (IsScanf)
292 return false;
293
294 if (I[1] == '3' && I[2] == '2') {
295 I += 3;
297 break;
298 }
299 }
300 ++I;
302 break;
303 case 'H':
304 if (LO.C23) {
306 ++I;
307 break;
308 }
309 return false;
310 case 'D':
311 if (LO.C23) {
312 ++I;
313 if (I != E && *I == 'D') {
314 ++I;
316 } else {
318 }
319 break;
320 }
321 return false;
322 case 'w':
323 if (LO.C23) {
324 const char *WidthModifier = I + 1;
325 unsigned BitWidth = 0;
326 unsigned ModifierLength = 1;
327
329 if (WidthModifier != E && *WidthModifier == 'f') {
330 WidthModifier = I + 2;
331 ModifierLength = 2;
332 WidthKind = LengthModifier::AsFastIntN;
333 }
334
335 if (parseWidthModifier(WidthModifier, E, BitWidth, ModifierLength)) {
336 I = WidthModifier;
338 LengthModifier(lmPosition, WidthKind, BitWidth, ModifierLength));
339 return true;
340 }
341 }
342 lmKind = LengthModifier::AsWide;
343 ++I;
344 break;
345 }
346 LengthModifier lm(lmPosition, lmKind);
347 FS.setLengthModifier(lm);
348 return true;
349}
350
351bool FormatStringParser::parseUTF8InvalidSpecifier(const char *SpecifierBegin,
352 const char *FmtStrEnd,
353 unsigned &Len) const {
354 if (SpecifierBegin + 1 >= FmtStrEnd)
355 return false;
356
357 const llvm::UTF8 *SB =
358 reinterpret_cast<const llvm::UTF8 *>(SpecifierBegin + 1);
359 const llvm::UTF8 *SE = reinterpret_cast<const llvm::UTF8 *>(FmtStrEnd);
360 const char FirstByte = *SB;
361
362 // If the invalid specifier is a multibyte UTF-8 string, return the
363 // total length accordingly so that the conversion specifier can be
364 // properly updated to reflect a complete UTF-8 specifier.
365 unsigned NumBytes = llvm::getNumBytesForUTF8(FirstByte);
366 if (NumBytes == 1)
367 return false;
368 if (SB + NumBytes > SE)
369 return false;
370
371 Len = NumBytes + 1;
372 return true;
373}
374
375//===----------------------------------------------------------------------===//
376// Methods on ArgType.
377//===----------------------------------------------------------------------===//
378
381 if (!Ctx.getLangOpts().C99 && !Ctx.getLangOpts().CPlusPlus)
382 return false;
383 for (/**/; const auto *TT = QT->getAs<TypedefType>(); QT = TT->desugar()) {
384 const auto *TD = TT->getDecl();
385 const auto *DC = TT->getDecl()->getDeclContext();
386 if (DC->isTranslationUnit() || DC->isStdNamespace()) {
387 StringRef Name = TD->getIdentifier()->getName();
388 if (Name == "size_t") {
390 return true;
391 } else if (Name == "ssize_t" /*Not C99, but common in Unix.*/) {
393 return true;
394 } else if (Name == "ptrdiff_t") {
396 return true;
397 } else if (Name == "intmax_t") {
399 return true;
400 } else if (Name == "uintmax_t") {
402 return true;
403 }
404 }
405 }
406 if (const auto *PST = QT->getAs<PredefinedSugarType>()) {
407 using Kind = PredefinedSugarType::Kind;
408 switch (PST->getKind()) {
409 case Kind::SizeT:
410 case Kind::SignedSizeT:
412 return true;
413 case Kind::PtrdiffT:
415 return true;
416 }
417 llvm_unreachable("unexpected kind");
418 }
419 return false;
420}
421
422// Check whether T and E are compatible size_t/ptrdiff_t types. E must be
423// consistent with LE.
424// T is the type of the actual expression in the code to be checked, and E is
425// the expected type parsed from the format string.
429
430 if (!T->isIntegerType() || T->isBooleanType())
431 return MatchKind::NoMatch;
432
433 if (C.hasSameType(T, E))
434 return MatchKind::Match;
435
436 if (C.getCorrespondingSignedType(T.getCanonicalType()) !=
437 C.getCorrespondingSignedType(E.getCanonicalType()))
438 return MatchKind::NoMatch;
439
440 return MatchKind::NoMatchSignedness;
441}
442
445 // When using the format attribute in C++, you can receive a function or an
446 // array that will necessarily decay to a pointer when passed to the final
447 // format consumer. Apply decay before type comparison.
448 if (argTy->canDecayToPointerType())
449 argTy = C.getDecayedType(argTy);
450
451 if (Ptr) {
452 // It has to be a pointer.
453 const PointerType *PT = argTy->getAs<PointerType>();
454 if (!PT)
455 return NoMatch;
456
457 // We cannot write through a const qualified pointer.
459 return NoMatch;
460
461 argTy = PT->getPointeeType();
462 }
463
464 if (const auto *OBT = argTy->getAs<OverflowBehaviorType>())
465 argTy = OBT->getUnderlyingType();
466
467 switch (K) {
468 case InvalidTy:
469 llvm_unreachable("ArgType must be valid");
470
471 case UnsupportedTy:
472 return NoMatch;
473
474 case UnknownTy:
475 return Match;
476
477 case AnyCharTy: {
478 if (const auto *ED = argTy->getAsEnumDecl()) {
479 // If the enum is incomplete we know nothing about the underlying type.
480 // Assume that it's 'int'. Do not use the underlying type for a scoped
481 // enumeration.
482 if (!ED->isComplete())
483 return NoMatch;
484 if (!ED->isScoped())
485 argTy = ED->getIntegerType();
486 }
487
488 if (const auto *BT = argTy->getAs<BuiltinType>()) {
489 // The types are perfectly matched?
490 switch (BT->getKind()) {
491 default:
492 break;
493 case BuiltinType::Char_S:
494 case BuiltinType::SChar:
495 case BuiltinType::UChar:
496 case BuiltinType::Char_U:
497 return Match;
498 case BuiltinType::Bool:
499 if (!Ptr)
500 return Match;
501 break;
502 }
503 // "Partially matched" because of promotions?
504 if (!Ptr) {
505 switch (BT->getKind()) {
506 default:
507 break;
508 case BuiltinType::Int:
509 case BuiltinType::UInt:
510 return MatchPromotion;
511 case BuiltinType::Short:
512 case BuiltinType::UShort:
513 case BuiltinType::WChar_S:
514 case BuiltinType::WChar_U:
516 }
517 }
518 }
519 return NoMatch;
520 }
521
522 case SpecificTy: {
523 if (TK == TypeKind::SizeT || TK == TypeKind::PtrdiffT) {
524 return matchesSizeTPtrdiffT(C, argTy, T);
525 }
526
527 if (const auto *ED = argTy->getAsEnumDecl()) {
528 // If the enum is incomplete we know nothing about the underlying type.
529 // Assume that it's 'int'. Do not use the underlying type for a scoped
530 // enumeration as that needs an exact match.
531 if (!ED->isComplete())
532 argTy = C.IntTy;
533 else if (!ED->isScoped())
534 argTy = ED->getIntegerType();
535 }
536
537 if (argTy->isSaturatedFixedPointType())
538 argTy = C.getCorrespondingUnsaturatedType(argTy);
539
540 argTy = C.getCanonicalType(argTy).getUnqualifiedType();
541
542 if (T == argTy)
543 return Match;
544 if (const auto *BT = argTy->getAs<BuiltinType>()) {
545 // Check if the only difference between them is signed vs unsigned
546 // if true, return match signedness.
547 switch (BT->getKind()) {
548 default:
549 break;
550 case BuiltinType::Bool:
551 if (Ptr && (T == C.UnsignedCharTy || T == C.SignedCharTy))
552 return NoMatch;
553 [[fallthrough]];
554 case BuiltinType::Char_S:
555 case BuiltinType::SChar:
556 if (T == C.UnsignedShortTy || T == C.ShortTy)
558 if (T == C.UnsignedCharTy)
559 return NoMatchSignedness;
560 if (T == C.SignedCharTy)
561 return Match;
562 break;
563 case BuiltinType::Char_U:
564 case BuiltinType::UChar:
565 if (T == C.UnsignedShortTy || T == C.ShortTy)
567 if (T == C.UnsignedCharTy)
568 return Match;
569 if (T == C.SignedCharTy)
570 return NoMatchSignedness;
571 break;
572 case BuiltinType::Short:
573 if (T == C.UnsignedShortTy)
574 return NoMatchSignedness;
575 break;
576 case BuiltinType::UShort:
577 if (T == C.ShortTy)
578 return NoMatchSignedness;
579 break;
580 case BuiltinType::Int:
581 if (T == C.UnsignedIntTy)
582 return NoMatchSignedness;
583 break;
584 case BuiltinType::UInt:
585 if (T == C.IntTy)
586 return NoMatchSignedness;
587 break;
588 case BuiltinType::Long:
589 if (T == C.UnsignedLongTy)
590 return NoMatchSignedness;
591 break;
592 case BuiltinType::ULong:
593 if (T == C.LongTy)
594 return NoMatchSignedness;
595 break;
596 case BuiltinType::LongLong:
597 if (T == C.UnsignedLongLongTy)
598 return NoMatchSignedness;
599 break;
600 case BuiltinType::ULongLong:
601 if (T == C.LongLongTy)
602 return NoMatchSignedness;
603 break;
604 }
605 // "Partially matched" because of promotions?
606 if (!Ptr) {
607 switch (BT->getKind()) {
608 default:
609 break;
610 case BuiltinType::Bool:
611 if (T == C.IntTy || T == C.UnsignedIntTy)
612 return MatchPromotion;
613 break;
614 case BuiltinType::Int:
615 case BuiltinType::UInt:
616 if (T == C.SignedCharTy || T == C.UnsignedCharTy || T == C.ShortTy ||
617 T == C.UnsignedShortTy || T == C.WCharTy || T == C.WideCharTy)
618 return MatchPromotion;
619 break;
620 case BuiltinType::Char_U:
621 if (T == C.UnsignedIntTy)
622 return MatchPromotion;
623 if (T == C.UnsignedShortTy)
625 break;
626 case BuiltinType::Char_S:
627 if (T == C.IntTy)
628 return MatchPromotion;
629 if (T == C.ShortTy)
631 break;
632 case BuiltinType::Half:
633 case BuiltinType::Float:
634 if (T == C.DoubleTy)
635 return MatchPromotion;
636 break;
637 case BuiltinType::Short:
638 case BuiltinType::UShort:
639 if (T == C.SignedCharTy || T == C.UnsignedCharTy)
641 break;
642 case BuiltinType::WChar_U:
643 case BuiltinType::WChar_S:
644 if (T != C.WCharTy && T != C.WideCharTy)
646 }
647 }
648 }
649 return NoMatch;
650 }
651
652 case CStrTy:
653 if (const auto *PT = argTy->getAs<PointerType>();
654 PT && PT->getPointeeType()->isCharType())
655 return Match;
656 return NoMatch;
657
658 case WCStrTy:
659 if (const auto *PT = argTy->getAs<PointerType>();
660 PT &&
661 C.hasSameUnqualifiedType(PT->getPointeeType(), C.getWideCharType()))
662 return Match;
663 return NoMatch;
664
665 case WIntTy: {
666 QualType WInt = C.getCanonicalType(C.getWIntType()).getUnqualifiedType();
667
668 if (C.getCanonicalType(argTy).getUnqualifiedType() == WInt)
669 return Match;
670
671 QualType PromoArg = C.isPromotableIntegerType(argTy)
672 ? C.getPromotedIntegerType(argTy)
673 : argTy;
674 PromoArg = C.getCanonicalType(PromoArg).getUnqualifiedType();
675
676 // If the promoted argument is the corresponding signed type of the
677 // wint_t type, then it should match.
678 if (PromoArg->hasSignedIntegerRepresentation() &&
679 C.getCorrespondingUnsignedType(PromoArg) == WInt)
680 return Match;
681
682 return WInt == PromoArg ? Match : NoMatch;
683 }
684
685 case CPointerTy:
686 if (const auto *PT = argTy->getAs<PointerType>()) {
687 QualType PointeeTy = PT->getPointeeType();
688 if (PointeeTy->isVoidType() || (!Ptr && PointeeTy->isCharType()))
689 return Match;
690 return NoMatchPedantic;
691 }
692
693 // nullptr_t* is not a double pointer, so reject when something like
694 // void** is expected.
695 // In C++, nullptr is promoted to void*. In C23, va_arg(ap, void*) is not
696 // undefined when the next argument is of type nullptr_t.
697 if (!Ptr && argTy->isNullPtrType())
698 return C.getLangOpts().CPlusPlus ? MatchPromotion : Match;
699
700 if (argTy->isObjCObjectPointerType() || argTy->isBlockPointerType())
701 return NoMatchPedantic;
702
703 return NoMatch;
704
705 case ObjCPointerTy: {
706 if (argTy->getAs<ObjCObjectPointerType>() ||
707 argTy->getAs<BlockPointerType>())
708 return Match;
709
710 // Handle implicit toll-free bridging.
711 if (const PointerType *PT = argTy->getAs<PointerType>()) {
712 // Things such as CFTypeRef are really just opaque pointers
713 // to C structs representing CF types that can often be bridged
714 // to Objective-C objects. Since the compiler doesn't know which
715 // structs can be toll-free bridged, we just accept them all.
716 QualType pointee = PT->getPointeeType();
717 if (pointee->isStructureType() || pointee->isVoidType())
718 return Match;
719 }
720 return NoMatch;
721 }
722 }
723
724 llvm_unreachable("Invalid ArgType Kind!");
725}
726
730
731 uint64_t IntSize = C.getTypeSize(C.IntTy);
732 uint64_t ASize = C.getTypeSize(A);
733 uint64_t BSize = C.getTypeSize(B);
734 if (std::max(ASize, IntSize) != std::max(BSize, IntSize))
735 return MK::NoMatch;
736 if (CheckSign && A->isSignedIntegerType() != B->isSignedIntegerType())
737 return MK::NoMatchSignedness;
738 if (ASize != BSize)
739 return MK::MatchPromotion;
740 return MK::Match;
741}
742
746
747 // Per matchesType.
748 if (K == AK::InvalidTy || Other.K == AK::InvalidTy)
749 return NoMatch;
750 if (K == AK::UnsupportedTy || Other.K == AK::UnsupportedTy)
751 return NoMatch;
752 if (K == AK::UnknownTy || Other.K == AK::UnknownTy)
753 return Match;
754
755 // Handle whether either (or both, or neither) sides has Ptr set,
756 // in addition to whether either (or both, or neither) sides is a SpecificTy
757 // that is a pointer.
758 ArgType Left = *this;
759 bool LeftWasPointer = false;
760 ArgType Right = Other;
761 bool RightWasPointer = false;
762 if (Left.Ptr) {
763 Left.Ptr = false;
764 LeftWasPointer = true;
765 } else if (Left.K == AK::SpecificTy && Left.T->isPointerType()) {
766 Left.T = Left.T->getPointeeType();
767 LeftWasPointer = true;
768 }
769 if (Right.Ptr) {
770 Right.Ptr = false;
771 RightWasPointer = true;
772 } else if (Right.K == AK::SpecificTy && Right.T->isPointerType()) {
773 Right.T = Right.T->getPointeeType();
774 RightWasPointer = true;
775 }
776
777 if (LeftWasPointer != RightWasPointer)
778 return NoMatch;
779
780 // Ensure that if at least one side is a SpecificTy, then Left is a
781 // SpecificTy.
782 if (Right.K == AK::SpecificTy)
783 std::swap(Left, Right);
784
785 if (Left.K == AK::SpecificTy) {
786 if (Right.K == AK::SpecificTy) {
787 if (Left.TK != TypeKind::DontCare) {
788 return matchesSizeTPtrdiffT(C, Right.T, Left.T);
789 } else if (Right.TK != TypeKind::DontCare) {
790 return matchesSizeTPtrdiffT(C, Left.T, Right.T);
791 }
792
793 auto Canon1 = C.getCanonicalType(Left.T);
794 auto Canon2 = C.getCanonicalType(Right.T);
795 if (Canon1 == Canon2)
796 return Match;
797
798 auto *BT1 = QualType(Canon1)->getAs<BuiltinType>();
799 auto *BT2 = QualType(Canon2)->getAs<BuiltinType>();
800 if (BT1 == nullptr || BT2 == nullptr)
801 return NoMatch;
802 if (BT1 == BT2)
803 return Match;
804
805 if (!LeftWasPointer && BT1->isInteger() && BT2->isInteger())
806 return integerTypeMatch(C, Canon1, Canon2, true);
807 return NoMatch;
808 } else if (Right.K == AK::AnyCharTy) {
809 if (!LeftWasPointer && Left.T->isIntegerType())
810 return integerTypeMatch(C, Left.T, C.CharTy, false);
811 return NoMatch;
812 } else if (Right.K == AK::WIntTy) {
813 if (!LeftWasPointer && Left.T->isIntegerType())
814 return integerTypeMatch(C, Left.T, C.WIntTy, true);
815 return NoMatch;
816 }
817 // It's hypothetically possible to create an AK::SpecificTy ArgType
818 // that matches another kind of ArgType, but in practice Clang doesn't
819 // do that, so ignore that case.
820 return NoMatch;
821 }
822
823 return Left.K == Right.K ? Match : NoMatch;
824}
825
826ArgType ArgType::makeVectorType(ASTContext &C, unsigned NumElts) const {
827 // Check for valid vector element types.
828 if (T.isNull())
829 return ArgType::Invalid();
830
831 QualType Vec = C.getExtVectorType(T, NumElts);
832 return ArgType(Vec, Name);
833}
834
836 bool Signed) {
837 bool IsFast = LengthMod.getKind() == LengthModifier::AsFastIntN;
838 QualType Ty =
839 IsFast ? Ctx.getLeastIntTypeForBitwidth(LengthMod.getBitWidth(), Signed)
840 : Ctx.getIntTypeForBitwidth(LengthMod.getBitWidth(), Signed);
841 if (Ty.isNull())
842 return ArgType::Invalid();
843
844 ArgType Res(Ty);
845 Res.TK = IsFast ? (Signed ? TypeKind::FastIntN : TypeKind::FastUIntN)
846 : (Signed ? TypeKind::IntN : TypeKind::UIntN);
847 Res.BitWidth = LengthMod.getBitWidth();
848 return Res;
849}
850
852 QualType Res;
853 switch (K) {
854 case InvalidTy:
855 llvm_unreachable("No representative type for Invalid ArgType");
856 case UnknownTy:
857 llvm_unreachable("No representative type for Unknown ArgType");
858 case UnsupportedTy:
859 llvm_unreachable("No representative type for Unsupported ArgType");
860 case AnyCharTy:
861 Res = C.CharTy;
862 break;
863 case SpecificTy:
864 if (TK == TypeKind::PtrdiffT || TK == TypeKind::SizeT)
865 // Using Name as name, so no need to show the uglified name.
866 Res = T->getCanonicalTypeInternal();
867 else
868 Res = T;
869 break;
870 case CStrTy:
871 Res = C.getPointerType(C.CharTy);
872 break;
873 case WCStrTy:
874 Res = C.getPointerType(C.getWideCharType());
875 break;
876 case ObjCPointerTy:
877 Res = C.ObjCBuiltinIdTy;
878 break;
879 case CPointerTy:
880 Res = C.VoidPtrTy;
881 break;
882 case WIntTy: {
883 Res = C.getWIntType();
884 break;
885 }
886 }
887
888 if (Ptr)
889 Res = C.getPointerType(Res);
890 return Res;
891}
892
894 std::string S;
895 if (K != UnsupportedTy)
896 S = getRepresentativeType(C).getAsString(C.getPrintingPolicy());
897
898 std::string Alias;
899 if (Name) {
900 // Use a specific name for this type, e.g. "size_t".
901 Alias = Name;
902 } else {
903 const char *Prefix = nullptr;
904 switch (TK) {
905 case TypeKind::IntN:
906 Prefix = "int";
907 break;
908 case TypeKind::UIntN:
909 Prefix = "uint";
910 break;
911 case TypeKind::FastIntN:
912 Prefix = "int_fast";
913 break;
914 case TypeKind::FastUIntN:
915 Prefix = "uint_fast";
916 break;
917 case TypeKind::DontCare:
918 case TypeKind::SizeT:
919 case TypeKind::PtrdiffT:
920 break;
921 }
922 if (Prefix) {
923 Alias = Prefix;
924 Alias += std::to_string(BitWidth);
925 Alias += "_t";
926 }
927 }
928 if (!Alias.empty()) {
929 if (Ptr) {
930 // If ArgType is actually a pointer to T, append an asterisk.
931 Alias += (Alias[Alias.size() - 1] == '*') ? "*" : " *";
932 }
933 // If Alias is the same as the underlying type, e.g. wchar_t, then drop it.
934 if (S == Alias)
935 Alias.clear();
936 }
937
938 if (Alias.empty())
939 return std::string("'") + S + "'";
940
941 return std::string("'") + Alias + "'" +
942 (K == UnsupportedTy ? "" : " (aka '" + S + "')");
943}
944
945//===----------------------------------------------------------------------===//
946// Methods on OptionalAmount.
947//===----------------------------------------------------------------------===//
948
953
954//===----------------------------------------------------------------------===//
955// Methods on LengthModifier.
956//===----------------------------------------------------------------------===//
957
959 switch (kind) {
960 case AsChar:
961 return "hh";
962 case AsShort:
963 return "h";
964 case AsShortLong:
965 return "hl";
966 case AsLong: // or AsWideChar
967 return "l";
968 case AsLongLong:
969 return "ll";
970 case AsQuad:
971 return "q";
972 case AsIntMax:
973 return "j";
974 case AsSizeT:
975 return "z";
976 case AsPtrDiff:
977 return "t";
978 case AsInt32:
979 return "I32";
980 case AsInt3264:
981 return "I";
982 case AsInt64:
983 return "I64";
984 case AsLongDouble:
985 return "L";
986 case AsDecimal32:
987 return "H";
988 case AsDecimal64:
989 return "D";
990 case AsDecimal128:
991 return "DD";
992 case AsIntN:
993 case AsFastIntN:
994 return StringRef(Position, getLength());
995 case AsAllocate:
996 return "a";
997 case AsMAllocate:
998 return "m";
999 case AsWide:
1000 return "w";
1001 case None:
1002 return "";
1003 }
1004 llvm_unreachable("Invalid LengthModifier Kind!");
1005}
1006
1007//===----------------------------------------------------------------------===//
1008// Methods on ConversionSpecifier.
1009//===----------------------------------------------------------------------===//
1010
1012 switch (kind) {
1013 case bArg:
1014 return "b";
1015 case BArg:
1016 return "B";
1017 case dArg:
1018 return "d";
1019 case DArg:
1020 return "D";
1021 case iArg:
1022 return "i";
1023 case oArg:
1024 return "o";
1025 case OArg:
1026 return "O";
1027 case uArg:
1028 return "u";
1029 case UArg:
1030 return "U";
1031 case xArg:
1032 return "x";
1033 case XArg:
1034 return "X";
1035 case fArg:
1036 return "f";
1037 case FArg:
1038 return "F";
1039 case eArg:
1040 return "e";
1041 case EArg:
1042 return "E";
1043 case gArg:
1044 return "g";
1045 case GArg:
1046 return "G";
1047 case aArg:
1048 return "a";
1049 case AArg:
1050 return "A";
1051 case cArg:
1052 return "c";
1053 case sArg:
1054 return "s";
1055 case pArg:
1056 return "p";
1057 case PArg:
1058 return "P";
1059 case nArg:
1060 return "n";
1061 case PercentArg:
1062 return "%";
1063 case ScanListArg:
1064 return "[";
1065 case InvalidSpecifier:
1066 return nullptr;
1067
1068 // POSIX unicode extensions.
1069 case CArg:
1070 return "C";
1071 case SArg:
1072 return "S";
1073
1074 // Objective-C specific specifiers.
1075 case ObjCObjArg:
1076 return "@";
1077
1078 // FreeBSD kernel specific specifiers.
1079 case FreeBSDbArg:
1080 return "b";
1081 case FreeBSDDArg:
1082 return "D";
1083 case FreeBSDrArg:
1084 return "r";
1085 case FreeBSDyArg:
1086 return "y";
1087
1088 // GlibC specific specifiers.
1089 case PrintErrno:
1090 return "m";
1091
1092 // MS specific specifiers.
1093 case ZArg:
1094 return "Z";
1095
1096 // ISO/IEC TR 18037 (fixed-point) specific specifiers.
1097 case rArg:
1098 return "r";
1099 case RArg:
1100 return "R";
1101 case kArg:
1102 return "k";
1103 case KArg:
1104 return "K";
1105 }
1106 return nullptr;
1107}
1108
1109std::optional<ConversionSpecifier>
1112
1113 switch (getKind()) {
1114 default:
1115 return std::nullopt;
1116 case DArg:
1117 NewKind = dArg;
1118 break;
1119 case UArg:
1120 NewKind = uArg;
1121 break;
1122 case OArg:
1123 NewKind = oArg;
1124 break;
1125 }
1126
1127 ConversionSpecifier FixedCS(*this);
1128 FixedCS.setKind(NewKind);
1129 return FixedCS;
1130}
1131
1132//===----------------------------------------------------------------------===//
1133// Methods on OptionalAmount.
1134//===----------------------------------------------------------------------===//
1135
1136void OptionalAmount::toString(raw_ostream &os) const {
1137 switch (hs) {
1138 case Invalid:
1139 case NotSpecified:
1140 return;
1141 case Arg:
1142 if (UsesDotPrefix)
1143 os << ".";
1144 if (usesPositionalArg())
1145 os << "*" << getPositionalArgIndex() << "$";
1146 else
1147 os << "*";
1148 break;
1149 case Constant:
1150 if (UsesDotPrefix)
1151 os << ".";
1152 os << amt;
1153 break;
1154 }
1155}
1156
1158 const LangOptions &LO) const {
1159 switch (LM.getKind()) {
1161 return true;
1162
1163 // Handle most integer flags
1165 // Length modifier only applies to FP vectors.
1166 if (LO.OpenCL && CS.isDoubleArg())
1167 return !VectorNumElts.isInvalid();
1168
1169 if (CS.isFixedPointArg())
1170 return true;
1171
1172 if (Target.getTriple().isOSMSVCRT()) {
1173 switch (CS.getKind()) {
1179 return true;
1180 default:
1181 break;
1182 }
1183 }
1184 [[fallthrough]];
1191 switch (CS.getKind()) {
1204 return true;
1207 return Target.getTriple().isOSFreeBSD() || Target.getTriple().isPS();
1208 default:
1209 return false;
1210 }
1211
1213 return LO.OpenCL && !VectorNumElts.isInvalid();
1214
1215 // Handle 'l' flag
1216 case LengthModifier::AsLong: // or AsWideChar
1217 if (CS.isDoubleArg()) {
1218 // Invalid for OpenCL FP scalars.
1219 if (LO.OpenCL && VectorNumElts.isInvalid())
1220 return false;
1221 return true;
1222 }
1223
1224 if (CS.isFixedPointArg())
1225 return true;
1226
1227 switch (CS.getKind()) {
1244 return true;
1247 return Target.getTriple().isOSFreeBSD() || Target.getTriple().isPS();
1248 default:
1249 return false;
1250 }
1251
1253 switch (CS.getKind()) {
1262 return true;
1263 // GNU libc extension.
1270 return !Target.getTriple().isOSDarwin() &&
1271 !Target.getTriple().isOSWindows();
1272 default:
1273 return false;
1274 }
1275
1278 if (!LO.C23)
1279 return false;
1280
1281 TargetInfo::IntType TargetType =
1282 LM.getKind() == LengthModifier::AsIntN
1283 ? Target.getIntTypeByWidth(LM.getBitWidth(), /*IsSigned=*/true)
1284 : Target.getLeastIntTypeByWidth(LM.getBitWidth(),
1285 /*IsSigned=*/true);
1286 if (TargetType == TargetInfo::NoInt)
1287 return false;
1288
1289 switch (CS.getKind()) {
1299 return true;
1300 default:
1301 return false;
1302 }
1303 }
1304
1306 switch (CS.getKind()) {
1310 return true;
1311 default:
1312 return false;
1313 }
1314
1316 switch (CS.getKind()) {
1322 return true;
1323 default:
1324 return false;
1325 }
1329 switch (CS.getKind()) {
1336 return Target.getTriple().isOSMSVCRT();
1337 default:
1338 return false;
1339 }
1341 switch (CS.getKind()) {
1347 return Target.getTriple().isOSMSVCRT();
1348 default:
1349 return false;
1350 }
1351
1355 switch (CS.getKind()) {
1364 return LO.C23;
1365 default:
1366 return false;
1367 }
1368 }
1369 llvm_unreachable("Invalid LengthModifier Kind!");
1370}
1371
1373 switch (LM.getKind()) {
1388 return true;
1396 case LengthModifier::AsShortLong: // ???
1397 return false;
1398 }
1399 llvm_unreachable("Invalid LengthModifier Kind!");
1400}
1401
1403 const LangOptions &LangOpt) const {
1404 switch (CS.getKind()) {
1429 return true;
1432 return LangOpt.ObjC;
1443 return false;
1448 return LangOpt.FixedPoint;
1449 }
1450 llvm_unreachable("Invalid ConversionSpecifier Kind!");
1451}
1452
1454 if (LM.getKind() == LengthModifier::AsLongDouble) {
1455 switch (CS.getKind()) {
1462 return false;
1463 default:
1464 return true;
1465 }
1466 }
1467 return true;
1468}
1469
1470std::optional<LengthModifier>
1472 if (CS.isAnyIntArg() || CS.getKind() == ConversionSpecifier::nArg) {
1473 if (LM.getKind() == LengthModifier::AsLongDouble ||
1474 LM.getKind() == LengthModifier::AsQuad) {
1475 LengthModifier FixedLM(LM);
1477 return FixedLM;
1478 }
1479 }
1480
1481 return std::nullopt;
1482}
1483
1485 LengthModifier &LM) {
1487 namedTypeToLengthModifierKind(Ctx, QT, Out)) {
1488 LM.setKind(Out);
1489 return true;
1490 }
1491 return false;
1492}
static clang::analyze_format_string::ArgType::MatchKind matchesSizeTPtrdiffT(ASTContext &C, QualType T, QualType E)
static analyze_format_string::ArgType::MatchKind integerTypeMatch(ASTContext &C, QualType A, QualType B, bool CheckSign)
static bool namedTypeToLengthModifierKind(ASTContext &Ctx, QualType QT, LengthModifier::Kind &K)
Defines the clang::LangOptions interface.
virtual ~FormatStringHandler()
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const LangOptions & getLangOpts() const
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
QualType getLeastIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
CanQualType IntTy
Pointer to a block type.
Definition TypeBase.h:3653
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
bool isInteger() const
Definition TypeBase.h:3312
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a pointer to an Objective C object.
Definition TypeBase.h:8219
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
PredefinedSugarKind Kind
Definition TypeBase.h:8489
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
QualType getCanonicalType() const
Definition TypeBase.h:8630
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
Exposes information about the current target.
Definition TargetInfo.h:228
bool isStructureType() const
Definition Type.cpp:811
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isVoidType() const
Definition TypeBase.h:9200
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2394
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9371
bool isCharType() const
Definition Type.cpp:2321
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9280
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2438
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3200
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isObjCObjectPointerType() const
Definition TypeBase.h:8994
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isNullPtrType() const
Definition TypeBase.h:9241
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
ArgType makeVectorType(ASTContext &C, unsigned NumElts) const
MatchKind matchesArgType(ASTContext &C, const ArgType &other) const
QualType getRepresentativeType(ASTContext &C) const
std::string getRepresentativeTypeName(ASTContext &C) const
static ArgType makeIntNType(ASTContext &Ctx, const LengthModifier &LengthMod, bool Signed)
ArgType(Kind K=UnknownTy, const char *N=nullptr)
MatchKind matchesType(ASTContext &C, QualType argTy) const
std::optional< ConversionSpecifier > getStandardSpecifier() const
static bool namedTypeToLengthModifier(ASTContext &Ctx, QualType QT, LengthModifier &LM)
For a TypedefType QT, if it is a named integer type such as size_t, assign the appropriate value to L...
void setFieldWidth(const OptionalAmount &Amt)
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const
bool hasValidLengthModifier(const TargetInfo &Target, const LangOptions &LO) const
std::optional< LengthModifier > getCorrectedLengthModifier() const
void setVectorNumElts(const OptionalAmount &Amt)
OptionalAmount parsePositionAmount(const char *Start, const char *&Beg, const char *E, PositionContext p) const
bool parseVectorModifier(FormatSpecifier &FS, const char *&Beg, const char *E) const
bool parseLengthModifier(FormatSpecifier &FS, const char *&Beg, const char *E) const
Returns true if a LengthModifier was parsed and installed in the FormatSpecifier& argument,...
bool parseArgPosition(FormatSpecifier &CS, const char *Start, const char *&Beg, const char *E) const
bool parseUTF8InvalidSpecifier(const char *SpecifierBegin, const char *FmtStrEnd, unsigned &Len) const
Returns true if the invalid specifier in SpecifierBegin is a UTF-8 string; check that it won't go fur...
OptionalAmount parseNonPositionAmount(const char *&Beg, const char *E, unsigned &argIndex) const
bool parseFieldWidth(FormatSpecifier &CS, const char *Start, const char *&Beg, const char *E, unsigned *argIndex) const
OptionalAmount parseAmount(const char *&Beg, const char *E) const
Represents the length modifier in a format string in scanf/printf.
ArgType getArgType(ASTContext &Ctx) const
Defines the clang::TargetInfo interface.
Top level wrappers for InstallAPI frontend operations.
const FunctionProtoType * T
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
IntType
===-— Target Data Type Query Methods ----------------------------—===//
Definition TargetInfo.h:148