Bug Summary

File:src/gnu/usr.bin/clang/libclangAST/../../../llvm/llvm/include/llvm/Support/Alignment.h
Warning:line 85, column 47
The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'uint64_t'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CommentSema.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangAST/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangAST/obj/../include/clang/AST -I /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangAST/../include -I /usr/src/gnu/usr.bin/clang/libclangAST/obj -I /usr/src/gnu/usr.bin/clang/libclangAST/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangAST/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/lib/AST/CommentSema.cpp

/usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/lib/AST/CommentSema.cpp

1//===--- CommentSema.cpp - Doxygen comment semantic analysis --------------===//
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#include "clang/AST/CommentSema.h"
10#include "clang/AST/Attr.h"
11#include "clang/AST/CommentCommandTraits.h"
12#include "clang/AST/CommentDiagnostic.h"
13#include "clang/AST/Decl.h"
14#include "clang/AST/DeclTemplate.h"
15#include "clang/Basic/LLVM.h"
16#include "clang/Basic/SourceManager.h"
17#include "clang/Lex/Preprocessor.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/StringSwitch.h"
20
21namespace clang {
22namespace comments {
23
24namespace {
25#include "clang/AST/CommentHTMLTagsProperties.inc"
26} // end anonymous namespace
27
28Sema::Sema(llvm::BumpPtrAllocator &Allocator, const SourceManager &SourceMgr,
29 DiagnosticsEngine &Diags, CommandTraits &Traits,
30 const Preprocessor *PP) :
31 Allocator(Allocator), SourceMgr(SourceMgr), Diags(Diags), Traits(Traits),
32 PP(PP), ThisDeclInfo(nullptr), BriefCommand(nullptr),
33 HeaderfileCommand(nullptr) {
34}
35
36void Sema::setDecl(const Decl *D) {
37 if (!D)
38 return;
39
40 ThisDeclInfo = new (Allocator) DeclInfo;
41 ThisDeclInfo->CommentDecl = D;
42 ThisDeclInfo->IsFilled = false;
43}
44
45ParagraphComment *Sema::actOnParagraphComment(
46 ArrayRef<InlineContentComment *> Content) {
47 return new (Allocator) ParagraphComment(Content);
48}
49
50BlockCommandComment *Sema::actOnBlockCommandStart(
51 SourceLocation LocBegin,
52 SourceLocation LocEnd,
53 unsigned CommandID,
54 CommandMarkerKind CommandMarker) {
55 BlockCommandComment *BC = new (Allocator) BlockCommandComment(LocBegin, LocEnd,
56 CommandID,
57 CommandMarker);
58 checkContainerDecl(BC);
59 return BC;
60}
61
62void Sema::actOnBlockCommandArgs(BlockCommandComment *Command,
63 ArrayRef<BlockCommandComment::Argument> Args) {
64 Command->setArgs(Args);
65}
66
67void Sema::actOnBlockCommandFinish(BlockCommandComment *Command,
68 ParagraphComment *Paragraph) {
69 Command->setParagraph(Paragraph);
70 checkBlockCommandEmptyParagraph(Command);
71 checkBlockCommandDuplicate(Command);
72 if (ThisDeclInfo) {
73 // These checks only make sense if the comment is attached to a
74 // declaration.
75 checkReturnsCommand(Command);
76 checkDeprecatedCommand(Command);
77 }
78}
79
80ParamCommandComment *Sema::actOnParamCommandStart(
81 SourceLocation LocBegin,
82 SourceLocation LocEnd,
83 unsigned CommandID,
84 CommandMarkerKind CommandMarker) {
85 ParamCommandComment *Command =
86 new (Allocator) ParamCommandComment(LocBegin, LocEnd, CommandID,
87 CommandMarker);
88
89 if (!isFunctionDecl() && !isFunctionOrBlockPointerVarLikeDecl())
90 Diag(Command->getLocation(),
91 diag::warn_doc_param_not_attached_to_a_function_decl)
92 << CommandMarker
93 << Command->getCommandNameRange(Traits);
94
95 return Command;
96}
97
98void Sema::checkFunctionDeclVerbatimLine(const BlockCommandComment *Comment) {
99 const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID());
100 if (!Info->IsFunctionDeclarationCommand)
101 return;
102
103 unsigned DiagSelect;
104 switch (Comment->getCommandID()) {
105 case CommandTraits::KCI_function:
106 DiagSelect = (!isAnyFunctionDecl() && !isFunctionTemplateDecl())? 1 : 0;
107 break;
108 case CommandTraits::KCI_functiongroup:
109 DiagSelect = (!isAnyFunctionDecl() && !isFunctionTemplateDecl())? 2 : 0;
110 break;
111 case CommandTraits::KCI_method:
112 DiagSelect = !isObjCMethodDecl() ? 3 : 0;
113 break;
114 case CommandTraits::KCI_methodgroup:
115 DiagSelect = !isObjCMethodDecl() ? 4 : 0;
116 break;
117 case CommandTraits::KCI_callback:
118 DiagSelect = !isFunctionPointerVarDecl() ? 5 : 0;
119 break;
120 default:
121 DiagSelect = 0;
122 break;
123 }
124 if (DiagSelect)
125 Diag(Comment->getLocation(), diag::warn_doc_function_method_decl_mismatch)
126 << Comment->getCommandMarker()
127 << (DiagSelect-1) << (DiagSelect-1)
128 << Comment->getSourceRange();
129}
130
131void Sema::checkContainerDeclVerbatimLine(const BlockCommandComment *Comment) {
132 const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID());
133 if (!Info->IsRecordLikeDeclarationCommand)
134 return;
135 unsigned DiagSelect;
136 switch (Comment->getCommandID()) {
137 case CommandTraits::KCI_class:
138 DiagSelect =
139 (!isClassOrStructOrTagTypedefDecl() && !isClassTemplateDecl()) ? 1
140 : 0;
141 // Allow @class command on @interface declarations.
142 // FIXME. Currently, \class and @class are indistinguishable. So,
143 // \class is also allowed on an @interface declaration
144 if (DiagSelect && Comment->getCommandMarker() && isObjCInterfaceDecl())
145 DiagSelect = 0;
146 break;
147 case CommandTraits::KCI_interface:
148 DiagSelect = !isObjCInterfaceDecl() ? 2 : 0;
149 break;
150 case CommandTraits::KCI_protocol:
151 DiagSelect = !isObjCProtocolDecl() ? 3 : 0;
152 break;
153 case CommandTraits::KCI_struct:
154 DiagSelect = !isClassOrStructOrTagTypedefDecl() ? 4 : 0;
155 break;
156 case CommandTraits::KCI_union:
157 DiagSelect = !isUnionDecl() ? 5 : 0;
158 break;
159 default:
160 DiagSelect = 0;
161 break;
162 }
163 if (DiagSelect)
164 Diag(Comment->getLocation(), diag::warn_doc_api_container_decl_mismatch)
165 << Comment->getCommandMarker()
166 << (DiagSelect-1) << (DiagSelect-1)
167 << Comment->getSourceRange();
168}
169
170void Sema::checkContainerDecl(const BlockCommandComment *Comment) {
171 const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID());
172 if (!Info->IsRecordLikeDetailCommand || isRecordLikeDecl())
173 return;
174 unsigned DiagSelect;
175 switch (Comment->getCommandID()) {
176 case CommandTraits::KCI_classdesign:
177 DiagSelect = 1;
178 break;
179 case CommandTraits::KCI_coclass:
180 DiagSelect = 2;
181 break;
182 case CommandTraits::KCI_dependency:
183 DiagSelect = 3;
184 break;
185 case CommandTraits::KCI_helper:
186 DiagSelect = 4;
187 break;
188 case CommandTraits::KCI_helperclass:
189 DiagSelect = 5;
190 break;
191 case CommandTraits::KCI_helps:
192 DiagSelect = 6;
193 break;
194 case CommandTraits::KCI_instancesize:
195 DiagSelect = 7;
196 break;
197 case CommandTraits::KCI_ownership:
198 DiagSelect = 8;
199 break;
200 case CommandTraits::KCI_performance:
201 DiagSelect = 9;
202 break;
203 case CommandTraits::KCI_security:
204 DiagSelect = 10;
205 break;
206 case CommandTraits::KCI_superclass:
207 DiagSelect = 11;
208 break;
209 default:
210 DiagSelect = 0;
211 break;
212 }
213 if (DiagSelect)
214 Diag(Comment->getLocation(), diag::warn_doc_container_decl_mismatch)
215 << Comment->getCommandMarker()
216 << (DiagSelect-1)
217 << Comment->getSourceRange();
218}
219
220/// Turn a string into the corresponding PassDirection or -1 if it's not
221/// valid.
222static int getParamPassDirection(StringRef Arg) {
223 return llvm::StringSwitch<int>(Arg)
224 .Case("[in]", ParamCommandComment::In)
225 .Case("[out]", ParamCommandComment::Out)
226 .Cases("[in,out]", "[out,in]", ParamCommandComment::InOut)
227 .Default(-1);
228}
229
230void Sema::actOnParamCommandDirectionArg(ParamCommandComment *Command,
231 SourceLocation ArgLocBegin,
232 SourceLocation ArgLocEnd,
233 StringRef Arg) {
234 std::string ArgLower = Arg.lower();
235 int Direction = getParamPassDirection(ArgLower);
236
237 if (Direction == -1) {
238 // Try again with whitespace removed.
239 ArgLower.erase(
240 std::remove_if(ArgLower.begin(), ArgLower.end(), clang::isWhitespace),
241 ArgLower.end());
242 Direction = getParamPassDirection(ArgLower);
243
244 SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
245 if (Direction != -1) {
246 const char *FixedName = ParamCommandComment::getDirectionAsString(
247 (ParamCommandComment::PassDirection)Direction);
248 Diag(ArgLocBegin, diag::warn_doc_param_spaces_in_direction)
249 << ArgRange << FixItHint::CreateReplacement(ArgRange, FixedName);
250 } else {
251 Diag(ArgLocBegin, diag::warn_doc_param_invalid_direction) << ArgRange;
252 Direction = ParamCommandComment::In; // Sane fall back.
253 }
254 }
255 Command->setDirection((ParamCommandComment::PassDirection)Direction,
256 /*Explicit=*/true);
257}
258
259void Sema::actOnParamCommandParamNameArg(ParamCommandComment *Command,
260 SourceLocation ArgLocBegin,
261 SourceLocation ArgLocEnd,
262 StringRef Arg) {
263 // Parser will not feed us more arguments than needed.
264 assert(Command->getNumArgs() == 0)((void)0);
265
266 if (!Command->isDirectionExplicit()) {
267 // User didn't provide a direction argument.
268 Command->setDirection(ParamCommandComment::In, /* Explicit = */ false);
269 }
270 typedef BlockCommandComment::Argument Argument;
271 Argument *A = new (Allocator) Argument(SourceRange(ArgLocBegin,
272 ArgLocEnd),
273 Arg);
274 Command->setArgs(llvm::makeArrayRef(A, 1));
275}
276
277void Sema::actOnParamCommandFinish(ParamCommandComment *Command,
278 ParagraphComment *Paragraph) {
279 Command->setParagraph(Paragraph);
280 checkBlockCommandEmptyParagraph(Command);
281}
282
283TParamCommandComment *Sema::actOnTParamCommandStart(
284 SourceLocation LocBegin,
285 SourceLocation LocEnd,
286 unsigned CommandID,
287 CommandMarkerKind CommandMarker) {
288 TParamCommandComment *Command =
289 new (Allocator) TParamCommandComment(LocBegin, LocEnd, CommandID,
290 CommandMarker);
291
292 if (!isTemplateOrSpecialization())
293 Diag(Command->getLocation(),
294 diag::warn_doc_tparam_not_attached_to_a_template_decl)
295 << CommandMarker
296 << Command->getCommandNameRange(Traits);
297
298 return Command;
299}
300
301void Sema::actOnTParamCommandParamNameArg(TParamCommandComment *Command,
302 SourceLocation ArgLocBegin,
303 SourceLocation ArgLocEnd,
304 StringRef Arg) {
305 // Parser will not feed us more arguments than needed.
306 assert(Command->getNumArgs() == 0)((void)0);
307
308 typedef BlockCommandComment::Argument Argument;
309 Argument *A = new (Allocator) Argument(SourceRange(ArgLocBegin,
310 ArgLocEnd),
311 Arg);
312 Command->setArgs(llvm::makeArrayRef(A, 1));
313
314 if (!isTemplateOrSpecialization()) {
315 // We already warned that this \\tparam is not attached to a template decl.
316 return;
317 }
318
319 const TemplateParameterList *TemplateParameters =
320 ThisDeclInfo->TemplateParameters;
321 SmallVector<unsigned, 2> Position;
322 if (resolveTParamReference(Arg, TemplateParameters, &Position)) {
323 Command->setPosition(copyArray(llvm::makeArrayRef(Position)));
324 TParamCommandComment *&PrevCommand = TemplateParameterDocs[Arg];
325 if (PrevCommand) {
326 SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
327 Diag(ArgLocBegin, diag::warn_doc_tparam_duplicate)
328 << Arg << ArgRange;
329 Diag(PrevCommand->getLocation(), diag::note_doc_tparam_previous)
330 << PrevCommand->getParamNameRange();
331 }
332 PrevCommand = Command;
333 return;
334 }
335
336 SourceRange ArgRange(ArgLocBegin, ArgLocEnd);
337 Diag(ArgLocBegin, diag::warn_doc_tparam_not_found)
338 << Arg << ArgRange;
339
340 if (!TemplateParameters || TemplateParameters->size() == 0)
341 return;
342
343 StringRef CorrectedName;
344 if (TemplateParameters->size() == 1) {
345 const NamedDecl *Param = TemplateParameters->getParam(0);
346 const IdentifierInfo *II = Param->getIdentifier();
347 if (II)
348 CorrectedName = II->getName();
349 } else {
350 CorrectedName = correctTypoInTParamReference(Arg, TemplateParameters);
351 }
352
353 if (!CorrectedName.empty()) {
354 Diag(ArgLocBegin, diag::note_doc_tparam_name_suggestion)
355 << CorrectedName
356 << FixItHint::CreateReplacement(ArgRange, CorrectedName);
357 }
358}
359
360void Sema::actOnTParamCommandFinish(TParamCommandComment *Command,
361 ParagraphComment *Paragraph) {
362 Command->setParagraph(Paragraph);
363 checkBlockCommandEmptyParagraph(Command);
364}
365
366InlineCommandComment *Sema::actOnInlineCommand(SourceLocation CommandLocBegin,
367 SourceLocation CommandLocEnd,
368 unsigned CommandID) {
369 ArrayRef<InlineCommandComment::Argument> Args;
370 StringRef CommandName = Traits.getCommandInfo(CommandID)->Name;
371 return new (Allocator) InlineCommandComment(
372 CommandLocBegin,
373 CommandLocEnd,
374 CommandID,
375 getInlineCommandRenderKind(CommandName),
376 Args);
377}
378
379InlineCommandComment *Sema::actOnInlineCommand(SourceLocation CommandLocBegin,
380 SourceLocation CommandLocEnd,
381 unsigned CommandID,
382 SourceLocation ArgLocBegin,
383 SourceLocation ArgLocEnd,
384 StringRef Arg) {
385 typedef InlineCommandComment::Argument Argument;
386 Argument *A = new (Allocator) Argument(SourceRange(ArgLocBegin,
387 ArgLocEnd),
388 Arg);
389 StringRef CommandName = Traits.getCommandInfo(CommandID)->Name;
390
391 return new (Allocator) InlineCommandComment(
392 CommandLocBegin,
393 CommandLocEnd,
394 CommandID,
395 getInlineCommandRenderKind(CommandName),
396 llvm::makeArrayRef(A, 1));
397}
398
399InlineContentComment *Sema::actOnUnknownCommand(SourceLocation LocBegin,
400 SourceLocation LocEnd,
401 StringRef CommandName) {
402 unsigned CommandID = Traits.registerUnknownCommand(CommandName)->getID();
403 return actOnUnknownCommand(LocBegin, LocEnd, CommandID);
404}
405
406InlineContentComment *Sema::actOnUnknownCommand(SourceLocation LocBegin,
407 SourceLocation LocEnd,
408 unsigned CommandID) {
409 ArrayRef<InlineCommandComment::Argument> Args;
410 return new (Allocator) InlineCommandComment(
411 LocBegin, LocEnd, CommandID,
412 InlineCommandComment::RenderNormal,
413 Args);
414}
415
416TextComment *Sema::actOnText(SourceLocation LocBegin,
417 SourceLocation LocEnd,
418 StringRef Text) {
419 return new (Allocator) TextComment(LocBegin, LocEnd, Text);
420}
421
422VerbatimBlockComment *Sema::actOnVerbatimBlockStart(SourceLocation Loc,
423 unsigned CommandID) {
424 StringRef CommandName = Traits.getCommandInfo(CommandID)->Name;
425 return new (Allocator) VerbatimBlockComment(
426 Loc,
427 Loc.getLocWithOffset(1 + CommandName.size()),
428 CommandID);
429}
430
431VerbatimBlockLineComment *Sema::actOnVerbatimBlockLine(SourceLocation Loc,
432 StringRef Text) {
433 return new (Allocator) VerbatimBlockLineComment(Loc, Text);
434}
435
436void Sema::actOnVerbatimBlockFinish(
437 VerbatimBlockComment *Block,
438 SourceLocation CloseNameLocBegin,
439 StringRef CloseName,
440 ArrayRef<VerbatimBlockLineComment *> Lines) {
441 Block->setCloseName(CloseName, CloseNameLocBegin);
442 Block->setLines(Lines);
443}
444
445VerbatimLineComment *Sema::actOnVerbatimLine(SourceLocation LocBegin,
446 unsigned CommandID,
447 SourceLocation TextBegin,
448 StringRef Text) {
449 VerbatimLineComment *VL = new (Allocator) VerbatimLineComment(
450 LocBegin,
451 TextBegin.getLocWithOffset(Text.size()),
452 CommandID,
453 TextBegin,
454 Text);
455 checkFunctionDeclVerbatimLine(VL);
456 checkContainerDeclVerbatimLine(VL);
457 return VL;
458}
459
460HTMLStartTagComment *Sema::actOnHTMLStartTagStart(SourceLocation LocBegin,
461 StringRef TagName) {
462 return new (Allocator) HTMLStartTagComment(LocBegin, TagName);
463}
464
465void Sema::actOnHTMLStartTagFinish(
466 HTMLStartTagComment *Tag,
467 ArrayRef<HTMLStartTagComment::Attribute> Attrs,
468 SourceLocation GreaterLoc,
469 bool IsSelfClosing) {
470 Tag->setAttrs(Attrs);
471 Tag->setGreaterLoc(GreaterLoc);
472 if (IsSelfClosing)
473 Tag->setSelfClosing();
474 else if (!isHTMLEndTagForbidden(Tag->getTagName()))
475 HTMLOpenTags.push_back(Tag);
476}
477
478HTMLEndTagComment *Sema::actOnHTMLEndTag(SourceLocation LocBegin,
479 SourceLocation LocEnd,
480 StringRef TagName) {
481 HTMLEndTagComment *HET =
482 new (Allocator) HTMLEndTagComment(LocBegin, LocEnd, TagName);
483 if (isHTMLEndTagForbidden(TagName)) {
484 Diag(HET->getLocation(), diag::warn_doc_html_end_forbidden)
485 << TagName << HET->getSourceRange();
486 HET->setIsMalformed();
487 return HET;
488 }
489
490 bool FoundOpen = false;
491 for (SmallVectorImpl<HTMLStartTagComment *>::const_reverse_iterator
492 I = HTMLOpenTags.rbegin(), E = HTMLOpenTags.rend();
493 I != E; ++I) {
494 if ((*I)->getTagName() == TagName) {
495 FoundOpen = true;
496 break;
497 }
498 }
499 if (!FoundOpen) {
500 Diag(HET->getLocation(), diag::warn_doc_html_end_unbalanced)
501 << HET->getSourceRange();
502 HET->setIsMalformed();
503 return HET;
504 }
505
506 while (!HTMLOpenTags.empty()) {
507 HTMLStartTagComment *HST = HTMLOpenTags.pop_back_val();
508 StringRef LastNotClosedTagName = HST->getTagName();
509 if (LastNotClosedTagName == TagName) {
510 // If the start tag is malformed, end tag is malformed as well.
511 if (HST->isMalformed())
512 HET->setIsMalformed();
513 break;
514 }
515
516 if (isHTMLEndTagOptional(LastNotClosedTagName))
517 continue;
518
519 bool OpenLineInvalid;
520 const unsigned OpenLine = SourceMgr.getPresumedLineNumber(
521 HST->getLocation(),
522 &OpenLineInvalid);
523 bool CloseLineInvalid;
524 const unsigned CloseLine = SourceMgr.getPresumedLineNumber(
525 HET->getLocation(),
526 &CloseLineInvalid);
527
528 if (OpenLineInvalid || CloseLineInvalid || OpenLine == CloseLine) {
529 Diag(HST->getLocation(), diag::warn_doc_html_start_end_mismatch)
530 << HST->getTagName() << HET->getTagName()
531 << HST->getSourceRange() << HET->getSourceRange();
532 HST->setIsMalformed();
533 } else {
534 Diag(HST->getLocation(), diag::warn_doc_html_start_end_mismatch)
535 << HST->getTagName() << HET->getTagName()
536 << HST->getSourceRange();
537 Diag(HET->getLocation(), diag::note_doc_html_end_tag)
538 << HET->getSourceRange();
539 HST->setIsMalformed();
540 }
541 }
542
543 return HET;
544}
545
546FullComment *Sema::actOnFullComment(
547 ArrayRef<BlockContentComment *> Blocks) {
548 FullComment *FC = new (Allocator) FullComment(Blocks, ThisDeclInfo);
1
Calling 'operator new<llvm::MallocAllocator, 4096UL, 4096UL, 128UL>'
549 resolveParamCommandIndexes(FC);
550
551 // Complain about HTML tags that are not closed.
552 while (!HTMLOpenTags.empty()) {
553 HTMLStartTagComment *HST = HTMLOpenTags.pop_back_val();
554 if (isHTMLEndTagOptional(HST->getTagName()))
555 continue;
556
557 Diag(HST->getLocation(), diag::warn_doc_html_missing_end_tag)
558 << HST->getTagName() << HST->getSourceRange();
559 HST->setIsMalformed();
560 }
561
562 return FC;
563}
564
565void Sema::checkBlockCommandEmptyParagraph(BlockCommandComment *Command) {
566 if (Traits.getCommandInfo(Command->getCommandID())->IsEmptyParagraphAllowed)
567 return;
568
569 ParagraphComment *Paragraph = Command->getParagraph();
570 if (Paragraph->isWhitespace()) {
571 SourceLocation DiagLoc;
572 if (Command->getNumArgs() > 0)
573 DiagLoc = Command->getArgRange(Command->getNumArgs() - 1).getEnd();
574 if (!DiagLoc.isValid())
575 DiagLoc = Command->getCommandNameRange(Traits).getEnd();
576 Diag(DiagLoc, diag::warn_doc_block_command_empty_paragraph)
577 << Command->getCommandMarker()
578 << Command->getCommandName(Traits)
579 << Command->getSourceRange();
580 }
581}
582
583void Sema::checkReturnsCommand(const BlockCommandComment *Command) {
584 if (!Traits.getCommandInfo(Command->getCommandID())->IsReturnsCommand)
585 return;
586
587 assert(ThisDeclInfo && "should not call this check on a bare comment")((void)0);
588
589 // We allow the return command for all @properties because it can be used
590 // to document the value that the property getter returns.
591 if (isObjCPropertyDecl())
592 return;
593 if (isFunctionDecl() || isFunctionOrBlockPointerVarLikeDecl()) {
594 assert(!ThisDeclInfo->ReturnType.isNull() &&((void)0)
595 "should have a valid return type")((void)0);
596 if (ThisDeclInfo->ReturnType->isVoidType()) {
597 unsigned DiagKind;
598 switch (ThisDeclInfo->CommentDecl->getKind()) {
599 default:
600 if (ThisDeclInfo->IsObjCMethod)
601 DiagKind = 3;
602 else
603 DiagKind = 0;
604 break;
605 case Decl::CXXConstructor:
606 DiagKind = 1;
607 break;
608 case Decl::CXXDestructor:
609 DiagKind = 2;
610 break;
611 }
612 Diag(Command->getLocation(),
613 diag::warn_doc_returns_attached_to_a_void_function)
614 << Command->getCommandMarker()
615 << Command->getCommandName(Traits)
616 << DiagKind
617 << Command->getSourceRange();
618 }
619 return;
620 }
621
622 Diag(Command->getLocation(),
623 diag::warn_doc_returns_not_attached_to_a_function_decl)
624 << Command->getCommandMarker()
625 << Command->getCommandName(Traits)
626 << Command->getSourceRange();
627}
628
629void Sema::checkBlockCommandDuplicate(const BlockCommandComment *Command) {
630 const CommandInfo *Info = Traits.getCommandInfo(Command->getCommandID());
631 const BlockCommandComment *PrevCommand = nullptr;
632 if (Info->IsBriefCommand) {
633 if (!BriefCommand) {
634 BriefCommand = Command;
635 return;
636 }
637 PrevCommand = BriefCommand;
638 } else if (Info->IsHeaderfileCommand) {
639 if (!HeaderfileCommand) {
640 HeaderfileCommand = Command;
641 return;
642 }
643 PrevCommand = HeaderfileCommand;
644 } else {
645 // We don't want to check this command for duplicates.
646 return;
647 }
648 StringRef CommandName = Command->getCommandName(Traits);
649 StringRef PrevCommandName = PrevCommand->getCommandName(Traits);
650 Diag(Command->getLocation(), diag::warn_doc_block_command_duplicate)
651 << Command->getCommandMarker()
652 << CommandName
653 << Command->getSourceRange();
654 if (CommandName == PrevCommandName)
655 Diag(PrevCommand->getLocation(), diag::note_doc_block_command_previous)
656 << PrevCommand->getCommandMarker()
657 << PrevCommandName
658 << PrevCommand->getSourceRange();
659 else
660 Diag(PrevCommand->getLocation(),
661 diag::note_doc_block_command_previous_alias)
662 << PrevCommand->getCommandMarker()
663 << PrevCommandName
664 << CommandName;
665}
666
667void Sema::checkDeprecatedCommand(const BlockCommandComment *Command) {
668 if (!Traits.getCommandInfo(Command->getCommandID())->IsDeprecatedCommand)
669 return;
670
671 assert(ThisDeclInfo && "should not call this check on a bare comment")((void)0);
672
673 const Decl *D = ThisDeclInfo->CommentDecl;
674 if (!D)
675 return;
676
677 if (D->hasAttr<DeprecatedAttr>() ||
678 D->hasAttr<AvailabilityAttr>() ||
679 D->hasAttr<UnavailableAttr>())
680 return;
681
682 Diag(Command->getLocation(), diag::warn_doc_deprecated_not_sync)
683 << Command->getSourceRange() << Command->getCommandMarker();
684
685 // Try to emit a fixit with a deprecation attribute.
686 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
687 // Don't emit a Fix-It for non-member function definitions. GCC does not
688 // accept attributes on them.
689 const DeclContext *Ctx = FD->getDeclContext();
690 if ((!Ctx || !Ctx->isRecord()) &&
691 FD->doesThisDeclarationHaveABody())
692 return;
693
694 const LangOptions &LO = FD->getLangOpts();
695 const bool DoubleSquareBracket = LO.CPlusPlus14 || LO.C2x;
696 StringRef AttributeSpelling =
697 DoubleSquareBracket ? "[[deprecated]]" : "__attribute__((deprecated))";
698 if (PP) {
699 // Try to find a replacement macro:
700 // - In C2x/C++14 we prefer [[deprecated]].
701 // - If not found or an older C/C++ look for __attribute__((deprecated)).
702 StringRef MacroName;
703 if (DoubleSquareBracket) {
704 TokenValue Tokens[] = {tok::l_square, tok::l_square,
705 PP->getIdentifierInfo("deprecated"),
706 tok::r_square, tok::r_square};
707 MacroName = PP->getLastMacroWithSpelling(FD->getLocation(), Tokens);
708 if (!MacroName.empty())
709 AttributeSpelling = MacroName;
710 }
711
712 if (MacroName.empty()) {
713 TokenValue Tokens[] = {
714 tok::kw___attribute, tok::l_paren,
715 tok::l_paren, PP->getIdentifierInfo("deprecated"),
716 tok::r_paren, tok::r_paren};
717 StringRef MacroName =
718 PP->getLastMacroWithSpelling(FD->getLocation(), Tokens);
719 if (!MacroName.empty())
720 AttributeSpelling = MacroName;
721 }
722 }
723
724 SmallString<64> TextToInsert = AttributeSpelling;
725 TextToInsert += " ";
726 SourceLocation Loc = FD->getSourceRange().getBegin();
727 Diag(Loc, diag::note_add_deprecation_attr)
728 << FixItHint::CreateInsertion(Loc, TextToInsert);
729 }
730}
731
732void Sema::resolveParamCommandIndexes(const FullComment *FC) {
733 if (!isFunctionDecl()) {
734 // We already warned that \\param commands are not attached to a function
735 // decl.
736 return;
737 }
738
739 SmallVector<ParamCommandComment *, 8> UnresolvedParamCommands;
740
741 // Comment AST nodes that correspond to \c ParamVars for which we have
742 // found a \\param command or NULL if no documentation was found so far.
743 SmallVector<ParamCommandComment *, 8> ParamVarDocs;
744
745 ArrayRef<const ParmVarDecl *> ParamVars = getParamVars();
746 ParamVarDocs.resize(ParamVars.size(), nullptr);
747
748 // First pass over all \\param commands: resolve all parameter names.
749 for (Comment::child_iterator I = FC->child_begin(), E = FC->child_end();
750 I != E; ++I) {
751 ParamCommandComment *PCC = dyn_cast<ParamCommandComment>(*I);
752 if (!PCC || !PCC->hasParamName())
753 continue;
754 StringRef ParamName = PCC->getParamNameAsWritten();
755
756 // Check that referenced parameter name is in the function decl.
757 const unsigned ResolvedParamIndex = resolveParmVarReference(ParamName,
758 ParamVars);
759 if (ResolvedParamIndex == ParamCommandComment::VarArgParamIndex) {
760 PCC->setIsVarArgParam();
761 continue;
762 }
763 if (ResolvedParamIndex == ParamCommandComment::InvalidParamIndex) {
764 UnresolvedParamCommands.push_back(PCC);
765 continue;
766 }
767 PCC->setParamIndex(ResolvedParamIndex);
768 if (ParamVarDocs[ResolvedParamIndex]) {
769 SourceRange ArgRange = PCC->getParamNameRange();
770 Diag(ArgRange.getBegin(), diag::warn_doc_param_duplicate)
771 << ParamName << ArgRange;
772 ParamCommandComment *PrevCommand = ParamVarDocs[ResolvedParamIndex];
773 Diag(PrevCommand->getLocation(), diag::note_doc_param_previous)
774 << PrevCommand->getParamNameRange();
775 }
776 ParamVarDocs[ResolvedParamIndex] = PCC;
777 }
778
779 // Find parameter declarations that have no corresponding \\param.
780 SmallVector<const ParmVarDecl *, 8> OrphanedParamDecls;
781 for (unsigned i = 0, e = ParamVarDocs.size(); i != e; ++i) {
782 if (!ParamVarDocs[i])
783 OrphanedParamDecls.push_back(ParamVars[i]);
784 }
785
786 // Second pass over unresolved \\param commands: do typo correction.
787 // Suggest corrections from a set of parameter declarations that have no
788 // corresponding \\param.
789 for (unsigned i = 0, e = UnresolvedParamCommands.size(); i != e; ++i) {
790 const ParamCommandComment *PCC = UnresolvedParamCommands[i];
791
792 SourceRange ArgRange = PCC->getParamNameRange();
793 StringRef ParamName = PCC->getParamNameAsWritten();
794 Diag(ArgRange.getBegin(), diag::warn_doc_param_not_found)
795 << ParamName << ArgRange;
796
797 // All parameters documented -- can't suggest a correction.
798 if (OrphanedParamDecls.size() == 0)
799 continue;
800
801 unsigned CorrectedParamIndex = ParamCommandComment::InvalidParamIndex;
802 if (OrphanedParamDecls.size() == 1) {
803 // If one parameter is not documented then that parameter is the only
804 // possible suggestion.
805 CorrectedParamIndex = 0;
806 } else {
807 // Do typo correction.
808 CorrectedParamIndex = correctTypoInParmVarReference(ParamName,
809 OrphanedParamDecls);
810 }
811 if (CorrectedParamIndex != ParamCommandComment::InvalidParamIndex) {
812 const ParmVarDecl *CorrectedPVD = OrphanedParamDecls[CorrectedParamIndex];
813 if (const IdentifierInfo *CorrectedII = CorrectedPVD->getIdentifier())
814 Diag(ArgRange.getBegin(), diag::note_doc_param_name_suggestion)
815 << CorrectedII->getName()
816 << FixItHint::CreateReplacement(ArgRange, CorrectedII->getName());
817 }
818 }
819}
820
821bool Sema::isFunctionDecl() {
822 if (!ThisDeclInfo)
823 return false;
824 if (!ThisDeclInfo->IsFilled)
825 inspectThisDecl();
826 return ThisDeclInfo->getKind() == DeclInfo::FunctionKind;
827}
828
829bool Sema::isAnyFunctionDecl() {
830 return isFunctionDecl() && ThisDeclInfo->CurrentDecl &&
831 isa<FunctionDecl>(ThisDeclInfo->CurrentDecl);
832}
833
834bool Sema::isFunctionOrMethodVariadic() {
835 if (!isFunctionDecl() || !ThisDeclInfo->CurrentDecl)
836 return false;
837 if (const FunctionDecl *FD =
838 dyn_cast<FunctionDecl>(ThisDeclInfo->CurrentDecl))
839 return FD->isVariadic();
840 if (const FunctionTemplateDecl *FTD =
841 dyn_cast<FunctionTemplateDecl>(ThisDeclInfo->CurrentDecl))
842 return FTD->getTemplatedDecl()->isVariadic();
843 if (const ObjCMethodDecl *MD =
844 dyn_cast<ObjCMethodDecl>(ThisDeclInfo->CurrentDecl))
845 return MD->isVariadic();
846 if (const TypedefNameDecl *TD =
847 dyn_cast<TypedefNameDecl>(ThisDeclInfo->CurrentDecl)) {
848 QualType Type = TD->getUnderlyingType();
849 if (Type->isFunctionPointerType() || Type->isBlockPointerType())
850 Type = Type->getPointeeType();
851 if (const auto *FT = Type->getAs<FunctionProtoType>())
852 return FT->isVariadic();
853 }
854 return false;
855}
856
857bool Sema::isObjCMethodDecl() {
858 return isFunctionDecl() && ThisDeclInfo->CurrentDecl &&
859 isa<ObjCMethodDecl>(ThisDeclInfo->CurrentDecl);
860}
861
862bool Sema::isFunctionPointerVarDecl() {
863 if (!ThisDeclInfo)
864 return false;
865 if (!ThisDeclInfo->IsFilled)
866 inspectThisDecl();
867 if (ThisDeclInfo->getKind() == DeclInfo::VariableKind) {
868 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDeclInfo->CurrentDecl)) {
869 QualType QT = VD->getType();
870 return QT->isFunctionPointerType();
871 }
872 }
873 return false;
874}
875
876bool Sema::isFunctionOrBlockPointerVarLikeDecl() {
877 if (!ThisDeclInfo)
878 return false;
879 if (!ThisDeclInfo->IsFilled)
880 inspectThisDecl();
881 if (ThisDeclInfo->getKind() != DeclInfo::VariableKind ||
882 !ThisDeclInfo->CurrentDecl)
883 return false;
884 QualType QT;
885 if (const auto *VD = dyn_cast<DeclaratorDecl>(ThisDeclInfo->CurrentDecl))
886 QT = VD->getType();
887 else if (const auto *PD =
888 dyn_cast<ObjCPropertyDecl>(ThisDeclInfo->CurrentDecl))
889 QT = PD->getType();
890 else
891 return false;
892 // We would like to warn about the 'returns'/'param' commands for
893 // variables that don't directly specify the function type, so type aliases
894 // can be ignored.
895 if (QT->getAs<TypedefType>())
896 return false;
897 if (const auto *P = QT->getAs<PointerType>())
898 if (P->getPointeeType()->getAs<TypedefType>())
899 return false;
900 if (const auto *P = QT->getAs<BlockPointerType>())
901 if (P->getPointeeType()->getAs<TypedefType>())
902 return false;
903 return QT->isFunctionPointerType() || QT->isBlockPointerType();
904}
905
906bool Sema::isObjCPropertyDecl() {
907 if (!ThisDeclInfo)
908 return false;
909 if (!ThisDeclInfo->IsFilled)
910 inspectThisDecl();
911 return ThisDeclInfo->CurrentDecl->getKind() == Decl::ObjCProperty;
912}
913
914bool Sema::isTemplateOrSpecialization() {
915 if (!ThisDeclInfo)
916 return false;
917 if (!ThisDeclInfo->IsFilled)
918 inspectThisDecl();
919 return ThisDeclInfo->getTemplateKind() != DeclInfo::NotTemplate;
920}
921
922bool Sema::isRecordLikeDecl() {
923 if (!ThisDeclInfo)
924 return false;
925 if (!ThisDeclInfo->IsFilled)
926 inspectThisDecl();
927 return isUnionDecl() || isClassOrStructDecl() || isObjCInterfaceDecl() ||
928 isObjCProtocolDecl();
929}
930
931bool Sema::isUnionDecl() {
932 if (!ThisDeclInfo)
933 return false;
934 if (!ThisDeclInfo->IsFilled)
935 inspectThisDecl();
936 if (const RecordDecl *RD =
937 dyn_cast_or_null<RecordDecl>(ThisDeclInfo->CurrentDecl))
938 return RD->isUnion();
939 return false;
940}
941static bool isClassOrStructDeclImpl(const Decl *D) {
942 if (auto *record = dyn_cast_or_null<RecordDecl>(D))
943 return !record->isUnion();
944
945 return false;
946}
947
948bool Sema::isClassOrStructDecl() {
949 if (!ThisDeclInfo)
950 return false;
951 if (!ThisDeclInfo->IsFilled)
952 inspectThisDecl();
953
954 if (!ThisDeclInfo->CurrentDecl)
955 return false;
956
957 return isClassOrStructDeclImpl(ThisDeclInfo->CurrentDecl);
958}
959
960bool Sema::isClassOrStructOrTagTypedefDecl() {
961 if (!ThisDeclInfo)
962 return false;
963 if (!ThisDeclInfo->IsFilled)
964 inspectThisDecl();
965
966 if (!ThisDeclInfo->CurrentDecl)
967 return false;
968
969 if (isClassOrStructDeclImpl(ThisDeclInfo->CurrentDecl))
970 return true;
971
972 if (auto *ThisTypedefDecl = dyn_cast<TypedefDecl>(ThisDeclInfo->CurrentDecl)) {
973 auto UnderlyingType = ThisTypedefDecl->getUnderlyingType();
974 if (auto ThisElaboratedType = dyn_cast<ElaboratedType>(UnderlyingType)) {
975 auto DesugaredType = ThisElaboratedType->desugar();
976 if (auto *DesugaredTypePtr = DesugaredType.getTypePtrOrNull()) {
977 if (auto *ThisRecordType = dyn_cast<RecordType>(DesugaredTypePtr)) {
978 return isClassOrStructDeclImpl(ThisRecordType->getAsRecordDecl());
979 }
980 }
981 }
982 }
983
984 return false;
985}
986
987bool Sema::isClassTemplateDecl() {
988 if (!ThisDeclInfo)
989 return false;
990 if (!ThisDeclInfo->IsFilled)
991 inspectThisDecl();
992 return ThisDeclInfo->CurrentDecl &&
993 (isa<ClassTemplateDecl>(ThisDeclInfo->CurrentDecl));
994}
995
996bool Sema::isFunctionTemplateDecl() {
997 if (!ThisDeclInfo)
998 return false;
999 if (!ThisDeclInfo->IsFilled)
1000 inspectThisDecl();
1001 return ThisDeclInfo->CurrentDecl &&
1002 (isa<FunctionTemplateDecl>(ThisDeclInfo->CurrentDecl));
1003}
1004
1005bool Sema::isObjCInterfaceDecl() {
1006 if (!ThisDeclInfo)
1007 return false;
1008 if (!ThisDeclInfo->IsFilled)
1009 inspectThisDecl();
1010 return ThisDeclInfo->CurrentDecl &&
1011 isa<ObjCInterfaceDecl>(ThisDeclInfo->CurrentDecl);
1012}
1013
1014bool Sema::isObjCProtocolDecl() {
1015 if (!ThisDeclInfo)
1016 return false;
1017 if (!ThisDeclInfo->IsFilled)
1018 inspectThisDecl();
1019 return ThisDeclInfo->CurrentDecl &&
1020 isa<ObjCProtocolDecl>(ThisDeclInfo->CurrentDecl);
1021}
1022
1023ArrayRef<const ParmVarDecl *> Sema::getParamVars() {
1024 if (!ThisDeclInfo->IsFilled)
1025 inspectThisDecl();
1026 return ThisDeclInfo->ParamVars;
1027}
1028
1029void Sema::inspectThisDecl() {
1030 ThisDeclInfo->fill();
1031}
1032
1033unsigned Sema::resolveParmVarReference(StringRef Name,
1034 ArrayRef<const ParmVarDecl *> ParamVars) {
1035 for (unsigned i = 0, e = ParamVars.size(); i != e; ++i) {
1036 const IdentifierInfo *II = ParamVars[i]->getIdentifier();
1037 if (II && II->getName() == Name)
1038 return i;
1039 }
1040 if (Name == "..." && isFunctionOrMethodVariadic())
1041 return ParamCommandComment::VarArgParamIndex;
1042 return ParamCommandComment::InvalidParamIndex;
1043}
1044
1045namespace {
1046class SimpleTypoCorrector {
1047 const NamedDecl *BestDecl;
1048
1049 StringRef Typo;
1050 const unsigned MaxEditDistance;
1051
1052 unsigned BestEditDistance;
1053 unsigned BestIndex;
1054 unsigned NextIndex;
1055
1056public:
1057 explicit SimpleTypoCorrector(StringRef Typo)
1058 : BestDecl(nullptr), Typo(Typo), MaxEditDistance((Typo.size() + 2) / 3),
1059 BestEditDistance(MaxEditDistance + 1), BestIndex(0), NextIndex(0) {}
1060
1061 void addDecl(const NamedDecl *ND);
1062
1063 const NamedDecl *getBestDecl() const {
1064 if (BestEditDistance > MaxEditDistance)
1065 return nullptr;
1066
1067 return BestDecl;
1068 }
1069
1070 unsigned getBestDeclIndex() const {
1071 assert(getBestDecl())((void)0);
1072 return BestIndex;
1073 }
1074};
1075
1076void SimpleTypoCorrector::addDecl(const NamedDecl *ND) {
1077 unsigned CurrIndex = NextIndex++;
1078
1079 const IdentifierInfo *II = ND->getIdentifier();
1080 if (!II)
1081 return;
1082
1083 StringRef Name = II->getName();
1084 unsigned MinPossibleEditDistance = abs((int)Name.size() - (int)Typo.size());
1085 if (MinPossibleEditDistance > 0 &&
1086 Typo.size() / MinPossibleEditDistance < 3)
1087 return;
1088
1089 unsigned EditDistance = Typo.edit_distance(Name, true, MaxEditDistance);
1090 if (EditDistance < BestEditDistance) {
1091 BestEditDistance = EditDistance;
1092 BestDecl = ND;
1093 BestIndex = CurrIndex;
1094 }
1095}
1096} // end anonymous namespace
1097
1098unsigned Sema::correctTypoInParmVarReference(
1099 StringRef Typo,
1100 ArrayRef<const ParmVarDecl *> ParamVars) {
1101 SimpleTypoCorrector Corrector(Typo);
1102 for (unsigned i = 0, e = ParamVars.size(); i != e; ++i)
1103 Corrector.addDecl(ParamVars[i]);
1104 if (Corrector.getBestDecl())
1105 return Corrector.getBestDeclIndex();
1106 else
1107 return ParamCommandComment::InvalidParamIndex;
1108}
1109
1110namespace {
1111bool ResolveTParamReferenceHelper(
1112 StringRef Name,
1113 const TemplateParameterList *TemplateParameters,
1114 SmallVectorImpl<unsigned> *Position) {
1115 for (unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) {
1116 const NamedDecl *Param = TemplateParameters->getParam(i);
1117 const IdentifierInfo *II = Param->getIdentifier();
1118 if (II && II->getName() == Name) {
1119 Position->push_back(i);
1120 return true;
1121 }
1122
1123 if (const TemplateTemplateParmDecl *TTP =
1124 dyn_cast<TemplateTemplateParmDecl>(Param)) {
1125 Position->push_back(i);
1126 if (ResolveTParamReferenceHelper(Name, TTP->getTemplateParameters(),
1127 Position))
1128 return true;
1129 Position->pop_back();
1130 }
1131 }
1132 return false;
1133}
1134} // end anonymous namespace
1135
1136bool Sema::resolveTParamReference(
1137 StringRef Name,
1138 const TemplateParameterList *TemplateParameters,
1139 SmallVectorImpl<unsigned> *Position) {
1140 Position->clear();
1141 if (!TemplateParameters)
1142 return false;
1143
1144 return ResolveTParamReferenceHelper(Name, TemplateParameters, Position);
1145}
1146
1147namespace {
1148void CorrectTypoInTParamReferenceHelper(
1149 const TemplateParameterList *TemplateParameters,
1150 SimpleTypoCorrector &Corrector) {
1151 for (unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) {
1152 const NamedDecl *Param = TemplateParameters->getParam(i);
1153 Corrector.addDecl(Param);
1154
1155 if (const TemplateTemplateParmDecl *TTP =
1156 dyn_cast<TemplateTemplateParmDecl>(Param))
1157 CorrectTypoInTParamReferenceHelper(TTP->getTemplateParameters(),
1158 Corrector);
1159 }
1160}
1161} // end anonymous namespace
1162
1163StringRef Sema::correctTypoInTParamReference(
1164 StringRef Typo,
1165 const TemplateParameterList *TemplateParameters) {
1166 SimpleTypoCorrector Corrector(Typo);
1167 CorrectTypoInTParamReferenceHelper(TemplateParameters, Corrector);
1168 if (const NamedDecl *ND = Corrector.getBestDecl()) {
1169 const IdentifierInfo *II = ND->getIdentifier();
1170 assert(II && "SimpleTypoCorrector should not return this decl")((void)0);
1171 return II->getName();
1172 }
1173 return StringRef();
1174}
1175
1176InlineCommandComment::RenderKind
1177Sema::getInlineCommandRenderKind(StringRef Name) const {
1178 assert(Traits.getCommandInfo(Name)->IsInlineCommand)((void)0);
1179
1180 return llvm::StringSwitch<InlineCommandComment::RenderKind>(Name)
1181 .Case("b", InlineCommandComment::RenderBold)
1182 .Cases("c", "p", InlineCommandComment::RenderMonospaced)
1183 .Cases("a", "e", "em", InlineCommandComment::RenderEmphasized)
1184 .Case("anchor", InlineCommandComment::RenderAnchor)
1185 .Default(InlineCommandComment::RenderNormal);
1186}
1187
1188} // end namespace comments
1189} // end namespace clang

/usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/llvm/include/llvm/Support/Allocator.h

1//===- Allocator.h - Simple memory allocation abstraction -------*- 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/// \file
9///
10/// This file defines the BumpPtrAllocator interface. BumpPtrAllocator conforms
11/// to the LLVM "Allocator" concept and is similar to MallocAllocator, but
12/// objects cannot be deallocated. Their lifetime is tied to the lifetime of the
13/// allocator.
14///
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_SUPPORT_ALLOCATOR_H
18#define LLVM_SUPPORT_ALLOCATOR_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/Support/Alignment.h"
23#include "llvm/Support/AllocatorBase.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/MemAlloc.h"
28#include <algorithm>
29#include <cassert>
30#include <cstddef>
31#include <cstdint>
32#include <cstdlib>
33#include <iterator>
34#include <type_traits>
35#include <utility>
36
37namespace llvm {
38
39namespace detail {
40
41// We call out to an external function to actually print the message as the
42// printing code uses Allocator.h in its implementation.
43void printBumpPtrAllocatorStats(unsigned NumSlabs, size_t BytesAllocated,
44 size_t TotalMemory);
45
46} // end namespace detail
47
48/// Allocate memory in an ever growing pool, as if by bump-pointer.
49///
50/// This isn't strictly a bump-pointer allocator as it uses backing slabs of
51/// memory rather than relying on a boundless contiguous heap. However, it has
52/// bump-pointer semantics in that it is a monotonically growing pool of memory
53/// where every allocation is found by merely allocating the next N bytes in
54/// the slab, or the next N bytes in the next slab.
55///
56/// Note that this also has a threshold for forcing allocations above a certain
57/// size into their own slab.
58///
59/// The BumpPtrAllocatorImpl template defaults to using a MallocAllocator
60/// object, which wraps malloc, to allocate memory, but it can be changed to
61/// use a custom allocator.
62///
63/// The GrowthDelay specifies after how many allocated slabs the allocator
64/// increases the size of the slabs.
65template <typename AllocatorT = MallocAllocator, size_t SlabSize = 4096,
66 size_t SizeThreshold = SlabSize, size_t GrowthDelay = 128>
67class BumpPtrAllocatorImpl
68 : public AllocatorBase<BumpPtrAllocatorImpl<AllocatorT, SlabSize,
69 SizeThreshold, GrowthDelay>>,
70 private AllocatorT {
71public:
72 static_assert(SizeThreshold <= SlabSize,
73 "The SizeThreshold must be at most the SlabSize to ensure "
74 "that objects larger than a slab go into their own memory "
75 "allocation.");
76 static_assert(GrowthDelay > 0,
77 "GrowthDelay must be at least 1 which already increases the"
78 "slab size after each allocated slab.");
79
80 BumpPtrAllocatorImpl() = default;
81
82 template <typename T>
83 BumpPtrAllocatorImpl(T &&Allocator)
84 : AllocatorT(std::forward<T &&>(Allocator)) {}
85
86 // Manually implement a move constructor as we must clear the old allocator's
87 // slabs as a matter of correctness.
88 BumpPtrAllocatorImpl(BumpPtrAllocatorImpl &&Old)
89 : AllocatorT(static_cast<AllocatorT &&>(Old)), CurPtr(Old.CurPtr),
90 End(Old.End), Slabs(std::move(Old.Slabs)),
91 CustomSizedSlabs(std::move(Old.CustomSizedSlabs)),
92 BytesAllocated(Old.BytesAllocated), RedZoneSize(Old.RedZoneSize) {
93 Old.CurPtr = Old.End = nullptr;
94 Old.BytesAllocated = 0;
95 Old.Slabs.clear();
96 Old.CustomSizedSlabs.clear();
97 }
98
99 ~BumpPtrAllocatorImpl() {
100 DeallocateSlabs(Slabs.begin(), Slabs.end());
101 DeallocateCustomSizedSlabs();
102 }
103
104 BumpPtrAllocatorImpl &operator=(BumpPtrAllocatorImpl &&RHS) {
105 DeallocateSlabs(Slabs.begin(), Slabs.end());
106 DeallocateCustomSizedSlabs();
107
108 CurPtr = RHS.CurPtr;
109 End = RHS.End;
110 BytesAllocated = RHS.BytesAllocated;
111 RedZoneSize = RHS.RedZoneSize;
112 Slabs = std::move(RHS.Slabs);
113 CustomSizedSlabs = std::move(RHS.CustomSizedSlabs);
114 AllocatorT::operator=(static_cast<AllocatorT &&>(RHS));
115
116 RHS.CurPtr = RHS.End = nullptr;
117 RHS.BytesAllocated = 0;
118 RHS.Slabs.clear();
119 RHS.CustomSizedSlabs.clear();
120 return *this;
121 }
122
123 /// Deallocate all but the current slab and reset the current pointer
124 /// to the beginning of it, freeing all memory allocated so far.
125 void Reset() {
126 // Deallocate all but the first slab, and deallocate all custom-sized slabs.
127 DeallocateCustomSizedSlabs();
128 CustomSizedSlabs.clear();
129
130 if (Slabs.empty())
131 return;
132
133 // Reset the state.
134 BytesAllocated = 0;
135 CurPtr = (char *)Slabs.front();
136 End = CurPtr + SlabSize;
137
138 __asan_poison_memory_region(*Slabs.begin(), computeSlabSize(0));
139 DeallocateSlabs(std::next(Slabs.begin()), Slabs.end());
140 Slabs.erase(std::next(Slabs.begin()), Slabs.end());
141 }
142
143 /// Allocate space at the specified alignment.
144 LLVM_ATTRIBUTE_RETURNS_NONNULL__attribute__((returns_nonnull)) LLVM_ATTRIBUTE_RETURNS_NOALIAS__attribute__((__malloc__)) void *
145 Allocate(size_t Size, Align Alignment) {
146 // Keep track of how many bytes we've allocated.
147 BytesAllocated += Size;
148
149 size_t Adjustment = offsetToAlignedAddr(CurPtr, Alignment);
4
Calling 'offsetToAlignedAddr'
150 assert(Adjustment + Size >= Size && "Adjustment + Size must not overflow")((void)0);
151
152 size_t SizeToAllocate = Size;
153#if LLVM_ADDRESS_SANITIZER_BUILD0
154 // Add trailing bytes as a "red zone" under ASan.
155 SizeToAllocate += RedZoneSize;
156#endif
157
158 // Check if we have enough space.
159 if (Adjustment + SizeToAllocate <= size_t(End - CurPtr)) {
160 char *AlignedPtr = CurPtr + Adjustment;
161 CurPtr = AlignedPtr + SizeToAllocate;
162 // Update the allocation point of this memory block in MemorySanitizer.
163 // Without this, MemorySanitizer messages for values originated from here
164 // will point to the allocation of the entire slab.
165 __msan_allocated_memory(AlignedPtr, Size);
166 // Similarly, tell ASan about this space.
167 __asan_unpoison_memory_region(AlignedPtr, Size);
168 return AlignedPtr;
169 }
170
171 // If Size is really big, allocate a separate slab for it.
172 size_t PaddedSize = SizeToAllocate + Alignment.value() - 1;
173 if (PaddedSize > SizeThreshold) {
174 void *NewSlab =
175 AllocatorT::Allocate(PaddedSize, alignof(std::max_align_t));
176 // We own the new slab and don't want anyone reading anyting other than
177 // pieces returned from this method. So poison the whole slab.
178 __asan_poison_memory_region(NewSlab, PaddedSize);
179 CustomSizedSlabs.push_back(std::make_pair(NewSlab, PaddedSize));
180
181 uintptr_t AlignedAddr = alignAddr(NewSlab, Alignment);
182 assert(AlignedAddr + Size <= (uintptr_t)NewSlab + PaddedSize)((void)0);
183 char *AlignedPtr = (char*)AlignedAddr;
184 __msan_allocated_memory(AlignedPtr, Size);
185 __asan_unpoison_memory_region(AlignedPtr, Size);
186 return AlignedPtr;
187 }
188
189 // Otherwise, start a new slab and try again.
190 StartNewSlab();
191 uintptr_t AlignedAddr = alignAddr(CurPtr, Alignment);
192 assert(AlignedAddr + SizeToAllocate <= (uintptr_t)End &&((void)0)
193 "Unable to allocate memory!")((void)0);
194 char *AlignedPtr = (char*)AlignedAddr;
195 CurPtr = AlignedPtr + SizeToAllocate;
196 __msan_allocated_memory(AlignedPtr, Size);
197 __asan_unpoison_memory_region(AlignedPtr, Size);
198 return AlignedPtr;
199 }
200
201 inline LLVM_ATTRIBUTE_RETURNS_NONNULL__attribute__((returns_nonnull)) LLVM_ATTRIBUTE_RETURNS_NOALIAS__attribute__((__malloc__)) void *
202 Allocate(size_t Size, size_t Alignment) {
203 assert(Alignment > 0 && "0-byte alignment is not allowed. Use 1 instead.")((void)0);
204 return Allocate(Size, Align(Alignment));
3
Calling 'BumpPtrAllocatorImpl::Allocate'
205 }
206
207 // Pull in base class overloads.
208 using AllocatorBase<BumpPtrAllocatorImpl>::Allocate;
209
210 // Bump pointer allocators are expected to never free their storage; and
211 // clients expect pointers to remain valid for non-dereferencing uses even
212 // after deallocation.
213 void Deallocate(const void *Ptr, size_t Size, size_t /*Alignment*/) {
214 __asan_poison_memory_region(Ptr, Size);
215 }
216
217 // Pull in base class overloads.
218 using AllocatorBase<BumpPtrAllocatorImpl>::Deallocate;
219
220 size_t GetNumSlabs() const { return Slabs.size() + CustomSizedSlabs.size(); }
221
222 /// \return An index uniquely and reproducibly identifying
223 /// an input pointer \p Ptr in the given allocator.
224 /// The returned value is negative iff the object is inside a custom-size
225 /// slab.
226 /// Returns an empty optional if the pointer is not found in the allocator.
227 llvm::Optional<int64_t> identifyObject(const void *Ptr) {
228 const char *P = static_cast<const char *>(Ptr);
229 int64_t InSlabIdx = 0;
230 for (size_t Idx = 0, E = Slabs.size(); Idx < E; Idx++) {
231 const char *S = static_cast<const char *>(Slabs[Idx]);
232 if (P >= S && P < S + computeSlabSize(Idx))
233 return InSlabIdx + static_cast<int64_t>(P - S);
234 InSlabIdx += static_cast<int64_t>(computeSlabSize(Idx));
235 }
236
237 // Use negative index to denote custom sized slabs.
238 int64_t InCustomSizedSlabIdx = -1;
239 for (size_t Idx = 0, E = CustomSizedSlabs.size(); Idx < E; Idx++) {
240 const char *S = static_cast<const char *>(CustomSizedSlabs[Idx].first);
241 size_t Size = CustomSizedSlabs[Idx].second;
242 if (P >= S && P < S + Size)
243 return InCustomSizedSlabIdx - static_cast<int64_t>(P - S);
244 InCustomSizedSlabIdx -= static_cast<int64_t>(Size);
245 }
246 return None;
247 }
248
249 /// A wrapper around identifyObject that additionally asserts that
250 /// the object is indeed within the allocator.
251 /// \return An index uniquely and reproducibly identifying
252 /// an input pointer \p Ptr in the given allocator.
253 int64_t identifyKnownObject(const void *Ptr) {
254 Optional<int64_t> Out = identifyObject(Ptr);
255 assert(Out && "Wrong allocator used")((void)0);
256 return *Out;
257 }
258
259 /// A wrapper around identifyKnownObject. Accepts type information
260 /// about the object and produces a smaller identifier by relying on
261 /// the alignment information. Note that sub-classes may have different
262 /// alignment, so the most base class should be passed as template parameter
263 /// in order to obtain correct results. For that reason automatic template
264 /// parameter deduction is disabled.
265 /// \return An index uniquely and reproducibly identifying
266 /// an input pointer \p Ptr in the given allocator. This identifier is
267 /// different from the ones produced by identifyObject and
268 /// identifyAlignedObject.
269 template <typename T>
270 int64_t identifyKnownAlignedObject(const void *Ptr) {
271 int64_t Out = identifyKnownObject(Ptr);
272 assert(Out % alignof(T) == 0 && "Wrong alignment information")((void)0);
273 return Out / alignof(T);
274 }
275
276 size_t getTotalMemory() const {
277 size_t TotalMemory = 0;
278 for (auto I = Slabs.begin(), E = Slabs.end(); I != E; ++I)
279 TotalMemory += computeSlabSize(std::distance(Slabs.begin(), I));
280 for (auto &PtrAndSize : CustomSizedSlabs)
281 TotalMemory += PtrAndSize.second;
282 return TotalMemory;
283 }
284
285 size_t getBytesAllocated() const { return BytesAllocated; }
286
287 void setRedZoneSize(size_t NewSize) {
288 RedZoneSize = NewSize;
289 }
290
291 void PrintStats() const {
292 detail::printBumpPtrAllocatorStats(Slabs.size(), BytesAllocated,
293 getTotalMemory());
294 }
295
296private:
297 /// The current pointer into the current slab.
298 ///
299 /// This points to the next free byte in the slab.
300 char *CurPtr = nullptr;
301
302 /// The end of the current slab.
303 char *End = nullptr;
304
305 /// The slabs allocated so far.
306 SmallVector<void *, 4> Slabs;
307
308 /// Custom-sized slabs allocated for too-large allocation requests.
309 SmallVector<std::pair<void *, size_t>, 0> CustomSizedSlabs;
310
311 /// How many bytes we've allocated.
312 ///
313 /// Used so that we can compute how much space was wasted.
314 size_t BytesAllocated = 0;
315
316 /// The number of bytes to put between allocations when running under
317 /// a sanitizer.
318 size_t RedZoneSize = 1;
319
320 static size_t computeSlabSize(unsigned SlabIdx) {
321 // Scale the actual allocated slab size based on the number of slabs
322 // allocated. Every GrowthDelay slabs allocated, we double
323 // the allocated size to reduce allocation frequency, but saturate at
324 // multiplying the slab size by 2^30.
325 return SlabSize *
326 ((size_t)1 << std::min<size_t>(30, SlabIdx / GrowthDelay));
327 }
328
329 /// Allocate a new slab and move the bump pointers over into the new
330 /// slab, modifying CurPtr and End.
331 void StartNewSlab() {
332 size_t AllocatedSlabSize = computeSlabSize(Slabs.size());
333
334 void *NewSlab =
335 AllocatorT::Allocate(AllocatedSlabSize, alignof(std::max_align_t));
336 // We own the new slab and don't want anyone reading anything other than
337 // pieces returned from this method. So poison the whole slab.
338 __asan_poison_memory_region(NewSlab, AllocatedSlabSize);
339
340 Slabs.push_back(NewSlab);
341 CurPtr = (char *)(NewSlab);
342 End = ((char *)NewSlab) + AllocatedSlabSize;
343 }
344
345 /// Deallocate a sequence of slabs.
346 void DeallocateSlabs(SmallVectorImpl<void *>::iterator I,
347 SmallVectorImpl<void *>::iterator E) {
348 for (; I != E; ++I) {
349 size_t AllocatedSlabSize =
350 computeSlabSize(std::distance(Slabs.begin(), I));
351 AllocatorT::Deallocate(*I, AllocatedSlabSize, alignof(std::max_align_t));
352 }
353 }
354
355 /// Deallocate all memory for custom sized slabs.
356 void DeallocateCustomSizedSlabs() {
357 for (auto &PtrAndSize : CustomSizedSlabs) {
358 void *Ptr = PtrAndSize.first;
359 size_t Size = PtrAndSize.second;
360 AllocatorT::Deallocate(Ptr, Size, alignof(std::max_align_t));
361 }
362 }
363
364 template <typename T> friend class SpecificBumpPtrAllocator;
365};
366
367/// The standard BumpPtrAllocator which just uses the default template
368/// parameters.
369typedef BumpPtrAllocatorImpl<> BumpPtrAllocator;
370
371/// A BumpPtrAllocator that allows only elements of a specific type to be
372/// allocated.
373///
374/// This allows calling the destructor in DestroyAll() and when the allocator is
375/// destroyed.
376template <typename T> class SpecificBumpPtrAllocator {
377 BumpPtrAllocator Allocator;
378
379public:
380 SpecificBumpPtrAllocator() {
381 // Because SpecificBumpPtrAllocator walks the memory to call destructors,
382 // it can't have red zones between allocations.
383 Allocator.setRedZoneSize(0);
384 }
385 SpecificBumpPtrAllocator(SpecificBumpPtrAllocator &&Old)
386 : Allocator(std::move(Old.Allocator)) {}
387 ~SpecificBumpPtrAllocator() { DestroyAll(); }
388
389 SpecificBumpPtrAllocator &operator=(SpecificBumpPtrAllocator &&RHS) {
390 Allocator = std::move(RHS.Allocator);
391 return *this;
392 }
393
394 /// Call the destructor of each allocated object and deallocate all but the
395 /// current slab and reset the current pointer to the beginning of it, freeing
396 /// all memory allocated so far.
397 void DestroyAll() {
398 auto DestroyElements = [](char *Begin, char *End) {
399 assert(Begin == (char *)alignAddr(Begin, Align::Of<T>()))((void)0);
400 for (char *Ptr = Begin; Ptr + sizeof(T) <= End; Ptr += sizeof(T))
401 reinterpret_cast<T *>(Ptr)->~T();
402 };
403
404 for (auto I = Allocator.Slabs.begin(), E = Allocator.Slabs.end(); I != E;
405 ++I) {
406 size_t AllocatedSlabSize = BumpPtrAllocator::computeSlabSize(
407 std::distance(Allocator.Slabs.begin(), I));
408 char *Begin = (char *)alignAddr(*I, Align::Of<T>());
409 char *End = *I == Allocator.Slabs.back() ? Allocator.CurPtr
410 : (char *)*I + AllocatedSlabSize;
411
412 DestroyElements(Begin, End);
413 }
414
415 for (auto &PtrAndSize : Allocator.CustomSizedSlabs) {
416 void *Ptr = PtrAndSize.first;
417 size_t Size = PtrAndSize.second;
418 DestroyElements((char *)alignAddr(Ptr, Align::Of<T>()),
419 (char *)Ptr + Size);
420 }
421
422 Allocator.Reset();
423 }
424
425 /// Allocate space for an array of objects without constructing them.
426 T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
427};
428
429} // end namespace llvm
430
431template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
432 size_t GrowthDelay>
433void *
434operator new(size_t Size,
435 llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize, SizeThreshold,
436 GrowthDelay> &Allocator) {
437 return Allocator.Allocate(Size, std::min((size_t)llvm::NextPowerOf2(Size),
2
Calling 'BumpPtrAllocatorImpl::Allocate'
438 alignof(std::max_align_t)));
439}
440
441template <typename AllocatorT, size_t SlabSize, size_t SizeThreshold,
442 size_t GrowthDelay>
443void operator delete(void *,
444 llvm::BumpPtrAllocatorImpl<AllocatorT, SlabSize,
445 SizeThreshold, GrowthDelay> &) {
446}
447
448#endif // LLVM_SUPPORT_ALLOCATOR_H

/usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/llvm/include/llvm/Support/Alignment.h

1//===-- llvm/Support/Alignment.h - Useful alignment functions ---*- 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// This file contains types to represent alignments.
10// They are instrumented to guarantee some invariants are preserved and prevent
11// invalid manipulations.
12//
13// - Align represents an alignment in bytes, it is always set and always a valid
14// power of two, its minimum value is 1 which means no alignment requirements.
15//
16// - MaybeAlign is an optional type, it may be undefined or set. When it's set
17// you can get the underlying Align type by using the getValue() method.
18//
19//===----------------------------------------------------------------------===//
20
21#ifndef LLVM_SUPPORT_ALIGNMENT_H_
22#define LLVM_SUPPORT_ALIGNMENT_H_
23
24#include "llvm/ADT/Optional.h"
25#include "llvm/Support/MathExtras.h"
26#include <cassert>
27#ifndef NDEBUG1
28#include <string>
29#endif // NDEBUG
30
31namespace llvm {
32
33#define ALIGN_CHECK_ISPOSITIVE(decl) \
34 assert(decl > 0 && (#decl " should be defined"))((void)0)
35
36/// This struct is a compact representation of a valid (non-zero power of two)
37/// alignment.
38/// It is suitable for use as static global constants.
39struct Align {
40private:
41 uint8_t ShiftValue = 0; /// The log2 of the required alignment.
42 /// ShiftValue is less than 64 by construction.
43
44 friend struct MaybeAlign;
45 friend unsigned Log2(Align);
46 friend bool operator==(Align Lhs, Align Rhs);
47 friend bool operator!=(Align Lhs, Align Rhs);
48 friend bool operator<=(Align Lhs, Align Rhs);
49 friend bool operator>=(Align Lhs, Align Rhs);
50 friend bool operator<(Align Lhs, Align Rhs);
51 friend bool operator>(Align Lhs, Align Rhs);
52 friend unsigned encode(struct MaybeAlign A);
53 friend struct MaybeAlign decodeMaybeAlign(unsigned Value);
54
55 /// A trivial type to allow construction of constexpr Align.
56 /// This is currently needed to workaround a bug in GCC 5.3 which prevents
57 /// definition of constexpr assign operators.
58 /// https://stackoverflow.com/questions/46756288/explicitly-defaulted-function-cannot-be-declared-as-constexpr-because-the-implic
59 /// FIXME: Remove this, make all assign operators constexpr and introduce user
60 /// defined literals when we don't have to support GCC 5.3 anymore.
61 /// https://llvm.org/docs/GettingStarted.html#getting-a-modern-host-c-toolchain
62 struct LogValue {
63 uint8_t Log;
64 };
65
66public:
67 /// Default is byte-aligned.
68 constexpr Align() = default;
69 /// Do not perform checks in case of copy/move construct/assign, because the
70 /// checks have been performed when building `Other`.
71 constexpr Align(const Align &Other) = default;
72 constexpr Align(Align &&Other) = default;
73 Align &operator=(const Align &Other) = default;
74 Align &operator=(Align &&Other) = default;
75
76 explicit Align(uint64_t Value) {
77 assert(Value > 0 && "Value must not be 0")((void)0);
78 assert(llvm::isPowerOf2_64(Value) && "Alignment is not a power of 2")((void)0);
79 ShiftValue = Log2_64(Value);
80 assert(ShiftValue < 64 && "Broken invariant")((void)0);
81 }
82
83 /// This is a hole in the type system and should not be abused.
84 /// Needed to interact with C for instance.
85 uint64_t value() const { return uint64_t(1) << ShiftValue; }
9
The result of the left shift is undefined due to shifting by '255', which is greater or equal to the width of type 'uint64_t'
86
87 /// Allow constructions of constexpr Align.
88 template <size_t kValue> constexpr static LogValue Constant() {
89 return LogValue{static_cast<uint8_t>(CTLog2<kValue>())};
90 }
91
92 /// Allow constructions of constexpr Align from types.
93 /// Compile time equivalent to Align(alignof(T)).
94 template <typename T> constexpr static LogValue Of() {
95 return Constant<std::alignment_of<T>::value>();
96 }
97
98 /// Constexpr constructor from LogValue type.
99 constexpr Align(LogValue CA) : ShiftValue(CA.Log) {}
100};
101
102/// Treats the value 0 as a 1, so Align is always at least 1.
103inline Align assumeAligned(uint64_t Value) {
104 return Value ? Align(Value) : Align();
105}
106
107/// This struct is a compact representation of a valid (power of two) or
108/// undefined (0) alignment.
109struct MaybeAlign : public llvm::Optional<Align> {
110private:
111 using UP = llvm::Optional<Align>;
112
113public:
114 /// Default is undefined.
115 MaybeAlign() = default;
116 /// Do not perform checks in case of copy/move construct/assign, because the
117 /// checks have been performed when building `Other`.
118 MaybeAlign(const MaybeAlign &Other) = default;
119 MaybeAlign &operator=(const MaybeAlign &Other) = default;
120 MaybeAlign(MaybeAlign &&Other) = default;
121 MaybeAlign &operator=(MaybeAlign &&Other) = default;
122
123 /// Use llvm::Optional<Align> constructor.
124 using UP::UP;
125
126 explicit MaybeAlign(uint64_t Value) {
127 assert((Value == 0 || llvm::isPowerOf2_64(Value)) &&((void)0)
128 "Alignment is neither 0 nor a power of 2")((void)0);
129 if (Value)
130 emplace(Value);
131 }
132
133 /// For convenience, returns a valid alignment or 1 if undefined.
134 Align valueOrOne() const { return hasValue() ? getValue() : Align(); }
135};
136
137/// Checks that SizeInBytes is a multiple of the alignment.
138inline bool isAligned(Align Lhs, uint64_t SizeInBytes) {
139 return SizeInBytes % Lhs.value() == 0;
140}
141
142/// Checks that Addr is a multiple of the alignment.
143inline bool isAddrAligned(Align Lhs, const void *Addr) {
144 return isAligned(Lhs, reinterpret_cast<uintptr_t>(Addr));
145}
146
147/// Returns a multiple of A needed to store `Size` bytes.
148inline uint64_t alignTo(uint64_t Size, Align A) {
149 const uint64_t Value = A.value();
8
Calling 'Align::value'
150 // The following line is equivalent to `(Size + Value - 1) / Value * Value`.
151
152 // The division followed by a multiplication can be thought of as a right
153 // shift followed by a left shift which zeros out the extra bits produced in
154 // the bump; `~(Value - 1)` is a mask where all those bits being zeroed out
155 // are just zero.
156
157 // Most compilers can generate this code but the pattern may be missed when
158 // multiple functions gets inlined.
159 return (Size + Value - 1) & ~(Value - 1U);
160}
161
162/// If non-zero \p Skew is specified, the return value will be a minimal integer
163/// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for
164/// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p
165/// Skew mod \p A'.
166///
167/// Examples:
168/// \code
169/// alignTo(5, Align(8), 7) = 7
170/// alignTo(17, Align(8), 1) = 17
171/// alignTo(~0LL, Align(8), 3) = 3
172/// \endcode
173inline uint64_t alignTo(uint64_t Size, Align A, uint64_t Skew) {
174 const uint64_t Value = A.value();
175 Skew %= Value;
176 return ((Size + Value - 1 - Skew) & ~(Value - 1U)) + Skew;
177}
178
179/// Returns a multiple of A needed to store `Size` bytes.
180/// Returns `Size` if current alignment is undefined.
181inline uint64_t alignTo(uint64_t Size, MaybeAlign A) {
182 return A ? alignTo(Size, A.getValue()) : Size;
183}
184
185/// Aligns `Addr` to `Alignment` bytes, rounding up.
186inline uintptr_t alignAddr(const void *Addr, Align Alignment) {
187 uintptr_t ArithAddr = reinterpret_cast<uintptr_t>(Addr);
188 assert(static_cast<uintptr_t>(ArithAddr + Alignment.value() - 1) >=((void)0)
189 ArithAddr &&((void)0)
190 "Overflow")((void)0);
191 return alignTo(ArithAddr, Alignment);
192}
193
194/// Returns the offset to the next integer (mod 2**64) that is greater than
195/// or equal to \p Value and is a multiple of \p Align.
196inline uint64_t offsetToAlignment(uint64_t Value, Align Alignment) {
197 return alignTo(Value, Alignment) - Value;
6
The value 255 is assigned to 'A.ShiftValue'
7
Calling 'alignTo'
198}
199
200/// Returns the necessary adjustment for aligning `Addr` to `Alignment`
201/// bytes, rounding up.
202inline uint64_t offsetToAlignedAddr(const void *Addr, Align Alignment) {
203 return offsetToAlignment(reinterpret_cast<uintptr_t>(Addr), Alignment);
5
Calling 'offsetToAlignment'
204}
205
206/// Returns the log2 of the alignment.
207inline unsigned Log2(Align A) { return A.ShiftValue; }
208
209/// Returns the alignment that satisfies both alignments.
210/// Same semantic as MinAlign.
211inline Align commonAlignment(Align A, Align B) { return std::min(A, B); }
212
213/// Returns the alignment that satisfies both alignments.
214/// Same semantic as MinAlign.
215inline Align commonAlignment(Align A, uint64_t Offset) {
216 return Align(MinAlign(A.value(), Offset));
217}
218
219/// Returns the alignment that satisfies both alignments.
220/// Same semantic as MinAlign.
221inline MaybeAlign commonAlignment(MaybeAlign A, MaybeAlign B) {
222 return A && B ? commonAlignment(*A, *B) : A ? A : B;
223}
224
225/// Returns the alignment that satisfies both alignments.
226/// Same semantic as MinAlign.
227inline MaybeAlign commonAlignment(MaybeAlign A, uint64_t Offset) {
228 return MaybeAlign(MinAlign((*A).value(), Offset));
229}
230
231/// Returns a representation of the alignment that encodes undefined as 0.
232inline unsigned encode(MaybeAlign A) { return A ? A->ShiftValue + 1 : 0; }
233
234/// Dual operation of the encode function above.
235inline MaybeAlign decodeMaybeAlign(unsigned Value) {
236 if (Value == 0)
237 return MaybeAlign();
238 Align Out;
239 Out.ShiftValue = Value - 1;
240 return Out;
241}
242
243/// Returns a representation of the alignment, the encoded value is positive by
244/// definition.
245inline unsigned encode(Align A) { return encode(MaybeAlign(A)); }
246
247/// Comparisons between Align and scalars. Rhs must be positive.
248inline bool operator==(Align Lhs, uint64_t Rhs) {
249 ALIGN_CHECK_ISPOSITIVE(Rhs);
250 return Lhs.value() == Rhs;
251}
252inline bool operator!=(Align Lhs, uint64_t Rhs) {
253 ALIGN_CHECK_ISPOSITIVE(Rhs);
254 return Lhs.value() != Rhs;
255}
256inline bool operator<=(Align Lhs, uint64_t Rhs) {
257 ALIGN_CHECK_ISPOSITIVE(Rhs);
258 return Lhs.value() <= Rhs;
259}
260inline bool operator>=(Align Lhs, uint64_t Rhs) {
261 ALIGN_CHECK_ISPOSITIVE(Rhs);
262 return Lhs.value() >= Rhs;
263}
264inline bool operator<(Align Lhs, uint64_t Rhs) {
265 ALIGN_CHECK_ISPOSITIVE(Rhs);
266 return Lhs.value() < Rhs;
267}
268inline bool operator>(Align Lhs, uint64_t Rhs) {
269 ALIGN_CHECK_ISPOSITIVE(Rhs);
270 return Lhs.value() > Rhs;
271}
272
273/// Comparisons between MaybeAlign and scalars.
274inline bool operator==(MaybeAlign Lhs, uint64_t Rhs) {
275 return Lhs ? (*Lhs).value() == Rhs : Rhs == 0;
276}
277inline bool operator!=(MaybeAlign Lhs, uint64_t Rhs) {
278 return Lhs ? (*Lhs).value() != Rhs : Rhs != 0;
279}
280
281/// Comparisons operators between Align.
282inline bool operator==(Align Lhs, Align Rhs) {
283 return Lhs.ShiftValue == Rhs.ShiftValue;
284}
285inline bool operator!=(Align Lhs, Align Rhs) {
286 return Lhs.ShiftValue != Rhs.ShiftValue;
287}
288inline bool operator<=(Align Lhs, Align Rhs) {
289 return Lhs.ShiftValue <= Rhs.ShiftValue;
290}
291inline bool operator>=(Align Lhs, Align Rhs) {
292 return Lhs.ShiftValue >= Rhs.ShiftValue;
293}
294inline bool operator<(Align Lhs, Align Rhs) {
295 return Lhs.ShiftValue < Rhs.ShiftValue;
296}
297inline bool operator>(Align Lhs, Align Rhs) {
298 return Lhs.ShiftValue > Rhs.ShiftValue;
299}
300
301// Don't allow relational comparisons with MaybeAlign.
302bool operator<=(Align Lhs, MaybeAlign Rhs) = delete;
303bool operator>=(Align Lhs, MaybeAlign Rhs) = delete;
304bool operator<(Align Lhs, MaybeAlign Rhs) = delete;
305bool operator>(Align Lhs, MaybeAlign Rhs) = delete;
306
307bool operator<=(MaybeAlign Lhs, Align Rhs) = delete;
308bool operator>=(MaybeAlign Lhs, Align Rhs) = delete;
309bool operator<(MaybeAlign Lhs, Align Rhs) = delete;
310bool operator>(MaybeAlign Lhs, Align Rhs) = delete;
311
312bool operator<=(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
313bool operator>=(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
314bool operator<(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
315bool operator>(MaybeAlign Lhs, MaybeAlign Rhs) = delete;
316
317inline Align operator*(Align Lhs, uint64_t Rhs) {
318 assert(Rhs > 0 && "Rhs must be positive")((void)0);
319 return Align(Lhs.value() * Rhs);
320}
321
322inline MaybeAlign operator*(MaybeAlign Lhs, uint64_t Rhs) {
323 assert(Rhs > 0 && "Rhs must be positive")((void)0);
324 return Lhs ? Lhs.getValue() * Rhs : MaybeAlign();
325}
326
327inline Align operator/(Align Lhs, uint64_t Divisor) {
328 assert(llvm::isPowerOf2_64(Divisor) &&((void)0)
329 "Divisor must be positive and a power of 2")((void)0);
330 assert(Lhs != 1 && "Can't halve byte alignment")((void)0);
331 return Align(Lhs.value() / Divisor);
332}
333
334inline MaybeAlign operator/(MaybeAlign Lhs, uint64_t Divisor) {
335 assert(llvm::isPowerOf2_64(Divisor) &&((void)0)
336 "Divisor must be positive and a power of 2")((void)0);
337 return Lhs ? Lhs.getValue() / Divisor : MaybeAlign();
338}
339
340inline Align max(MaybeAlign Lhs, Align Rhs) {
341 return Lhs && *Lhs > Rhs ? *Lhs : Rhs;
342}
343
344inline Align max(Align Lhs, MaybeAlign Rhs) {
345 return Rhs && *Rhs > Lhs ? *Rhs : Lhs;
346}
347
348#ifndef NDEBUG1
349// For usage in LLVM_DEBUG macros.
350inline std::string DebugStr(const Align &A) {
351 return std::to_string(A.value());
352}
353// For usage in LLVM_DEBUG macros.
354inline std::string DebugStr(const MaybeAlign &MA) {
355 if (MA)
356 return std::to_string(MA->value());
357 return "None";
358}
359#endif // NDEBUG
360
361#undef ALIGN_CHECK_ISPOSITIVE
362
363} // namespace llvm
364
365#endif // LLVM_SUPPORT_ALIGNMENT_H_