LLVM 23.0.0git
MCWin64EH.cpp
Go to the documentation of this file.
1//===- lib/MC/MCWin64EH.cpp - MCWin64EH implementation --------------------===//
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 "llvm/MC/MCWin64EH.h"
10#include "llvm/ADT/Twine.h"
11#include "llvm/MC/MCAssembler.h"
12#include "llvm/MC/MCContext.h"
13#include "llvm/MC/MCExpr.h"
15#include "llvm/MC/MCStreamer.h"
16#include "llvm/MC/MCSymbol.h"
17#include "llvm/MC/MCValue.h"
19
20namespace llvm {
21class MCSection;
22}
23
24using namespace llvm;
25
26namespace {
27/// MCExpr that represents the epilog unwind code in an unwind table.
28class MCUnwindV2EpilogTargetExpr final : public MCTargetExpr {
29 const WinEH::FrameInfo &FrameInfo;
30 const MCSymbol *UnwindV2Start;
31 const MCSymbol *EpilogEnd;
32 uint8_t EpilogSize;
33 SMLoc Loc;
34
35 MCUnwindV2EpilogTargetExpr(const WinEH::FrameInfo &FrameInfo,
36 const WinEH::FrameInfo::Epilog &Epilog,
37 uint8_t EpilogSize_)
38 : FrameInfo(FrameInfo), UnwindV2Start(Epilog.UnwindV2Start),
39 EpilogEnd(Epilog.End), EpilogSize(EpilogSize_), Loc(Epilog.Loc) {
40 assert(UnwindV2Start && "Epilog must have a start");
41 assert(EpilogEnd && "Epilog must have an end");
42 }
43
44public:
45 static MCUnwindV2EpilogTargetExpr *
46 create(const WinEH::FrameInfo &FrameInfo,
47 const WinEH::FrameInfo::Epilog &Epilog, uint8_t EpilogSize_,
48 MCContext &Ctx) {
49 return new (Ctx) MCUnwindV2EpilogTargetExpr(FrameInfo, Epilog, EpilogSize_);
50 }
51
52 void printImpl(raw_ostream &OS, const MCAsmInfo *MAI) const override {
53 OS << ":epilog:";
54 UnwindV2Start->print(OS, MAI);
55 }
56
57 bool evaluateAsRelocatableImpl(MCValue &Res,
58 const MCAssembler *Asm) const override;
59
60 void visitUsedExpr(MCStreamer &Streamer) const override {
61 // Contains no sub-expressions.
62 }
63
64 MCFragment *findAssociatedFragment() const override {
65 return UnwindV2Start->getFragment();
66 }
67};
68} // namespace
69
70// NOTE: All relocations generated here are 4-byte image-relative.
71
72static uint8_t CountOfUnwindCodes(std::vector<WinEH::Instruction> &Insns) {
73 uint8_t Count = 0;
74 for (const auto &I : Insns) {
75 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
76 default:
77 llvm_unreachable("Unsupported unwind code");
82 Count += 1;
83 break;
86 Count += 2;
87 break;
90 Count += 3;
91 break;
93 Count += (I.Offset > 512 * 1024 - 8) ? 3 : 2;
94 break;
95 }
96 }
97 return Count;
98}
99
100static void EmitAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS,
101 const MCSymbol *RHS) {
102 MCContext &Context = Streamer.getContext();
103 const MCExpr *Diff =
105 MCSymbolRefExpr::create(RHS, Context), Context);
106 Streamer.emitValue(Diff, 1);
107}
108
109static void EmitUnwindCode(MCStreamer &streamer, const MCSymbol *begin,
110 WinEH::Instruction &inst) {
111 uint8_t b2;
112 uint16_t w;
113 b2 = (inst.Operation & 0x0F);
114 switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
115 default:
116 llvm_unreachable("Unsupported unwind code");
118 EmitAbsDifference(streamer, inst.Label, begin);
119 b2 |= (inst.Register & 0x0F) << 4;
120 streamer.emitInt8(b2);
121 break;
123 EmitAbsDifference(streamer, inst.Label, begin);
124 if (inst.Offset > 512 * 1024 - 8) {
125 b2 |= 0x10;
126 streamer.emitInt8(b2);
127 w = inst.Offset & 0xFFF8;
128 streamer.emitInt16(w);
129 w = inst.Offset >> 16;
130 } else {
131 streamer.emitInt8(b2);
132 w = inst.Offset >> 3;
133 }
134 streamer.emitInt16(w);
135 break;
137 b2 |= (((inst.Offset - 8) >> 3) & 0x0F) << 4;
138 EmitAbsDifference(streamer, inst.Label, begin);
139 streamer.emitInt8(b2);
140 break;
142 EmitAbsDifference(streamer, inst.Label, begin);
143 streamer.emitInt8(b2);
144 break;
147 b2 |= (inst.Register & 0x0F) << 4;
148 EmitAbsDifference(streamer, inst.Label, begin);
149 streamer.emitInt8(b2);
150 w = inst.Offset >> 3;
152 w >>= 1;
153 streamer.emitInt16(w);
154 break;
157 b2 |= (inst.Register & 0x0F) << 4;
158 EmitAbsDifference(streamer, inst.Label, begin);
159 streamer.emitInt8(b2);
161 w = inst.Offset & 0xFFF0;
162 else
163 w = inst.Offset & 0xFFF8;
164 streamer.emitInt16(w);
165 w = inst.Offset >> 16;
166 streamer.emitInt16(w);
167 break;
169 if (inst.Offset == 1)
170 b2 |= 0x10;
171 EmitAbsDifference(streamer, inst.Label, begin);
172 streamer.emitInt8(b2);
173 break;
174 }
175}
176
177static void EmitSymbolRefWithOfs(MCStreamer &streamer,
178 const MCSymbol *Base,
179 int64_t Offset) {
180 MCContext &Context = streamer.getContext();
181 const MCConstantExpr *OffExpr = MCConstantExpr::create(Offset, Context);
182 const MCSymbolRefExpr *BaseRefRel = MCSymbolRefExpr::create(Base,
184 Context);
185 streamer.emitValue(MCBinaryExpr::createAdd(BaseRefRel, OffExpr, Context), 4);
186}
187
188static void EmitSymbolRefWithOfs(MCStreamer &streamer,
189 const MCSymbol *Base,
190 const MCSymbol *Other) {
191 MCContext &Context = streamer.getContext();
192 const MCSymbolRefExpr *BaseRef = MCSymbolRefExpr::create(Base, Context);
193 const MCSymbolRefExpr *OtherRef = MCSymbolRefExpr::create(Other, Context);
194 const MCExpr *Ofs = MCBinaryExpr::createSub(OtherRef, BaseRef, Context);
195 const MCSymbolRefExpr *BaseRefRel = MCSymbolRefExpr::create(Base,
197 Context);
198 streamer.emitValue(MCBinaryExpr::createAdd(BaseRefRel, Ofs, Context), 4);
199}
200
201static void EmitRuntimeFunction(MCStreamer &streamer,
202 const WinEH::FrameInfo *info) {
203 MCContext &context = streamer.getContext();
204
205 streamer.emitValueToAlignment(Align(4));
206 EmitSymbolRefWithOfs(streamer, info->Begin, info->Begin);
207 EmitSymbolRefWithOfs(streamer, info->Begin, info->End);
208 streamer.emitValue(MCSymbolRefExpr::create(info->Symbol,
210 context), 4);
211}
212
213static std::optional<int64_t>
215 const MCSymbol *RHS) {
216 MCContext &Context = Assembler.getContext();
217 const MCExpr *Diff =
219 MCSymbolRefExpr::create(RHS, Context), Context);
220 // It should normally be possible to calculate the length of a function
221 // at this point, but it might not be possible in the presence of certain
222 // unusual constructs, like an inline asm with an alignment directive.
223 int64_t value;
224 if (!Diff->evaluateAsAbsolute(value, Assembler))
225 return std::nullopt;
226 return value;
227}
228
230 // If this UNWIND_INFO already has a symbol, it's already been emitted.
231 if (info->Symbol)
232 return;
233
234 MCContext &context = streamer.getContext();
235 MCObjectStreamer *OS = (MCObjectStreamer *)(&streamer);
236 MCSymbol *Label = context.createTempSymbol();
237
238 streamer.emitValueToAlignment(Align(4));
239 streamer.emitLabel(Label);
240 info->Symbol = Label;
241
242 uint8_t numCodes = CountOfUnwindCodes(info->Instructions);
243 bool LastEpilogIsAtEnd = false;
244 bool AddPaddingEpilogCode = false;
245 uint8_t EpilogSize = 0;
246 bool EnableUnwindV2 = (info->Version >= 2) && !info->EpilogMap.empty();
247 if (EnableUnwindV2) {
248 auto &LastEpilog = info->EpilogMap.back().second;
249
250 // Calculate the size of the epilogs. Note that we +1 to the size so that
251 // the terminator instruction is also included in the epilog (the Windows
252 // unwinder does a simple range check versus the current instruction pointer
253 // so, although there are terminators that are large than 1 byte, the
254 // starting address of the terminator instruction will always be considered
255 // inside the epilog).
256 assert(
257 LastEpilog.UnwindV2Start &&
258 "If unwind v2 is enabled, epilog must have a unwind v2 start marker");
259 assert(LastEpilog.End && "Epilog must have an end");
260 auto MaybeSize = GetOptionalAbsDifference(
261 OS->getAssembler(), LastEpilog.End, LastEpilog.UnwindV2Start);
262 if (!MaybeSize) {
263 context.reportError(LastEpilog.Loc,
264 "Failed to evaluate epilog size for Unwind v2 in " +
265 info->Function->getName());
266 return;
267 }
268 assert(*MaybeSize >= 0);
269 if (*MaybeSize >= (int64_t)UINT8_MAX) {
270 context.reportError(LastEpilog.Loc,
271 "Epilog size is too large for Unwind v2 in " +
272 info->Function->getName());
273 return;
274 }
275 EpilogSize = *MaybeSize + 1;
276
277 // If the last epilog is at the end of the function, we can use a special
278 // encoding for it. Because of our +1 trick for the size, this will only
279 // work where that final terminator instruction is 1 byte long.
280 // NOTE: At the point where the unwind info is emitted, the function may not
281 // have ended yet (e.g., if there is EH Handler Data), so assume that we
282 // aren't at the end (since we can't calculate it).
283 if (info->End) {
284 auto LastEpilogToFuncEnd = GetOptionalAbsDifference(
285 OS->getAssembler(), info->End, LastEpilog.UnwindV2Start);
286 LastEpilogIsAtEnd = (LastEpilogToFuncEnd == EpilogSize);
287 }
288
289 // If we have an odd number of epilog codes, we need to add a padding code.
290 size_t numEpilogCodes =
291 info->EpilogMap.size() + (LastEpilogIsAtEnd ? 0 : 1);
292 if ((numEpilogCodes % 2) != 0) {
293 AddPaddingEpilogCode = true;
294 numEpilogCodes++;
295 }
296
297 // Too many epilogs to handle.
298 if ((size_t)numCodes + numEpilogCodes > UINT8_MAX) {
299 context.reportError(info->FunctionLoc,
300 "Too many unwind codes with Unwind v2 enabled in " +
301 info->Function->getName());
302 return;
303 }
304
305 numCodes += numEpilogCodes;
306 }
307
308 // Upper 3 bits are the version number.
309 uint8_t flags = info->Version;
310 if (info->ChainedParent)
311 flags |= Win64EH::UNW_ChainInfo << 3;
312 else {
313 if (info->HandlesUnwind)
314 flags |= Win64EH::UNW_TerminateHandler << 3;
315 if (info->HandlesExceptions)
316 flags |= Win64EH::UNW_ExceptionHandler << 3;
317 }
318 streamer.emitInt8(flags);
319
320 if (info->PrologEnd)
321 EmitAbsDifference(streamer, info->PrologEnd, info->Begin);
322 else
323 streamer.emitInt8(0);
324
325 streamer.emitInt8(numCodes);
326
327 uint8_t frame = 0;
328 if (info->LastFrameInst >= 0) {
329 WinEH::Instruction &frameInst = info->Instructions[info->LastFrameInst];
331 frame = (frameInst.Register & 0x0F) | (frameInst.Offset & 0xF0);
332 }
333 streamer.emitInt8(frame);
334
335 // Emit the epilog instructions.
336 if (EnableUnwindV2) {
337 // Ensure the fixups and appended content apply to the same fragment.
338 // size byte + flags byte + 2 per epilog (for the distance).
339 OS->ensureHeadroom(2 + info->EpilogMap.size() * 2);
340
341 bool IsLast = true;
342 for (const auto &Epilog : llvm::reverse(info->EpilogMap)) {
343 if (IsLast) {
344 IsLast = false;
345 uint8_t Flags = LastEpilogIsAtEnd ? 0x01 : 0;
346 OS->emitInt8(EpilogSize);
347 OS->emitInt8((Flags << 4) | Win64EH::UOP_Epilog);
348
349 if (LastEpilogIsAtEnd)
350 continue;
351 }
352
353 // Each epilog is emitted as a fixup, since we can't measure the distance
354 // between the start of the epilog and the end of the function until
355 // layout has been completed.
356 auto *MCE = MCUnwindV2EpilogTargetExpr::create(*info, Epilog.second,
357 EpilogSize, context);
358 OS->addFixup(MCE, FK_Data_2);
359 OS->appendContents(2, 0);
360 }
361 }
362 if (AddPaddingEpilogCode)
363 streamer.emitInt16(Win64EH::UOP_Epilog << 8);
364
365 // Emit unwind instructions (in reverse order).
366 uint8_t numInst = info->Instructions.size();
367 for (uint8_t c = 0; c < numInst; ++c) {
368 WinEH::Instruction inst = info->Instructions.back();
369 info->Instructions.pop_back();
370 EmitUnwindCode(streamer, info->Begin, inst);
371 }
372
373 // For alignment purposes, the instruction array will always have an even
374 // number of entries, with the final entry potentially unused (in which case
375 // the array will be one longer than indicated by the count of unwind codes
376 // field).
377 if (numCodes & 1) {
378 streamer.emitInt16(0);
379 }
380
381 if (flags & (Win64EH::UNW_ChainInfo << 3))
382 EmitRuntimeFunction(streamer, info->ChainedParent);
383 else if (flags &
385 streamer.emitValue(MCSymbolRefExpr::create(info->ExceptionHandler,
387 context), 4);
388 else if (numCodes == 0) {
389 // The minimum size of an UNWIND_INFO struct is 8 bytes. If we're not
390 // a chained unwind info, if there is no handler, and if there are fewer
391 // than 2 slots used in the unwind code array, we have to pad to 8 bytes.
392 streamer.emitInt32(0);
393 }
394}
395
396bool MCUnwindV2EpilogTargetExpr::evaluateAsRelocatableImpl(
397 MCValue &Res, const MCAssembler *Asm) const {
398 // Calculate the offset to this epilog, and validate it's within the allowed
399 // range.
400 auto Offset = GetOptionalAbsDifference(*Asm, FrameInfo.End, UnwindV2Start);
401 if (!Offset) {
402 Asm->getContext().reportError(
403 Loc, "Failed to evaluate epilog offset for Unwind v2 in " +
404 FrameInfo.Function->getName());
405 return false;
406 }
407 assert(*Offset > 0);
408 constexpr uint16_t MaxEpilogOffset = 0x0fff;
409 if (*Offset > MaxEpilogOffset) {
410 Asm->getContext().reportError(
411 Loc, "Epilog offset is too large for Unwind v2 in " +
412 FrameInfo.Function->getName());
413 return false;
414 }
415
416 // Validate that all epilogs are the same size.
417 auto Size = GetOptionalAbsDifference(*Asm, EpilogEnd, UnwindV2Start);
418 if (Size != (EpilogSize - 1)) {
419 Asm->getContext().reportError(
420 Loc, "Size of this epilog does not match size of last epilog in " +
421 FrameInfo.Function->getName());
422 return false;
423 }
424
425 auto HighBits = *Offset >> 8;
426 Res = MCValue::get((HighBits << 12) | (Win64EH::UOP_Epilog << 8) |
427 (*Offset & 0xFF));
428 return true;
429}
430
432 // Emit the unwind info structs first.
433 for (const auto &CFI : Streamer.getWinFrameInfos()) {
434 MCSection *XData = Streamer.getAssociatedXDataSection(CFI->TextSection);
435 Streamer.switchSection(XData);
436 ::EmitUnwindInfo(Streamer, CFI.get());
437 }
438
439 // Now emit RUNTIME_FUNCTION entries.
440 for (const auto &CFI : Streamer.getWinFrameInfos()) {
441 MCSection *PData = Streamer.getAssociatedPDataSection(CFI->TextSection);
442 Streamer.switchSection(PData);
443 EmitRuntimeFunction(Streamer, CFI.get());
444 }
445}
446
449 bool HandlerData) const {
450 // Switch sections (the static function above is meant to be called from
451 // here and from Emit().
452 MCSection *XData = Streamer.getAssociatedXDataSection(info->TextSection);
453 Streamer.switchSection(XData);
454
455 ::EmitUnwindInfo(Streamer, info);
456}
457
458static const MCExpr *GetSubDivExpr(MCStreamer &Streamer, const MCSymbol *LHS,
459 const MCSymbol *RHS, int Div) {
460 MCContext &Context = Streamer.getContext();
461 const MCExpr *Expr =
463 MCSymbolRefExpr::create(RHS, Context), Context);
464 if (Div != 1)
465 Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(Div, Context),
466 Context);
467 return Expr;
468}
469
470static std::optional<int64_t> GetOptionalAbsDifference(MCStreamer &Streamer,
471 const MCSymbol *LHS,
472 const MCSymbol *RHS) {
473 MCObjectStreamer *OS = (MCObjectStreamer *)(&Streamer);
475}
476
477static int64_t GetAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS,
478 const MCSymbol *RHS) {
479 std::optional<int64_t> MaybeDiff =
480 GetOptionalAbsDifference(Streamer, LHS, RHS);
481 if (!MaybeDiff)
482 report_fatal_error("Failed to evaluate function length in SEH unwind info");
483 return *MaybeDiff;
484}
485
486static void checkARM64Instructions(MCStreamer &Streamer,
488 const MCSymbol *Begin, const MCSymbol *End,
489 StringRef Name, StringRef Type) {
490 if (!End)
491 return;
492 std::optional<int64_t> MaybeDistance =
493 GetOptionalAbsDifference(Streamer, End, Begin);
494 if (!MaybeDistance)
495 return;
496 uint32_t Distance = (uint32_t)*MaybeDistance;
497
498 for (const auto &I : Insns) {
499 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
500 default:
501 break;
507 // Can't reason about these opcodes and how they map to actual
508 // instructions.
509 return;
510 }
511 }
512 // Exclude the end opcode which doesn't map to an instruction.
513 uint32_t InstructionBytes = 4 * (Insns.size() - 1);
514 if (Distance != InstructionBytes) {
515 Streamer.getContext().reportError(
516 SMLoc(), "Incorrect size for " + Name + " " + Type + ": " +
517 Twine(Distance) +
518 " bytes of instructions in range, but .seh directives "
519 "corresponding to " +
520 Twine(InstructionBytes) + " bytes\n");
521 }
522}
523
525 uint32_t Count = 0;
526 for (const auto &I : Insns) {
527 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
528 default:
529 llvm_unreachable("Unsupported ARM64 unwind code");
531 Count += 1;
532 break;
534 Count += 2;
535 break;
537 Count += 4;
538 break;
540 Count += 1;
541 break;
543 Count += 1;
544 break;
546 Count += 1;
547 break;
549 Count += 2;
550 break;
552 Count += 2;
553 break;
555 Count += 2;
556 break;
558 Count += 2;
559 break;
561 Count += 2;
562 break;
564 Count += 2;
565 break;
567 Count += 2;
568 break;
570 Count += 2;
571 break;
573 Count += 2;
574 break;
576 Count += 1;
577 break;
579 Count += 2;
580 break;
581 case Win64EH::UOP_Nop:
582 Count += 1;
583 break;
584 case Win64EH::UOP_End:
585 Count += 1;
586 break;
588 Count += 1;
589 break;
591 Count += 1;
592 break;
594 Count += 1;
595 break;
597 Count += 1;
598 break;
600 Count += 1;
601 break;
603 Count += 1;
604 break;
606 Count += 1;
607 break;
609 Count += 2;
610 break;
625 Count += 3;
626 break;
627 }
628 }
629 return Count;
630}
631
632// Unwind opcode encodings and restrictions are documented at
633// https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
634static void ARM64EmitUnwindCode(MCStreamer &streamer,
635 const WinEH::Instruction &inst) {
636 uint8_t b, reg;
637 switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
638 default:
639 llvm_unreachable("Unsupported ARM64 unwind code");
641 b = (inst.Offset >> 4) & 0x1F;
642 streamer.emitInt8(b);
643 break;
645 uint16_t hw = (inst.Offset >> 4) & 0x7FF;
646 b = 0xC0;
647 b |= (hw >> 8);
648 streamer.emitInt8(b);
649 b = hw & 0xFF;
650 streamer.emitInt8(b);
651 break;
652 }
654 uint32_t w;
655 b = 0xE0;
656 streamer.emitInt8(b);
657 w = inst.Offset >> 4;
658 b = (w & 0x00FF0000) >> 16;
659 streamer.emitInt8(b);
660 b = (w & 0x0000FF00) >> 8;
661 streamer.emitInt8(b);
662 b = w & 0x000000FF;
663 streamer.emitInt8(b);
664 break;
665 }
667 b = 0xE1;
668 streamer.emitInt8(b);
669 break;
671 b = 0xE2;
672 streamer.emitInt8(b);
673 b = (inst.Offset >> 3);
674 streamer.emitInt8(b);
675 break;
676 case Win64EH::UOP_Nop:
677 b = 0xE3;
678 streamer.emitInt8(b);
679 break;
681 b = 0x20;
682 b |= (inst.Offset >> 3) & 0x1F;
683 streamer.emitInt8(b);
684 break;
686 b = 0x80;
687 b |= ((inst.Offset >> 3) - 1) & 0x3F;
688 streamer.emitInt8(b);
689 break;
691 b = 0x40;
692 b |= (inst.Offset >> 3) & 0x3F;
693 streamer.emitInt8(b);
694 break;
696 assert(inst.Register >= 19 && "Saved reg must be >= 19");
697 reg = inst.Register - 19;
698 b = 0xD0 | ((reg & 0xC) >> 2);
699 streamer.emitInt8(b);
700 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
701 streamer.emitInt8(b);
702 break;
704 assert(inst.Register >= 19 && "Saved reg must be >= 19");
705 reg = inst.Register - 19;
706 b = 0xD4 | ((reg & 0x8) >> 3);
707 streamer.emitInt8(b);
708 b = ((reg & 0x7) << 5) | ((inst.Offset >> 3) - 1);
709 streamer.emitInt8(b);
710 break;
712 assert(inst.Register >= 19 && "Saved registers must be >= 19");
713 reg = inst.Register - 19;
714 b = 0xC8 | ((reg & 0xC) >> 2);
715 streamer.emitInt8(b);
716 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
717 streamer.emitInt8(b);
718 break;
720 assert(inst.Register >= 19 && "Saved registers must be >= 19");
721 reg = inst.Register - 19;
722 b = 0xCC | ((reg & 0xC) >> 2);
723 streamer.emitInt8(b);
724 b = ((reg & 0x3) << 6) | ((inst.Offset >> 3) - 1);
725 streamer.emitInt8(b);
726 break;
728 assert(inst.Register >= 19 && "Saved reg must be >= 19");
729 reg = inst.Register - 19;
730 assert((reg % 2) == 0 && "Saved reg must be 19+2*X");
731 reg /= 2;
732 b = 0xD6 | ((reg & 0x7) >> 2);
733 streamer.emitInt8(b);
734 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
735 streamer.emitInt8(b);
736 break;
738 assert(inst.Register >= 8 && "Saved dreg must be >= 8");
739 reg = inst.Register - 8;
740 b = 0xDC | ((reg & 0x4) >> 2);
741 streamer.emitInt8(b);
742 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
743 streamer.emitInt8(b);
744 break;
746 assert(inst.Register >= 8 && "Saved dreg must be >= 8");
747 reg = inst.Register - 8;
748 b = 0xDE;
749 streamer.emitInt8(b);
750 b = ((reg & 0x7) << 5) | ((inst.Offset >> 3) - 1);
751 streamer.emitInt8(b);
752 break;
754 assert(inst.Register >= 8 && "Saved dregs must be >= 8");
755 reg = inst.Register - 8;
756 b = 0xD8 | ((reg & 0x4) >> 2);
757 streamer.emitInt8(b);
758 b = ((reg & 0x3) << 6) | (inst.Offset >> 3);
759 streamer.emitInt8(b);
760 break;
762 assert(inst.Register >= 8 && "Saved dregs must be >= 8");
763 reg = inst.Register - 8;
764 b = 0xDA | ((reg & 0x4) >> 2);
765 streamer.emitInt8(b);
766 b = ((reg & 0x3) << 6) | ((inst.Offset >> 3) - 1);
767 streamer.emitInt8(b);
768 break;
769 case Win64EH::UOP_End:
770 b = 0xE4;
771 streamer.emitInt8(b);
772 break;
774 b = 0xE6;
775 streamer.emitInt8(b);
776 break;
778 b = 0xE8;
779 streamer.emitInt8(b);
780 break;
782 b = 0xE9;
783 streamer.emitInt8(b);
784 break;
786 b = 0xEA;
787 streamer.emitInt8(b);
788 break;
790 b = 0xEB;
791 streamer.emitInt8(b);
792 break;
794 b = 0xEC;
795 streamer.emitInt8(b);
796 break;
798 b = 0xFC;
799 streamer.emitInt8(b);
800 break;
813 // This assumes the opcodes are listed in the enum in a particular order.
815 int Writeback = Op / 6;
816 int Paired = Op % 2;
817 int Mode = (Op / 2) % 3;
818 int Offset = inst.Offset >> 3;
819 if (Writeback || Paired || Mode == 2)
820 Offset >>= 1;
821 if (Writeback)
822 --Offset;
823 b = 0xE7;
824 streamer.emitInt8(b);
825 assert(inst.Register < 32);
826 b = inst.Register | (Writeback << 5) | (Paired << 6);
827 streamer.emitInt8(b);
828 b = Offset | (Mode << 6);
829 streamer.emitInt8(b);
830 break;
831 }
832 case Win64EH::UOP_AllocZ: {
833 b = 0xDF;
834 streamer.emitInt8(b);
835 b = inst.Offset;
836 streamer.emitInt8(b);
837 break;
838 }
840 assert(inst.Register >= 8 && inst.Register <= 23);
841 assert(inst.Offset < 256);
842 b = 0xE7;
843 streamer.emitInt8(b);
844 reg = inst.Register - 8;
845 b = ((inst.Offset & 0xC0) >> 1) | reg;
846 streamer.emitInt8(b);
847 b = 0xC0 | (inst.Offset & 0x3F);
848 streamer.emitInt8(b);
849 break;
850 }
852 assert(inst.Register >= 4 && inst.Register <= 15);
853 assert(inst.Offset < 256);
854 b = 0xE7;
855 streamer.emitInt8(b);
856 reg = inst.Register;
857 b = ((inst.Offset & 0xC0) >> 1) | 0x10 | reg;
858 streamer.emitInt8(b);
859 b = 0xC0 | (inst.Offset & 0x3F);
860 streamer.emitInt8(b);
861 break;
862 }
863 }
864}
865
866// Returns the epilog symbol of an epilog with the exact same unwind code
867// sequence, if it exists. Otherwise, returns nullptr.
868// EpilogInstrs - Unwind codes for the current epilog.
869// Epilogs - Epilogs that potentialy match the current epilog.
870static MCSymbol*
871FindMatchingEpilog(const std::vector<WinEH::Instruction>& EpilogInstrs,
872 const std::vector<MCSymbol *>& Epilogs,
873 const WinEH::FrameInfo *info) {
874 for (auto *EpilogStart : Epilogs) {
875 auto InstrsIter = info->EpilogMap.find(EpilogStart);
876 assert(InstrsIter != info->EpilogMap.end() &&
877 "Epilog not found in EpilogMap");
878 const auto &Instrs = InstrsIter->second.Instructions;
879
880 if (Instrs.size() != EpilogInstrs.size())
881 continue;
882
883 bool Match = true;
884 for (unsigned i = 0; i < Instrs.size(); ++i)
885 if (Instrs[i] != EpilogInstrs[i]) {
886 Match = false;
887 break;
888 }
889
890 if (Match)
891 return EpilogStart;
892 }
893 return nullptr;
894}
895
896static void simplifyARM64Opcodes(std::vector<WinEH::Instruction> &Instructions,
897 bool Reverse) {
898 unsigned PrevOffset = -1;
899 unsigned PrevRegister = -1;
900
901 // Iterate over instructions in a forward order (for prologues),
902 // backwards for epilogues (i.e. always reverse compared to how the
903 // opcodes are stored).
904 for (WinEH::Instruction &Inst :
905 llvm::reverse_conditionally(Instructions, Reverse)) {
906 // Convert 2-byte opcodes into equivalent 1-byte ones.
907 if (Inst.Operation == Win64EH::UOP_SaveRegP && Inst.Register == 29) {
908 Inst.Operation = Win64EH::UOP_SaveFPLR;
909 Inst.Register = -1;
910 } else if (Inst.Operation == Win64EH::UOP_SaveRegPX &&
911 Inst.Register == 29) {
912 Inst.Operation = Win64EH::UOP_SaveFPLRX;
913 Inst.Register = -1;
914 } else if (Inst.Operation == Win64EH::UOP_SaveRegPX &&
915 Inst.Register == 19 && Inst.Offset <= 248) {
916 Inst.Operation = Win64EH::UOP_SaveR19R20X;
917 Inst.Register = -1;
918 } else if (Inst.Operation == Win64EH::UOP_AddFP && Inst.Offset == 0) {
919 Inst.Operation = Win64EH::UOP_SetFP;
920 } else if (Inst.Operation == Win64EH::UOP_SaveRegP &&
921 Inst.Register == PrevRegister + 2 &&
922 Inst.Offset == PrevOffset + 16) {
923 Inst.Operation = Win64EH::UOP_SaveNext;
924 Inst.Register = -1;
925 Inst.Offset = 0;
926 // Intentionally not creating UOP_SaveNext for float register pairs,
927 // as current versions of Windows (up to at least 20.04) is buggy
928 // regarding SaveNext for float pairs.
929 }
930 // Update info about the previous instruction, for detecting if
931 // the next one can be made a UOP_SaveNext
932 if (Inst.Operation == Win64EH::UOP_SaveR19R20X) {
933 PrevOffset = 0;
934 PrevRegister = 19;
935 } else if (Inst.Operation == Win64EH::UOP_SaveRegPX) {
936 PrevOffset = 0;
937 PrevRegister = Inst.Register;
938 } else if (Inst.Operation == Win64EH::UOP_SaveRegP) {
939 PrevOffset = Inst.Offset;
940 PrevRegister = Inst.Register;
941 } else if (Inst.Operation == Win64EH::UOP_SaveNext) {
942 PrevRegister += 2;
943 PrevOffset += 16;
944 } else {
945 PrevRegister = -1;
946 PrevOffset = -1;
947 }
948 }
949}
950
951// Check if an epilog exists as a subset of the end of a prolog (backwards).
952static int
953getARM64OffsetInProlog(const std::vector<WinEH::Instruction> &Prolog,
954 const std::vector<WinEH::Instruction> &Epilog) {
955 // Can't find an epilog as a subset if it is longer than the prolog.
956 if (Epilog.size() > Prolog.size())
957 return -1;
958
959 // Check that the epilog actually is a perfect match for the end (backwrds)
960 // of the prolog.
961 for (int I = Epilog.size() - 1; I >= 0; I--) {
962 if (Prolog[I] != Epilog[Epilog.size() - 1 - I])
963 return -1;
964 }
965
966 if (Epilog.size() == Prolog.size())
967 return 0;
968
969 // If the epilog was a subset of the prolog, find its offset.
971 &Prolog[Epilog.size()], Prolog.size() - Epilog.size()));
972}
973
976 int PrologCodeBytes) {
977 // Can only pack if there's one single epilog
978 if (Seg->Epilogs.size() != 1)
979 return -1;
980
981 MCSymbol *Sym = Seg->Epilogs.begin()->first;
982 const std::vector<WinEH::Instruction> &Epilog =
983 info->EpilogMap[Sym].Instructions;
984
985 // Check that the epilog actually is at the very end of the function,
986 // otherwise it can't be packed.
987 uint32_t DistanceFromEnd =
988 (uint32_t)(Seg->Offset + Seg->Length - Seg->Epilogs.begin()->second);
989 if (DistanceFromEnd / 4 != Epilog.size())
990 return -1;
991
992 int RetVal = -1;
993 // Even if we don't end up sharing opcodes with the prolog, we can still
994 // write the offset as a packed offset, if the single epilog is located at
995 // the end of the function and the offset (pointing after the prolog) fits
996 // as a packed offset.
997 if (PrologCodeBytes <= 31 &&
998 PrologCodeBytes + ARM64CountOfUnwindCodes(Epilog) <= 124)
999 RetVal = PrologCodeBytes;
1000
1001 int Offset = getARM64OffsetInProlog(info->Instructions, Epilog);
1002 if (Offset < 0)
1003 return RetVal;
1004
1005 // Check that the offset and prolog size fits in the first word; it's
1006 // unclear whether the epilog count in the extension word can be taken
1007 // as packed epilog offset.
1008 if (Offset > 31 || PrologCodeBytes > 124)
1009 return RetVal;
1010
1011 // As we choose to express the epilog as part of the prolog, remove the
1012 // epilog from the map, so we don't try to emit its opcodes.
1013 info->EpilogMap.erase(Sym);
1014 return Offset;
1015}
1016
1018 int PackedEpilogOffset) {
1019 if (PackedEpilogOffset == 0) {
1020 // Fully symmetric prolog and epilog, should be ok for packed format.
1021 // For CR=3, the corresponding synthesized epilog actually lacks the
1022 // SetFP opcode, but unwinding should work just fine despite that
1023 // (if at the SetFP opcode, the unwinder considers it as part of the
1024 // function body and just unwinds the full prolog instead).
1025 } else if (PackedEpilogOffset == 1) {
1026 // One single case of differences between prolog and epilog is allowed:
1027 // The epilog can lack a single SetFP that is the last opcode in the
1028 // prolog, for the CR=3 case.
1029 if (info->Instructions.back().Operation != Win64EH::UOP_SetFP)
1030 return false;
1031 } else {
1032 // Too much difference between prolog and epilog.
1033 return false;
1034 }
1035 unsigned RegI = 0, RegF = 0;
1036 int Predecrement = 0;
1037 enum {
1038 Start,
1039 Start2,
1040 Start3,
1041 IntRegs,
1042 FloatRegs,
1043 InputArgs,
1044 StackAdjust,
1045 FrameRecord,
1046 End
1047 } Location = Start;
1048 bool StandaloneLR = false, FPLRPair = false;
1049 bool PAC = false;
1050 int StackOffset = 0;
1051 int Nops = 0;
1052 // Iterate over the prolog and check that all opcodes exactly match
1053 // the canonical order and form. A more lax check could verify that
1054 // all saved registers are in the expected locations, but not enforce
1055 // the order - that would work fine when unwinding from within
1056 // functions, but not be exactly right if unwinding happens within
1057 // prologs/epilogs.
1058 for (auto It = info->Instructions.begin(), EndIt = info->Instructions.end();
1059 It != EndIt; It++) {
1060 const WinEH::Instruction &Inst = *It;
1061 switch (Inst.Operation) {
1062 case Win64EH::UOP_End:
1063 if (Location != Start)
1064 return false;
1065 Location = Start2;
1066 break;
1068 if (Location != Start2)
1069 return false;
1070 PAC = true;
1071 Location = Start3;
1072 break;
1074 if (Location != Start2 && Location != Start3)
1075 return false;
1076 Predecrement = Inst.Offset;
1077 RegI = 2;
1078 Location = IntRegs;
1079 break;
1081 if (Location != Start2 && Location != Start3)
1082 return false;
1083 Predecrement = Inst.Offset;
1084 if (Inst.Register == 19)
1085 RegI += 1;
1086 else if (Inst.Register == 30)
1087 StandaloneLR = true;
1088 else
1089 return false;
1090 // Odd register; can't be any further int registers.
1091 Location = FloatRegs;
1092 break;
1094 // Can't have this in a canonical prologue. Either this has been
1095 // canonicalized into SaveR19R20X or SaveFPLRX, or it's an unsupported
1096 // register pair.
1097 // It can't be canonicalized into SaveR19R20X if the offset is
1098 // larger than 248 bytes, but even with the maximum case with
1099 // RegI=10/RegF=8/CR=1/H=1, we end up with SavSZ = 216, which should
1100 // fit into SaveR19R20X.
1101 // The unwinding opcodes can't describe the otherwise seemingly valid
1102 // case for RegI=1 CR=1, that would start with a
1103 // "stp x19, lr, [sp, #-...]!" as that fits neither SaveRegPX nor
1104 // SaveLRPair.
1105 return false;
1107 if (Location != IntRegs || Inst.Offset != 8 * RegI ||
1108 Inst.Register != 19 + RegI)
1109 return false;
1110 RegI += 2;
1111 break;
1113 if (Location != IntRegs || Inst.Offset != 8 * RegI)
1114 return false;
1115 if (Inst.Register == 19 + RegI)
1116 RegI += 1;
1117 else if (Inst.Register == 30)
1118 StandaloneLR = true;
1119 else
1120 return false;
1121 // Odd register; can't be any further int registers.
1122 Location = FloatRegs;
1123 break;
1125 if (Location != IntRegs || Inst.Offset != 8 * RegI ||
1126 Inst.Register != 19 + RegI)
1127 return false;
1128 RegI += 1;
1129 StandaloneLR = true;
1130 Location = FloatRegs;
1131 break;
1133 // Packed unwind can't handle prologs that only save one single
1134 // float register.
1135 return false;
1137 if (Location != FloatRegs || RegF == 0 || Inst.Register != 8 + RegF ||
1138 Inst.Offset != 8 * (RegI + (StandaloneLR ? 1 : 0) + RegF))
1139 return false;
1140 RegF += 1;
1141 Location = InputArgs;
1142 break;
1144 if ((Location != Start2 && Location != Start3) || Inst.Register != 8)
1145 return false;
1146 Predecrement = Inst.Offset;
1147 RegF = 2;
1148 Location = FloatRegs;
1149 break;
1151 if ((Location != IntRegs && Location != FloatRegs) ||
1152 Inst.Register != 8 + RegF ||
1153 Inst.Offset != 8 * (RegI + (StandaloneLR ? 1 : 0) + RegF))
1154 return false;
1155 RegF += 2;
1156 Location = FloatRegs;
1157 break;
1159 if (Location == IntRegs)
1160 RegI += 2;
1161 else if (Location == FloatRegs)
1162 RegF += 2;
1163 else
1164 return false;
1165 break;
1166 case Win64EH::UOP_Nop:
1167 if (Location != IntRegs && Location != FloatRegs && Location != InputArgs)
1168 return false;
1169 Location = InputArgs;
1170 Nops++;
1171 break;
1174 if (Location != Start2 && Location != Start3 && Location != IntRegs &&
1175 Location != FloatRegs && Location != InputArgs &&
1176 Location != StackAdjust)
1177 return false;
1178 // Becuase there's no save_lrpair_x opcode, the case of CR=01,
1179 // RegI=1 is handled as a special case with a pair of instructions; an
1180 // alloc followed by a regular save_lrpair. So when encountering an
1181 // alloc here, check if this is the start of such an instruction pair.
1182 if (Location == Start2) { // Can't have this at Start3, after PACSignLR
1183 auto NextIt = It + 1;
1184 if (NextIt != EndIt) {
1185 const WinEH::Instruction &NextInst = *NextIt;
1186 if (NextInst.Operation == Win64EH::UOP_SaveLRPair &&
1187 NextInst.Offset == 0 && NextInst.Register == 19) {
1188 assert(Predecrement == 0);
1189 assert(RegI == 0);
1190 assert(!StandaloneLR);
1191 Predecrement = Inst.Offset;
1192 RegI = 1;
1193 StandaloneLR = true;
1194 Location = FloatRegs;
1195 It++; // Consume both the Alloc and the SaveLRPair
1196 continue;
1197 }
1198 }
1199 }
1200 // Can have either a single decrement, or a pair of decrements with
1201 // 4080 and another decrement.
1202 if (StackOffset == 0)
1203 StackOffset = Inst.Offset;
1204 else if (StackOffset != 4080)
1205 return false;
1206 else
1207 StackOffset += Inst.Offset;
1208 Location = StackAdjust;
1209 break;
1211 // Not allowing FPLRX after StackAdjust; if a StackAdjust is used, it
1212 // should be followed by a FPLR instead.
1213 if (Location != Start2 && Location != Start3 && Location != IntRegs &&
1214 Location != FloatRegs && Location != InputArgs)
1215 return false;
1216 StackOffset = Inst.Offset;
1217 Location = FrameRecord;
1218 FPLRPair = true;
1219 break;
1221 // This can only follow after a StackAdjust
1222 if (Location != StackAdjust || Inst.Offset != 0)
1223 return false;
1224 Location = FrameRecord;
1225 FPLRPair = true;
1226 break;
1227 case Win64EH::UOP_SetFP:
1228 if (Location != FrameRecord)
1229 return false;
1230 Location = End;
1231 break;
1244 // These are never canonical; they don't show up with the usual Arm64
1245 // calling convention.
1246 return false;
1248 // Allocations this large can't be represented in packed unwind (and
1249 // usually don't fit the canonical form anyway because we need to use
1250 // __chkstk to allocate the stack space).
1251 return false;
1252 case Win64EH::UOP_AddFP:
1253 // "add x29, sp, #N" doesn't show up in the canonical pattern (except for
1254 // N=0, which is UOP_SetFP).
1255 return false;
1259 // Canonical prologues don't support spilling SVE registers.
1260 return false;
1266 // These are special opcodes that aren't normally generated.
1267 return false;
1268 default:
1269 report_fatal_error("Unknown Arm64 unwind opcode");
1270 }
1271 }
1272 if (RegI > 10 || RegF > 8)
1273 return false;
1274 if (StandaloneLR && FPLRPair)
1275 return false;
1276 if (FPLRPair && Location != End)
1277 return false;
1278 if (Nops != 0 && Nops != 4)
1279 return false;
1280 if (PAC && !FPLRPair)
1281 return false;
1282 int H = Nops == 4;
1283 // For packed unwind info with the H bit set, the prolog and epilog
1284 // actually shouldn't be symmetrical; the epilog shouldn't have any
1285 // nop instructions/opcodes while the prolog has them. We currently
1286 // require exactly symmetrical prologs/epilogs, which is wrong for this
1287 // case - therefore, don't emit packed unwind info for this case.
1288 // See https://github.com/llvm/llvm-project/issues/54879 for details.
1289 //
1290 // Additionally - older versions of Windows also deviated from the
1291 // documentation here; older versions of Windows (at least up until
1292 // 10.0.22000.2176) incorrectly did assume that the epilog has matching
1293 // nop instructions. This is fixed at least in version 10.0.26100.6899.
1294 // As long as we can't assume that the generated code always will run on
1295 // a new enough version, don't emit the packed format here, even if the
1296 // implementation would be fixed to match for the asymmetrical form
1297 // according to the documentation.
1298 if (H)
1299 return false;
1300 // Older versions of Windows (at least in 10.0.22000.2176) incorrectly
1301 // unwind packed unwind info with CR=01, RegI=1, RegF>0, see
1302 // https://github.com/llvm/llvm-project/issues/169588#issuecomment-3584907886.
1303 // This issue only exists in older versions; current versions
1304 // (10.0.26100.6899) do handle it correctly. As long as we can't be sure
1305 // that we won't run on older versions, avoid producing the packed form
1306 // here.
1307 if (StandaloneLR && RegI == 1 && RegF > 0)
1308 return false;
1309 int IntSZ = 8 * RegI;
1310 if (StandaloneLR)
1311 IntSZ += 8;
1312 int FpSZ = 8 * RegF; // RegF not yet decremented
1313 int SavSZ = (IntSZ + FpSZ + 8 * 8 * H + 0xF) & ~0xF;
1314 if (Predecrement != SavSZ)
1315 return false;
1316 if (FPLRPair && StackOffset < 16)
1317 return false;
1318 if (StackOffset % 16)
1319 return false;
1320 uint32_t FrameSize = (StackOffset + SavSZ) / 16;
1321 if (FrameSize > 0x1FF)
1322 return false;
1323 assert(RegF != 1 && "One single float reg not allowed");
1324 if (RegF > 0)
1325 RegF--; // Convert from actual number of registers, to value stored
1326 assert(FuncLength <= 0x7FF && "FuncLength should have been checked earlier");
1327 int Flag = 0x01; // Function segments not supported yet
1328 int CR = PAC ? 2 : FPLRPair ? 3 : StandaloneLR ? 1 : 0;
1329 info->PackedInfo |= Flag << 0;
1330 info->PackedInfo |= (FuncLength & 0x7FF) << 2;
1331 info->PackedInfo |= (RegF & 0x7) << 13;
1332 info->PackedInfo |= (RegI & 0xF) << 16;
1333 info->PackedInfo |= (H & 0x1) << 20;
1334 info->PackedInfo |= (CR & 0x3) << 21;
1335 info->PackedInfo |= (FrameSize & 0x1FF) << 23;
1336 return true;
1337}
1338
1341 uint32_t &TotalCodeBytes,
1342 MapVector<MCSymbol *, uint32_t> &EpilogInfo) {
1343
1344 std::vector<MCSymbol *> EpilogStarts;
1345 for (auto &I : Seg->Epilogs)
1346 EpilogStarts.push_back(I.first);
1347
1348 // Epilogs processed so far.
1349 std::vector<MCSymbol *> AddedEpilogs;
1350 for (auto *S : EpilogStarts) {
1351 MCSymbol *EpilogStart = S;
1352 auto &EpilogInstrs = info->EpilogMap[S].Instructions;
1353 uint32_t CodeBytes = ARM64CountOfUnwindCodes(EpilogInstrs);
1354
1355 MCSymbol* MatchingEpilog =
1356 FindMatchingEpilog(EpilogInstrs, AddedEpilogs, info);
1357 int PrologOffset;
1358 if (MatchingEpilog) {
1359 assert(EpilogInfo.contains(MatchingEpilog) &&
1360 "Duplicate epilog not found");
1361 EpilogInfo[EpilogStart] = EpilogInfo.lookup(MatchingEpilog);
1362 // Clear the unwind codes in the EpilogMap, so that they don't get output
1363 // in ARM64EmitUnwindInfoForSegment().
1364 EpilogInstrs.clear();
1365 } else if ((PrologOffset = getARM64OffsetInProlog(info->Instructions,
1366 EpilogInstrs)) >= 0) {
1367 EpilogInfo[EpilogStart] = PrologOffset;
1368 // If the segment doesn't have a prolog, an end_c will be emitted before
1369 // prolog opcodes. So epilog start index in opcodes array is moved by 1.
1370 if (!Seg->HasProlog)
1371 EpilogInfo[EpilogStart] += 1;
1372 // Clear the unwind codes in the EpilogMap, so that they don't get output
1373 // in ARM64EmitUnwindInfoForSegment().
1374 EpilogInstrs.clear();
1375 } else {
1376 EpilogInfo[EpilogStart] = TotalCodeBytes;
1377 TotalCodeBytes += CodeBytes;
1378 AddedEpilogs.push_back(EpilogStart);
1379 }
1380 }
1381}
1382
1385 int64_t RawFuncLength) {
1386 if (info->PrologEnd)
1387 checkARM64Instructions(streamer, info->Instructions, info->Begin,
1388 info->PrologEnd, info->Function->getName(),
1389 "prologue");
1390 struct EpilogStartEnd {
1391 MCSymbol *Start;
1392 int64_t Offset;
1393 int64_t End;
1394 };
1395 // Record Start and End of each epilog.
1397 for (auto &I : info->EpilogMap) {
1398 MCSymbol *Start = I.first;
1399 auto &Instrs = I.second.Instructions;
1400 int64_t Offset = GetAbsDifference(streamer, Start, info->Begin);
1401 checkARM64Instructions(streamer, Instrs, Start, I.second.End,
1402 info->Function->getName(), "epilogue");
1403 assert((Epilogs.size() == 0 || Offset >= Epilogs.back().End) &&
1404 "Epilogs should be monotonically ordered");
1405 // Exclue the end opcode from Instrs.size() when calculating the end of the
1406 // epilog.
1407 Epilogs.push_back({Start, Offset, Offset + (int64_t)(Instrs.size() - 1) * 4});
1408 }
1409
1410 unsigned E = 0;
1411 int64_t SegLimit = 0xFFFFC;
1412 int64_t SegOffset = 0;
1413
1414 if (RawFuncLength > SegLimit) {
1415
1416 int64_t RemainingLength = RawFuncLength;
1417
1418 while (RemainingLength > SegLimit) {
1419 // Try divide the function into segments, requirements:
1420 // 1. Segment length <= 0xFFFFC;
1421 // 2. Each Prologue or Epilogue must be fully within a segment.
1422 int64_t SegLength = SegLimit;
1423 int64_t SegEnd = SegOffset + SegLength;
1424 // Keep record on symbols and offsets of epilogs in this segment.
1425 MapVector<MCSymbol *, int64_t> EpilogsInSegment;
1426
1427 while (E < Epilogs.size() && Epilogs[E].End < SegEnd) {
1428 // Epilogs within current segment.
1429 EpilogsInSegment[Epilogs[E].Start] = Epilogs[E].Offset;
1430 ++E;
1431 }
1432
1433 // At this point, we have:
1434 // 1. Put all epilogs in segments already. No action needed here; or
1435 // 2. Found an epilog that will cross segments boundry. We need to
1436 // move back current segment's end boundry, so the epilog is entirely
1437 // in the next segment; or
1438 // 3. Left at least one epilog that is entirely after this segment.
1439 // It'll be handled by the next iteration, or the last segment.
1440 if (E < Epilogs.size() && Epilogs[E].Offset <= SegEnd)
1441 // Move back current Segment's end boundry.
1442 SegLength = Epilogs[E].Offset - SegOffset;
1443
1444 auto Seg = WinEH::FrameInfo::Segment(
1445 SegOffset, SegLength, /* HasProlog */!SegOffset);
1446 Seg.Epilogs = std::move(EpilogsInSegment);
1447 info->Segments.push_back(Seg);
1448
1449 SegOffset += SegLength;
1450 RemainingLength -= SegLength;
1451 }
1452 }
1453
1454 // Add the last segment when RawFuncLength > 0xFFFFC,
1455 // or the only segment otherwise.
1456 auto LastSeg =
1457 WinEH::FrameInfo::Segment(SegOffset, RawFuncLength - SegOffset,
1458 /* HasProlog */!SegOffset);
1459 for (; E < Epilogs.size(); ++E)
1460 LastSeg.Epilogs[Epilogs[E].Start] = Epilogs[E].Offset;
1461 info->Segments.push_back(LastSeg);
1462}
1463
1467 bool TryPacked = true) {
1468 MCContext &context = streamer.getContext();
1469 MCSymbol *Label = context.createTempSymbol();
1470
1471 streamer.emitValueToAlignment(Align(4));
1472 streamer.emitLabel(Label);
1473 Seg.Symbol = Label;
1474 // Use the 1st segemnt's label as function's.
1475 if (Seg.Offset == 0)
1476 info->Symbol = Label;
1477
1478 bool HasProlog = Seg.HasProlog;
1479 bool HasEpilogs = (Seg.Epilogs.size() != 0);
1480
1481 uint32_t SegLength = (uint32_t)Seg.Length / 4;
1482 uint32_t PrologCodeBytes = info->PrologCodeBytes;
1483
1484 int PackedEpilogOffset = HasEpilogs ?
1485 checkARM64PackedEpilog(streamer, info, &Seg, PrologCodeBytes) : -1;
1486
1487 // TODO:
1488 // 1. Enable packed unwind info (.pdata only) for multi-segment functions.
1489 // 2. Emit packed unwind info (.pdata only) for segments that have neithor
1490 // prolog nor epilog.
1491 if (info->Segments.size() == 1 && PackedEpilogOffset >= 0 &&
1492 uint32_t(PackedEpilogOffset) < PrologCodeBytes &&
1493 !info->HandlesExceptions && SegLength <= 0x7ff && TryPacked) {
1494 // Matching prolog/epilog and no exception handlers; check if the
1495 // prolog matches the patterns that can be described by the packed
1496 // format.
1497
1498 // info->Symbol was already set even if we didn't actually write any
1499 // unwind info there. Keep using that as indicator that this unwind
1500 // info has been generated already.
1501 if (tryARM64PackedUnwind(info, SegLength, PackedEpilogOffset))
1502 return;
1503 }
1504
1505 // If the prolog is not in this segment, we need to emit an end_c, which takes
1506 // 1 byte, before prolog unwind ops.
1507 if (!HasProlog) {
1508 PrologCodeBytes += 1;
1509 if (PackedEpilogOffset >= 0)
1510 PackedEpilogOffset += 1;
1511 // If a segment has neither prolog nor epilog, "With full .xdata record,
1512 // Epilog Count = 1. Epilog Start Index points to end_c."
1513 // https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling#function-fragments
1514 // TODO: We can remove this if testing shows zero epilog scope is ok with
1515 // MS unwinder.
1516 if (!HasEpilogs)
1517 // Pack the fake epilog into phantom prolog.
1518 PackedEpilogOffset = 0;
1519 }
1520
1521 uint32_t TotalCodeBytes = PrologCodeBytes;
1522
1523 // Process epilogs.
1525 ARM64ProcessEpilogs(info, &Seg, TotalCodeBytes, EpilogInfo);
1526
1527 // Code Words, Epilog count, E, X, Vers, Function Length
1528 uint32_t row1 = 0x0;
1529 uint32_t CodeWords = TotalCodeBytes / 4;
1530 uint32_t CodeWordsMod = TotalCodeBytes % 4;
1531 if (CodeWordsMod)
1532 CodeWords++;
1533 uint32_t EpilogCount =
1534 PackedEpilogOffset >= 0 ? PackedEpilogOffset : Seg.Epilogs.size();
1535 bool ExtensionWord = EpilogCount > 31 || TotalCodeBytes > 124;
1536 if (!ExtensionWord) {
1537 row1 |= (EpilogCount & 0x1F) << 22;
1538 row1 |= (CodeWords & 0x1F) << 27;
1539 }
1540 if (info->HandlesExceptions) // X
1541 row1 |= 1 << 20;
1542 if (PackedEpilogOffset >= 0) // E
1543 row1 |= 1 << 21;
1544 row1 |= SegLength & 0x3FFFF;
1545 streamer.emitInt32(row1);
1546
1547 // Extended Code Words, Extended Epilog Count
1548 if (ExtensionWord) {
1549 // FIXME: We should be able to split unwind info into multiple sections.
1550 if (CodeWords > 0xFF || EpilogCount > 0xFFFF)
1552 "SEH unwind data splitting is only implemented for large functions, "
1553 "cases of too many code words or too many epilogs will be done "
1554 "later");
1555 uint32_t row2 = 0x0;
1556 row2 |= (CodeWords & 0xFF) << 16;
1557 row2 |= (EpilogCount & 0xFFFF);
1558 streamer.emitInt32(row2);
1559 }
1560
1561 if (PackedEpilogOffset < 0) {
1562 // Epilog Start Index, Epilog Start Offset
1563 for (auto &I : EpilogInfo) {
1564 MCSymbol *EpilogStart = I.first;
1565 uint32_t EpilogIndex = I.second;
1566 // Epilog offset within the Segment.
1567 uint32_t EpilogOffset = (uint32_t)(Seg.Epilogs[EpilogStart] - Seg.Offset);
1568 if (EpilogOffset)
1569 EpilogOffset /= 4;
1570 uint32_t row3 = EpilogOffset;
1571 row3 |= (EpilogIndex & 0x3FF) << 22;
1572 streamer.emitInt32(row3);
1573 }
1574 }
1575
1576 // Note that even for segments that have no prolog, we still need to emit
1577 // prolog unwinding opcodes so that the unwinder knows how to unwind from
1578 // such a segment.
1579 // The end_c opcode at the start indicates to the unwinder that the actual
1580 // prolog is outside of the current segment, and the unwinder shouldn't try
1581 // to check for unwinding from a partial prolog.
1582 if (!HasProlog)
1583 // Emit an end_c.
1584 streamer.emitInt8((uint8_t)0xE5);
1585
1586 // Emit prolog unwind instructions (in reverse order).
1587 for (auto Inst : llvm::reverse(info->Instructions))
1588 ARM64EmitUnwindCode(streamer, Inst);
1589
1590 // Emit epilog unwind instructions
1591 for (auto &I : Seg.Epilogs) {
1592 auto &EpilogInstrs = info->EpilogMap[I.first].Instructions;
1593 for (const WinEH::Instruction &inst : EpilogInstrs)
1594 ARM64EmitUnwindCode(streamer, inst);
1595 }
1596
1597 int32_t BytesMod = CodeWords * 4 - TotalCodeBytes;
1598 assert(BytesMod >= 0);
1599 for (int i = 0; i < BytesMod; i++)
1600 streamer.emitInt8(0xE3);
1601
1602 if (info->HandlesExceptions)
1603 streamer.emitValue(
1604 MCSymbolRefExpr::create(info->ExceptionHandler,
1606 4);
1607}
1608
1609// Populate the .xdata section. The format of .xdata on ARM64 is documented at
1610// https://docs.microsoft.com/en-us/cpp/build/arm64-exception-handling
1612 bool TryPacked = true) {
1613 // If this UNWIND_INFO already has a symbol, it's already been emitted.
1614 if (info->Symbol)
1615 return;
1616 // If there's no unwind info here (not even a terminating UOP_End), the
1617 // unwind info is considered bogus and skipped. If this was done in
1618 // response to an explicit .seh_handlerdata, the associated trailing
1619 // handler data is left orphaned in the xdata section.
1620 if (info->empty()) {
1621 info->EmitAttempted = true;
1622 return;
1623 }
1624 if (info->EmitAttempted) {
1625 // If we tried to emit unwind info before (due to an explicit
1626 // .seh_handlerdata directive), but skipped it (because there was no
1627 // valid information to emit at the time), and it later got valid unwind
1628 // opcodes, we can't emit it here, because the trailing handler data
1629 // was already emitted elsewhere in the xdata section.
1630 streamer.getContext().reportError(
1631 SMLoc(), "Earlier .seh_handlerdata for " + info->Function->getName() +
1632 " skipped due to no unwind info at the time "
1633 "(.seh_handlerdata too early?), but the function later "
1634 "did get unwind info that can't be emitted");
1635 return;
1636 }
1637
1638 simplifyARM64Opcodes(info->Instructions, false);
1639 for (auto &I : info->EpilogMap)
1640 simplifyARM64Opcodes(I.second.Instructions, true);
1641
1642 int64_t RawFuncLength;
1643 if (!info->FuncletOrFuncEnd) {
1644 report_fatal_error("FuncletOrFuncEnd not set");
1645 } else {
1646 // FIXME: GetAbsDifference tries to compute the length of the function
1647 // immediately, before the whole file is emitted, but in general
1648 // that's impossible: the size in bytes of certain assembler directives
1649 // like .align and .fill is not known until the whole file is parsed and
1650 // relaxations are applied. Currently, GetAbsDifference fails with a fatal
1651 // error in that case. (We mostly don't hit this because inline assembly
1652 // specifying those directives is rare, and we don't normally try to
1653 // align loops on AArch64.)
1654 //
1655 // There are two potential approaches to delaying the computation. One,
1656 // we could emit something like ".word (endfunc-beginfunc)/4+0x10800000",
1657 // as long as we have some conservative estimate we could use to prove
1658 // that we don't need to split the unwind data. Emitting the constant
1659 // is straightforward, but there's no existing code for estimating the
1660 // size of the function.
1661 //
1662 // The other approach would be to use a dedicated, relaxable fragment,
1663 // which could grow to accommodate splitting the unwind data if
1664 // necessary. This is more straightforward, since it automatically works
1665 // without any new infrastructure, and it's consistent with how we handle
1666 // relaxation in other contexts. But it would require some refactoring
1667 // to move parts of the pdata/xdata emission into the implementation of
1668 // a fragment. We could probably continue to encode the unwind codes
1669 // here, but we'd have to emit the pdata, the xdata header, and the
1670 // epilogue scopes later, since they depend on whether the we need to
1671 // split the unwind data.
1672 //
1673 // If this is fixed, remove code in AArch64ISelLowering.cpp that
1674 // disables loop alignment on Windows.
1675 RawFuncLength = GetAbsDifference(streamer, info->FuncletOrFuncEnd,
1676 info->Begin);
1677 }
1678
1679 ARM64FindSegmentsInFunction(streamer, info, RawFuncLength);
1680
1681 info->PrologCodeBytes = ARM64CountOfUnwindCodes(info->Instructions);
1682 for (auto &S : info->Segments)
1683 ARM64EmitUnwindInfoForSegment(streamer, info, S, TryPacked);
1684
1685 // Clear prolog instructions after unwind info is emitted for all segments.
1686 info->Instructions.clear();
1687}
1688
1690 uint32_t Count = 0;
1691 for (const auto &I : Insns) {
1692 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
1693 default:
1694 llvm_unreachable("Unsupported ARM unwind code");
1696 Count += 1;
1697 break;
1699 Count += 3;
1700 break;
1702 Count += 4;
1703 break;
1705 Count += 2;
1706 break;
1708 Count += 3;
1709 break;
1711 Count += 4;
1712 break;
1714 Count += 2;
1715 break;
1717 Count += 1;
1718 break;
1720 Count += 1;
1721 break;
1723 Count += 1;
1724 break;
1726 Count += 1;
1727 break;
1729 Count += 2;
1730 break;
1732 Count += 2;
1733 break;
1735 Count += 2;
1736 break;
1738 Count += 2;
1739 break;
1740 case Win64EH::UOP_Nop:
1742 case Win64EH::UOP_End:
1745 Count += 1;
1746 break;
1747 case Win64EH::UOP_Custom: {
1748 int J;
1749 for (J = 3; J > 0; J--)
1750 if (I.Offset & (0xffu << (8 * J)))
1751 break;
1752 Count += J + 1;
1753 break;
1754 }
1755 }
1756 }
1757 return Count;
1758}
1759
1761 bool *HasCustom = nullptr) {
1762 uint32_t Count = 0;
1763 for (const auto &I : Insns) {
1764 switch (static_cast<Win64EH::UnwindOpcodes>(I.Operation)) {
1765 default:
1766 llvm_unreachable("Unsupported ARM unwind code");
1770 Count += 2;
1771 break;
1775 Count += 4;
1776 break;
1779 Count += 4;
1780 break;
1782 Count += 2;
1783 break;
1786 Count += 2;
1787 break;
1791 Count += 4;
1792 break;
1794 Count += 4;
1795 break;
1796 case Win64EH::UOP_Nop:
1798 Count += 2;
1799 break;
1802 Count += 4;
1803 break;
1804 case Win64EH::UOP_End:
1805 // This doesn't map to any instruction
1806 break;
1808 // We can't reason about what instructions this maps to; return a
1809 // phony number to make sure we don't accidentally do epilog packing.
1810 Count += 1000;
1811 if (HasCustom)
1812 *HasCustom = true;
1813 break;
1814 }
1815 }
1816 return Count;
1817}
1818
1819static void checkARMInstructions(MCStreamer &Streamer,
1821 const MCSymbol *Begin, const MCSymbol *End,
1822 StringRef Name, StringRef Type) {
1823 if (!End)
1824 return;
1825 std::optional<int64_t> MaybeDistance =
1826 GetOptionalAbsDifference(Streamer, End, Begin);
1827 if (!MaybeDistance)
1828 return;
1829 uint32_t Distance = (uint32_t)*MaybeDistance;
1830 bool HasCustom = false;
1831 uint32_t InstructionBytes = ARMCountOfInstructionBytes(Insns, &HasCustom);
1832 if (HasCustom)
1833 return;
1834 if (Distance != InstructionBytes) {
1835 Streamer.getContext().reportError(
1836 SMLoc(), "Incorrect size for " + Name + " " + Type + ": " +
1837 Twine(Distance) +
1838 " bytes of instructions in range, but .seh directives "
1839 "corresponding to " +
1840 Twine(InstructionBytes) + " bytes\n");
1841 }
1842}
1843
1844static bool isARMTerminator(const WinEH::Instruction &inst) {
1845 switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
1846 case Win64EH::UOP_End:
1849 return true;
1850 default:
1851 return false;
1852 }
1853}
1854
1855// Unwind opcode encodings and restrictions are documented at
1856// https://docs.microsoft.com/en-us/cpp/build/arm-exception-handling
1857static void ARMEmitUnwindCode(MCStreamer &streamer,
1858 const WinEH::Instruction &inst) {
1859 uint32_t w, lr;
1860 int i;
1861 switch (static_cast<Win64EH::UnwindOpcodes>(inst.Operation)) {
1862 default:
1863 llvm_unreachable("Unsupported ARM unwind code");
1865 assert((inst.Offset & 3) == 0);
1866 assert(inst.Offset / 4 <= 0x7f);
1867 streamer.emitInt8(inst.Offset / 4);
1868 break;
1870 assert((inst.Register & ~0x5fff) == 0);
1871 lr = (inst.Register >> 14) & 1;
1872 w = 0x8000 | (inst.Register & 0x1fff) | (lr << 13);
1873 streamer.emitInt8((w >> 8) & 0xff);
1874 streamer.emitInt8((w >> 0) & 0xff);
1875 break;
1877 assert(inst.Register <= 0x0f);
1878 streamer.emitInt8(0xc0 | inst.Register);
1879 break;
1881 assert(inst.Register >= 4 && inst.Register <= 7);
1882 assert(inst.Offset <= 1);
1883 streamer.emitInt8(0xd0 | (inst.Register - 4) | (inst.Offset << 2));
1884 break;
1886 assert(inst.Register >= 8 && inst.Register <= 11);
1887 assert(inst.Offset <= 1);
1888 streamer.emitInt8(0xd8 | (inst.Register - 8) | (inst.Offset << 2));
1889 break;
1891 assert(inst.Register >= 8 && inst.Register <= 15);
1892 streamer.emitInt8(0xe0 | (inst.Register - 8));
1893 break;
1895 assert((inst.Offset & 3) == 0);
1896 assert(inst.Offset / 4 <= 0x3ff);
1897 w = 0xe800 | (inst.Offset / 4);
1898 streamer.emitInt8((w >> 8) & 0xff);
1899 streamer.emitInt8((w >> 0) & 0xff);
1900 break;
1902 assert((inst.Register & ~0x40ff) == 0);
1903 lr = (inst.Register >> 14) & 1;
1904 w = 0xec00 | (inst.Register & 0x0ff) | (lr << 8);
1905 streamer.emitInt8((w >> 8) & 0xff);
1906 streamer.emitInt8((w >> 0) & 0xff);
1907 break;
1909 assert((inst.Offset & 3) == 0);
1910 assert(inst.Offset / 4 <= 0x0f);
1911 streamer.emitInt8(0xef);
1912 streamer.emitInt8(inst.Offset / 4);
1913 break;
1915 assert(inst.Register <= 15);
1916 assert(inst.Offset <= 15);
1917 assert(inst.Register <= inst.Offset);
1918 streamer.emitInt8(0xf5);
1919 streamer.emitInt8((inst.Register << 4) | inst.Offset);
1920 break;
1922 assert(inst.Register >= 16 && inst.Register <= 31);
1923 assert(inst.Offset >= 16 && inst.Offset <= 31);
1924 assert(inst.Register <= inst.Offset);
1925 streamer.emitInt8(0xf6);
1926 streamer.emitInt8(((inst.Register - 16) << 4) | (inst.Offset - 16));
1927 break;
1929 assert((inst.Offset & 3) == 0);
1930 assert(inst.Offset / 4 <= 0xffff);
1931 w = inst.Offset / 4;
1932 streamer.emitInt8(0xf7);
1933 streamer.emitInt8((w >> 8) & 0xff);
1934 streamer.emitInt8((w >> 0) & 0xff);
1935 break;
1937 assert((inst.Offset & 3) == 0);
1938 assert(inst.Offset / 4 <= 0xffffff);
1939 w = inst.Offset / 4;
1940 streamer.emitInt8(0xf8);
1941 streamer.emitInt8((w >> 16) & 0xff);
1942 streamer.emitInt8((w >> 8) & 0xff);
1943 streamer.emitInt8((w >> 0) & 0xff);
1944 break;
1946 assert((inst.Offset & 3) == 0);
1947 assert(inst.Offset / 4 <= 0xffff);
1948 w = inst.Offset / 4;
1949 streamer.emitInt8(0xf9);
1950 streamer.emitInt8((w >> 8) & 0xff);
1951 streamer.emitInt8((w >> 0) & 0xff);
1952 break;
1954 assert((inst.Offset & 3) == 0);
1955 assert(inst.Offset / 4 <= 0xffffff);
1956 w = inst.Offset / 4;
1957 streamer.emitInt8(0xfa);
1958 streamer.emitInt8((w >> 16) & 0xff);
1959 streamer.emitInt8((w >> 8) & 0xff);
1960 streamer.emitInt8((w >> 0) & 0xff);
1961 break;
1962 case Win64EH::UOP_Nop:
1963 streamer.emitInt8(0xfb);
1964 break;
1966 streamer.emitInt8(0xfc);
1967 break;
1969 streamer.emitInt8(0xfd);
1970 break;
1972 streamer.emitInt8(0xfe);
1973 break;
1974 case Win64EH::UOP_End:
1975 streamer.emitInt8(0xff);
1976 break;
1978 for (i = 3; i > 0; i--)
1979 if (inst.Offset & (0xffu << (8 * i)))
1980 break;
1981 for (; i >= 0; i--)
1982 streamer.emitInt8((inst.Offset >> (8 * i)) & 0xff);
1983 break;
1984 }
1985}
1986
1987// Check if an epilog exists as a subset of the end of a prolog (backwards).
1988// An epilog may end with one out of three different end opcodes; if this
1989// is the first epilog that shares opcodes with the prolog, we can tolerate
1990// that this opcode differs (and the caller will update the prolog to use
1991// the same end opcode as the epilog). If another epilog already shares
1992// opcodes with the prolog, the ending opcode must be a strict match.
1993static int getARMOffsetInProlog(const std::vector<WinEH::Instruction> &Prolog,
1994 const std::vector<WinEH::Instruction> &Epilog,
1995 bool CanTweakProlog) {
1996 // Can't find an epilog as a subset if it is longer than the prolog.
1997 if (Epilog.size() > Prolog.size())
1998 return -1;
1999
2000 // Check that the epilog actually is a perfect match for the end (backwrds)
2001 // of the prolog.
2002 // If we can adjust the prolog afterwards, don't check that the end opcodes
2003 // match.
2004 int EndIdx = CanTweakProlog ? 1 : 0;
2005 for (int I = Epilog.size() - 1; I >= EndIdx; I--) {
2006 // TODO: Could also allow minor mismatches, e.g. "add sp, #16" vs
2007 // "push {r0-r3}".
2008 if (Prolog[I] != Epilog[Epilog.size() - 1 - I])
2009 return -1;
2010 }
2011
2012 if (CanTweakProlog) {
2013 // Check that both prolog and epilog end with an expected end opcode.
2014 if (Prolog.front().Operation != Win64EH::UOP_End)
2015 return -1;
2016 if (Epilog.back().Operation != Win64EH::UOP_End &&
2017 Epilog.back().Operation != Win64EH::UOP_EndNop &&
2018 Epilog.back().Operation != Win64EH::UOP_WideEndNop)
2019 return -1;
2020 }
2021
2022 // If the epilog was a subset of the prolog, find its offset.
2023 if (Epilog.size() == Prolog.size())
2024 return 0;
2026 &Prolog[Epilog.size()], Prolog.size() - Epilog.size()));
2027}
2028
2030 int PrologCodeBytes) {
2031 // Can only pack if there's one single epilog
2032 if (info->EpilogMap.size() != 1)
2033 return -1;
2034
2035 const WinEH::FrameInfo::Epilog &EpilogInfo = info->EpilogMap.begin()->second;
2036 // Can only pack if the epilog is unconditional
2037 if (EpilogInfo.Condition != 0xe) // ARMCC::AL
2038 return -1;
2039
2040 const std::vector<WinEH::Instruction> &Epilog = EpilogInfo.Instructions;
2041 // Make sure we have at least the trailing end opcode
2042 if (info->Instructions.empty() || Epilog.empty())
2043 return -1;
2044
2045 // Check that the epilog actually is at the very end of the function,
2046 // otherwise it can't be packed.
2047 std::optional<int64_t> MaybeDistance = GetOptionalAbsDifference(
2048 streamer, info->FuncletOrFuncEnd, info->EpilogMap.begin()->first);
2049 if (!MaybeDistance)
2050 return -1;
2051 uint32_t DistanceFromEnd = (uint32_t)*MaybeDistance;
2052 uint32_t InstructionBytes = ARMCountOfInstructionBytes(Epilog);
2053 if (DistanceFromEnd != InstructionBytes)
2054 return -1;
2055
2056 int RetVal = -1;
2057 // Even if we don't end up sharing opcodes with the prolog, we can still
2058 // write the offset as a packed offset, if the single epilog is located at
2059 // the end of the function and the offset (pointing after the prolog) fits
2060 // as a packed offset.
2061 if (PrologCodeBytes <= 31 &&
2062 PrologCodeBytes + ARMCountOfUnwindCodes(Epilog) <= 63)
2063 RetVal = PrologCodeBytes;
2064
2065 int Offset =
2066 getARMOffsetInProlog(info->Instructions, Epilog, /*CanTweakProlog=*/true);
2067 if (Offset < 0)
2068 return RetVal;
2069
2070 // Check that the offset and prolog size fits in the first word; it's
2071 // unclear whether the epilog count in the extension word can be taken
2072 // as packed epilog offset.
2073 if (Offset > 31 || PrologCodeBytes > 63)
2074 return RetVal;
2075
2076 // Replace the regular end opcode of the prolog with the one from the
2077 // epilog.
2078 info->Instructions.front() = Epilog.back();
2079
2080 // As we choose to express the epilog as part of the prolog, remove the
2081 // epilog from the map, so we don't try to emit its opcodes.
2082 info->EpilogMap.clear();
2083 return Offset;
2084}
2085
2086static bool parseRegMask(unsigned Mask, bool &HasLR, bool &HasR11,
2087 unsigned &Folded, int &IntRegs) {
2088 if (Mask & (1 << 14)) {
2089 HasLR = true;
2090 Mask &= ~(1 << 14);
2091 }
2092 if (Mask & (1 << 11)) {
2093 HasR11 = true;
2094 Mask &= ~(1 << 11);
2095 }
2096 Folded = 0;
2097 IntRegs = -1;
2098 if (!Mask)
2099 return true;
2100 int First = 0;
2101 // Shift right until we have the bits at the bottom
2102 while ((Mask & 1) == 0) {
2103 First++;
2104 Mask >>= 1;
2105 }
2106 if ((Mask & (Mask + 1)) != 0)
2107 return false; // Not a consecutive series of bits? Can't be packed.
2108 // Count the bits
2109 int N = 0;
2110 while (Mask & (1 << N))
2111 N++;
2112 if (First < 4) {
2113 if (First + N < 4)
2114 return false;
2115 Folded = 4 - First;
2116 N -= Folded;
2117 First = 4;
2118 }
2119 if (First > 4)
2120 return false; // Can't be packed
2121 if (N >= 1)
2122 IntRegs = N - 1;
2123 return true;
2124}
2125
2127 uint32_t FuncLength) {
2128 int Step = 0;
2129 bool Homing = false;
2130 bool HasR11 = false;
2131 bool HasChain = false;
2132 bool HasLR = false;
2133 int IntRegs = -1; // r4 - r(4+N)
2134 int FloatRegs = -1; // d8 - d(8+N)
2135 unsigned PF = 0; // Number of extra pushed registers
2136 unsigned StackAdjust = 0;
2137 // Iterate over the prolog and check that all opcodes exactly match
2138 // the canonical order and form.
2139 for (const WinEH::Instruction &Inst : info->Instructions) {
2140 switch (Inst.Operation) {
2141 default:
2142 llvm_unreachable("Unsupported ARM unwind code");
2150 // Can't be packed
2151 return false;
2153 // Can't be packed; we can't rely on restoring sp from r11 when
2154 // unwinding a packed prologue.
2155 return false;
2157 // Can't be present in a packed prologue
2158 return false;
2159
2160 case Win64EH::UOP_End:
2163 if (Step != 0)
2164 return false;
2165 Step = 1;
2166 break;
2167
2170 // push {r4-r11,lr}
2171 if (Step != 1 && Step != 2)
2172 return false;
2173 assert(Inst.Register >= 4 && Inst.Register <= 11); // r4-rX
2174 assert(Inst.Offset <= 1); // Lr
2175 IntRegs = Inst.Register - 4;
2176 if (Inst.Register == 11) {
2177 HasR11 = true;
2178 IntRegs--;
2179 }
2180 if (Inst.Offset)
2181 HasLR = true;
2182 Step = 3;
2183 break;
2184
2186 if (Step == 1 && Inst.Register == 0x0f) {
2187 // push {r0-r3}
2188 Homing = true;
2189 Step = 2;
2190 break;
2191 }
2192 [[fallthrough]];
2194 if (Step != 1 && Step != 2)
2195 return false;
2196 // push {r4-r9,r11,lr}
2197 // push {r11,lr}
2198 // push {r1-r5}
2199 if (!parseRegMask(Inst.Register, HasLR, HasR11, PF, IntRegs))
2200 return false;
2201 Step = 3;
2202 break;
2203
2204 case Win64EH::UOP_Nop:
2205 // mov r11, sp
2206 if (Step != 3 || !HasR11 || IntRegs >= 0 || PF > 0)
2207 return false;
2208 HasChain = true;
2209 Step = 4;
2210 break;
2212 // add.w r11, sp, #xx
2213 if (Step != 3 || !HasR11 || (IntRegs < 0 && PF == 0))
2214 return false;
2215 HasChain = true;
2216 Step = 4;
2217 break;
2218
2220 if (Step != 1 && Step != 2 && Step != 3 && Step != 4)
2221 return false;
2222 assert(Inst.Register >= 8 && Inst.Register <= 15);
2223 if (Inst.Register == 15)
2224 return false; // Can't pack this case, R==7 means no IntRegs
2225 if (IntRegs >= 0)
2226 return false;
2227 FloatRegs = Inst.Register - 8;
2228 Step = 5;
2229 break;
2230
2233 if (Step != 1 && Step != 2 && Step != 3 && Step != 4 && Step != 5)
2234 return false;
2235 if (PF > 0) // Can't have both folded and explicit stack allocation
2236 return false;
2237 if (Inst.Offset / 4 >= 0x3f4)
2238 return false;
2239 StackAdjust = Inst.Offset / 4;
2240 Step = 6;
2241 break;
2242 }
2243 }
2244 if (HasR11 && !HasChain) {
2245 if (IntRegs + 4 == 10) {
2246 // r11 stored, but not chaining; can be packed if already saving r4-r10
2247 // and we can fit r11 into this range.
2248 IntRegs++;
2249 HasR11 = false;
2250 } else
2251 return false;
2252 }
2253 if (HasChain && !HasLR)
2254 return false;
2255
2256 // Packed uneind info can't express multiple epilogues.
2257 if (info->EpilogMap.size() > 1)
2258 return false;
2259
2260 unsigned EF = 0;
2261 int Ret = 0;
2262 if (info->EpilogMap.size() == 0) {
2263 Ret = 3; // No epilogue
2264 } else {
2265 // As the prologue and epilogue aren't exact mirrors of each other,
2266 // we have to check the epilogue too and see if it matches what we've
2267 // concluded from the prologue.
2268 const WinEH::FrameInfo::Epilog &EpilogInfo =
2269 info->EpilogMap.begin()->second;
2270 if (EpilogInfo.Condition != 0xe) // ARMCC::AL
2271 return false;
2272 const std::vector<WinEH::Instruction> &Epilog = EpilogInfo.Instructions;
2273 std::optional<int64_t> MaybeDistance = GetOptionalAbsDifference(
2274 streamer, info->FuncletOrFuncEnd, info->EpilogMap.begin()->first);
2275 if (!MaybeDistance)
2276 return false;
2277 uint32_t DistanceFromEnd = (uint32_t)*MaybeDistance;
2278 uint32_t InstructionBytes = ARMCountOfInstructionBytes(Epilog);
2279 if (DistanceFromEnd != InstructionBytes)
2280 return false;
2281
2282 bool GotStackAdjust = false;
2283 bool GotFloatRegs = false;
2284 bool GotIntRegs = false;
2285 bool GotHomingRestore = false;
2286 bool GotLRRestore = false;
2287 bool NeedsReturn = false;
2288 bool GotReturn = false;
2289
2290 Step = 6;
2291 for (const WinEH::Instruction &Inst : Epilog) {
2292 switch (Inst.Operation) {
2293 default:
2294 llvm_unreachable("Unsupported ARM unwind code");
2303 case Win64EH::UOP_Nop:
2305 // Can't be packed in an epilogue
2306 return false;
2307
2310 if (Inst.Offset / 4 >= 0x3f4)
2311 return false;
2312 if (Step == 6) {
2313 if (Homing && FloatRegs < 0 && IntRegs < 0 && StackAdjust == 0 &&
2314 PF == 0 && Inst.Offset == 16) {
2315 GotHomingRestore = true;
2316 Step = 10;
2317 } else {
2318 if (StackAdjust > 0) {
2319 // Got stack adjust in prologue too; must match.
2320 if (StackAdjust != Inst.Offset / 4)
2321 return false;
2322 GotStackAdjust = true;
2323 } else if (PF == Inst.Offset / 4) {
2324 // Folded prologue, non-folded epilogue
2325 StackAdjust = Inst.Offset / 4;
2326 GotStackAdjust = true;
2327 } else {
2328 // StackAdjust == 0 in prologue, mismatch
2329 return false;
2330 }
2331 Step = 7;
2332 }
2333 } else if (Step == 7 || Step == 8 || Step == 9) {
2334 if (!Homing || Inst.Offset != 16)
2335 return false;
2336 GotHomingRestore = true;
2337 Step = 10;
2338 } else
2339 return false;
2340 break;
2341
2343 if (Step != 6 && Step != 7)
2344 return false;
2345 assert(Inst.Register >= 8 && Inst.Register <= 15);
2346 if (FloatRegs != (int)(Inst.Register - 8))
2347 return false;
2348 GotFloatRegs = true;
2349 Step = 8;
2350 break;
2351
2354 // push {r4-r11,lr}
2355 if (Step != 6 && Step != 7 && Step != 8)
2356 return false;
2357 assert(Inst.Register >= 4 && Inst.Register <= 11); // r4-rX
2358 assert(Inst.Offset <= 1); // Lr
2359 if (Homing && HasLR) {
2360 // If homing and LR is backed up, we can either restore LR here
2361 // and return with Ret == 1 or 2, or return with SaveLR below
2362 if (Inst.Offset) {
2363 GotLRRestore = true;
2364 NeedsReturn = true;
2365 } else {
2366 // Expecting a separate SaveLR below
2367 }
2368 } else {
2369 if (HasLR != (Inst.Offset == 1))
2370 return false;
2371 }
2372 GotLRRestore = Inst.Offset == 1;
2373 if (IntRegs < 0) // This opcode must include r4
2374 return false;
2375 int Expected = IntRegs;
2376 if (HasChain) {
2377 // Can't express r11 here unless IntRegs describe r4-r10
2378 if (IntRegs != 6)
2379 return false;
2380 Expected++;
2381 }
2382 if (Expected != (int)(Inst.Register - 4))
2383 return false;
2384 GotIntRegs = true;
2385 Step = 9;
2386 break;
2387 }
2388
2391 if (Step != 6 && Step != 7 && Step != 8)
2392 return false;
2393 // push {r4-r9,r11,lr}
2394 // push {r11,lr}
2395 // push {r1-r5}
2396 bool CurHasLR = false, CurHasR11 = false;
2397 int Regs;
2398 if (!parseRegMask(Inst.Register, CurHasLR, CurHasR11, EF, Regs))
2399 return false;
2400 if (EF > 0) {
2401 if (EF != PF && EF != StackAdjust)
2402 return false;
2403 }
2404 if (Homing && HasLR) {
2405 // If homing and LR is backed up, we can either restore LR here
2406 // and return with Ret == 1 or 2, or return with SaveLR below
2407 if (CurHasLR) {
2408 GotLRRestore = true;
2409 NeedsReturn = true;
2410 } else {
2411 // Expecting a separate SaveLR below
2412 }
2413 } else {
2414 if (CurHasLR != HasLR)
2415 return false;
2416 GotLRRestore = CurHasLR;
2417 }
2418 int Expected = IntRegs;
2419 if (HasChain) {
2420 // If we have chaining, the mask must have included r11.
2421 if (!CurHasR11)
2422 return false;
2423 } else if (Expected == 7) {
2424 // If we don't have chaining, the mask could still include r11,
2425 // expressed as part of IntRegs Instead.
2426 Expected--;
2427 if (!CurHasR11)
2428 return false;
2429 } else {
2430 // Neither HasChain nor r11 included in IntRegs, must not have r11
2431 // here either.
2432 if (CurHasR11)
2433 return false;
2434 }
2435 if (Expected != Regs)
2436 return false;
2437 GotIntRegs = true;
2438 Step = 9;
2439 break;
2440 }
2441
2443 if (Step != 6 && Step != 7 && Step != 8 && Step != 9)
2444 return false;
2445 if (!Homing || Inst.Offset != 20 || GotLRRestore)
2446 return false;
2447 GotLRRestore = true;
2448 GotHomingRestore = true;
2449 Step = 10;
2450 break;
2451
2454 GotReturn = true;
2455 Ret = (Inst.Operation == Win64EH::UOP_EndNop) ? 1 : 2;
2456 [[fallthrough]];
2457 case Win64EH::UOP_End:
2458 if (Step != 6 && Step != 7 && Step != 8 && Step != 9 && Step != 10)
2459 return false;
2460 Step = 11;
2461 break;
2462 }
2463 }
2464
2465 if (Step != 11)
2466 return false;
2467 if (StackAdjust > 0 && !GotStackAdjust && EF == 0)
2468 return false;
2469 if (FloatRegs >= 0 && !GotFloatRegs)
2470 return false;
2471 if (IntRegs >= 0 && !GotIntRegs)
2472 return false;
2473 if (Homing && !GotHomingRestore)
2474 return false;
2475 if (HasLR && !GotLRRestore)
2476 return false;
2477 if (NeedsReturn && !GotReturn)
2478 return false;
2479 }
2480
2481 assert(PF == 0 || EF == 0 ||
2482 StackAdjust == 0); // Can't have adjust in all three
2483 if (PF > 0 || EF > 0) {
2484 StackAdjust = PF > 0 ? (PF - 1) : (EF - 1);
2485 assert(StackAdjust <= 3);
2486 StackAdjust |= 0x3f0;
2487 if (PF > 0)
2488 StackAdjust |= 1 << 2;
2489 if (EF > 0)
2490 StackAdjust |= 1 << 3;
2491 }
2492
2493 assert(FuncLength <= 0x7FF && "FuncLength should have been checked earlier");
2494 int Flag = info->Fragment ? 0x02 : 0x01;
2495 int H = Homing ? 1 : 0;
2496 int L = HasLR ? 1 : 0;
2497 int C = HasChain ? 1 : 0;
2498 assert(IntRegs < 0 || FloatRegs < 0);
2499 unsigned Reg, R;
2500 if (IntRegs >= 0) {
2501 Reg = IntRegs;
2502 assert(Reg <= 7);
2503 R = 0;
2504 } else if (FloatRegs >= 0) {
2505 Reg = FloatRegs;
2506 assert(Reg < 7);
2507 R = 1;
2508 } else {
2509 // No int or float regs stored (except possibly R11,LR)
2510 Reg = 7;
2511 R = 1;
2512 }
2513 info->PackedInfo |= Flag << 0;
2514 info->PackedInfo |= (FuncLength & 0x7FF) << 2;
2515 info->PackedInfo |= (Ret & 0x3) << 13;
2516 info->PackedInfo |= H << 15;
2517 info->PackedInfo |= Reg << 16;
2518 info->PackedInfo |= R << 19;
2519 info->PackedInfo |= L << 20;
2520 info->PackedInfo |= C << 21;
2521 assert(StackAdjust <= 0x3ff);
2522 info->PackedInfo |= StackAdjust << 22;
2523 return true;
2524}
2525
2526// Populate the .xdata section. The format of .xdata on ARM is documented at
2527// https://docs.microsoft.com/en-us/cpp/build/arm-exception-handling
2529 bool TryPacked = true) {
2530 // If this UNWIND_INFO already has a symbol, it's already been emitted.
2531 if (info->Symbol)
2532 return;
2533 // If there's no unwind info here (not even a terminating UOP_End), the
2534 // unwind info is considered bogus and skipped. If this was done in
2535 // response to an explicit .seh_handlerdata, the associated trailing
2536 // handler data is left orphaned in the xdata section.
2537 if (info->empty()) {
2538 info->EmitAttempted = true;
2539 return;
2540 }
2541 if (info->EmitAttempted) {
2542 // If we tried to emit unwind info before (due to an explicit
2543 // .seh_handlerdata directive), but skipped it (because there was no
2544 // valid information to emit at the time), and it later got valid unwind
2545 // opcodes, we can't emit it here, because the trailing handler data
2546 // was already emitted elsewhere in the xdata section.
2547 streamer.getContext().reportError(
2548 SMLoc(), "Earlier .seh_handlerdata for " + info->Function->getName() +
2549 " skipped due to no unwind info at the time "
2550 "(.seh_handlerdata too early?), but the function later "
2551 "did get unwind info that can't be emitted");
2552 return;
2553 }
2554
2555 MCContext &context = streamer.getContext();
2556 MCSymbol *Label = context.createTempSymbol();
2557
2558 streamer.emitValueToAlignment(Align(4));
2559 streamer.emitLabel(Label);
2560 info->Symbol = Label;
2561
2562 if (!info->PrologEnd)
2563 streamer.getContext().reportError(SMLoc(), "Prologue in " +
2564 info->Function->getName() +
2565 " not correctly terminated");
2566
2567 if (info->PrologEnd && !info->Fragment)
2568 checkARMInstructions(streamer, info->Instructions, info->Begin,
2569 info->PrologEnd, info->Function->getName(),
2570 "prologue");
2571 for (auto &I : info->EpilogMap) {
2572 MCSymbol *EpilogStart = I.first;
2573 auto &Epilog = I.second;
2574 checkARMInstructions(streamer, Epilog.Instructions, EpilogStart, Epilog.End,
2575 info->Function->getName(), "epilogue");
2576 if (Epilog.Instructions.empty() ||
2577 !isARMTerminator(Epilog.Instructions.back()))
2578 streamer.getContext().reportError(
2579 SMLoc(), "Epilogue in " + info->Function->getName() +
2580 " not correctly terminated");
2581 }
2582
2583 std::optional<int64_t> RawFuncLength;
2584 const MCExpr *FuncLengthExpr = nullptr;
2585 if (!info->FuncletOrFuncEnd) {
2586 report_fatal_error("FuncletOrFuncEnd not set");
2587 } else {
2588 // As the size of many thumb2 instructions isn't known until later,
2589 // we can't always rely on being able to calculate the absolute
2590 // length of the function here. If we can't calculate it, defer it
2591 // to a relocation.
2592 //
2593 // In such a case, we won't know if the function is too long so that
2594 // the unwind info would need to be split (but this isn't implemented
2595 // anyway).
2596 RawFuncLength =
2597 GetOptionalAbsDifference(streamer, info->FuncletOrFuncEnd, info->Begin);
2598 if (!RawFuncLength)
2599 FuncLengthExpr =
2600 GetSubDivExpr(streamer, info->FuncletOrFuncEnd, info->Begin, 2);
2601 }
2602 uint32_t FuncLength = 0;
2603 if (RawFuncLength)
2604 FuncLength = (uint32_t)*RawFuncLength / 2;
2605 if (FuncLength > 0x3FFFF)
2606 report_fatal_error("SEH unwind data splitting not yet implemented");
2607 uint32_t PrologCodeBytes = ARMCountOfUnwindCodes(info->Instructions);
2608 uint32_t TotalCodeBytes = PrologCodeBytes;
2609
2610 if (!info->HandlesExceptions && RawFuncLength && FuncLength <= 0x7ff &&
2611 TryPacked) {
2612 // No exception handlers; check if the prolog and epilog matches the
2613 // patterns that can be described by the packed format. If we don't
2614 // know the exact function length yet, we can't do this.
2615
2616 // info->Symbol was already set even if we didn't actually write any
2617 // unwind info there. Keep using that as indicator that this unwind
2618 // info has been generated already.
2619
2620 if (tryARMPackedUnwind(streamer, info, FuncLength))
2621 return;
2622 }
2623
2624 int PackedEpilogOffset =
2625 checkARMPackedEpilog(streamer, info, PrologCodeBytes);
2626
2627 // Process epilogs.
2629 // Epilogs processed so far.
2630 std::vector<MCSymbol *> AddedEpilogs;
2631
2632 bool CanTweakProlog = true;
2633 for (auto &I : info->EpilogMap) {
2634 MCSymbol *EpilogStart = I.first;
2635 auto &EpilogInstrs = I.second.Instructions;
2636 uint32_t CodeBytes = ARMCountOfUnwindCodes(EpilogInstrs);
2637
2638 MCSymbol *MatchingEpilog =
2639 FindMatchingEpilog(EpilogInstrs, AddedEpilogs, info);
2640 int PrologOffset;
2641 if (MatchingEpilog) {
2642 assert(EpilogInfo.contains(MatchingEpilog) &&
2643 "Duplicate epilog not found");
2644 EpilogInfo[EpilogStart] = EpilogInfo.lookup(MatchingEpilog);
2645 // Clear the unwind codes in the EpilogMap, so that they don't get output
2646 // in the logic below.
2647 EpilogInstrs.clear();
2648 } else if ((PrologOffset = getARMOffsetInProlog(
2649 info->Instructions, EpilogInstrs, CanTweakProlog)) >= 0) {
2650 if (CanTweakProlog) {
2651 // Replace the regular end opcode of the prolog with the one from the
2652 // epilog.
2653 info->Instructions.front() = EpilogInstrs.back();
2654 // Later epilogs need a strict match for the end opcode.
2655 CanTweakProlog = false;
2656 }
2657 EpilogInfo[EpilogStart] = PrologOffset;
2658 // Clear the unwind codes in the EpilogMap, so that they don't get output
2659 // in the logic below.
2660 EpilogInstrs.clear();
2661 } else {
2662 EpilogInfo[EpilogStart] = TotalCodeBytes;
2663 TotalCodeBytes += CodeBytes;
2664 AddedEpilogs.push_back(EpilogStart);
2665 }
2666 }
2667
2668 // Code Words, Epilog count, F, E, X, Vers, Function Length
2669 uint32_t row1 = 0x0;
2670 uint32_t CodeWords = TotalCodeBytes / 4;
2671 uint32_t CodeWordsMod = TotalCodeBytes % 4;
2672 if (CodeWordsMod)
2673 CodeWords++;
2674 uint32_t EpilogCount =
2675 PackedEpilogOffset >= 0 ? PackedEpilogOffset : info->EpilogMap.size();
2676 bool ExtensionWord = EpilogCount > 31 || CodeWords > 15;
2677 if (!ExtensionWord) {
2678 row1 |= (EpilogCount & 0x1F) << 23;
2679 row1 |= (CodeWords & 0x0F) << 28;
2680 }
2681 if (info->HandlesExceptions) // X
2682 row1 |= 1 << 20;
2683 if (PackedEpilogOffset >= 0) // E
2684 row1 |= 1 << 21;
2685 if (info->Fragment) // F
2686 row1 |= 1 << 22;
2687 row1 |= FuncLength & 0x3FFFF;
2688 if (RawFuncLength)
2689 streamer.emitInt32(row1);
2690 else
2691 streamer.emitValue(
2692 MCBinaryExpr::createOr(FuncLengthExpr,
2693 MCConstantExpr::create(row1, context), context),
2694 4);
2695
2696 // Extended Code Words, Extended Epilog Count
2697 if (ExtensionWord) {
2698 // FIXME: We should be able to split unwind info into multiple sections.
2699 if (CodeWords > 0xFF || EpilogCount > 0xFFFF)
2700 report_fatal_error("SEH unwind data splitting not yet implemented");
2701 uint32_t row2 = 0x0;
2702 row2 |= (CodeWords & 0xFF) << 16;
2703 row2 |= (EpilogCount & 0xFFFF);
2704 streamer.emitInt32(row2);
2705 }
2706
2707 if (PackedEpilogOffset < 0) {
2708 // Epilog Start Index, Epilog Start Offset
2709 for (auto &I : EpilogInfo) {
2710 MCSymbol *EpilogStart = I.first;
2711 uint32_t EpilogIndex = I.second;
2712
2713 std::optional<int64_t> MaybeEpilogOffset =
2714 GetOptionalAbsDifference(streamer, EpilogStart, info->Begin);
2715 const MCExpr *OffsetExpr = nullptr;
2716 uint32_t EpilogOffset = 0;
2717 if (MaybeEpilogOffset)
2718 EpilogOffset = *MaybeEpilogOffset / 2;
2719 else
2720 OffsetExpr = GetSubDivExpr(streamer, EpilogStart, info->Begin, 2);
2721
2722 assert(info->EpilogMap.contains(EpilogStart));
2723 unsigned Condition = info->EpilogMap[EpilogStart].Condition;
2724 assert(Condition <= 0xf);
2725
2726 uint32_t row3 = EpilogOffset;
2727 row3 |= Condition << 20;
2728 row3 |= (EpilogIndex & 0x3FF) << 24;
2729 if (MaybeEpilogOffset)
2730 streamer.emitInt32(row3);
2731 else
2732 streamer.emitValue(
2734 OffsetExpr, MCConstantExpr::create(row3, context), context),
2735 4);
2736 }
2737 }
2738
2739 // Emit prolog unwind instructions (in reverse order).
2740 uint8_t numInst = info->Instructions.size();
2741 for (uint8_t c = 0; c < numInst; ++c) {
2742 WinEH::Instruction inst = info->Instructions.back();
2743 info->Instructions.pop_back();
2744 ARMEmitUnwindCode(streamer, inst);
2745 }
2746
2747 // Emit epilog unwind instructions
2748 for (auto &I : info->EpilogMap) {
2749 auto &EpilogInstrs = I.second.Instructions;
2750 for (const WinEH::Instruction &inst : EpilogInstrs)
2751 ARMEmitUnwindCode(streamer, inst);
2752 }
2753
2754 int32_t BytesMod = CodeWords * 4 - TotalCodeBytes;
2755 assert(BytesMod >= 0);
2756 for (int i = 0; i < BytesMod; i++)
2757 streamer.emitInt8(0xFB);
2758
2759 if (info->HandlesExceptions)
2760 streamer.emitValue(
2761 MCSymbolRefExpr::create(info->ExceptionHandler,
2763 4);
2764}
2765
2767 const WinEH::FrameInfo *info) {
2768 MCContext &context = streamer.getContext();
2769
2770 streamer.emitValueToAlignment(Align(4));
2771 for (const auto &S : info->Segments) {
2772 EmitSymbolRefWithOfs(streamer, info->Begin, S.Offset);
2773 if (info->PackedInfo)
2774 streamer.emitInt32(info->PackedInfo);
2775 else
2776 streamer.emitValue(
2778 context),
2779 4);
2780 }
2781}
2782
2783
2785 const WinEH::FrameInfo *info) {
2786 MCContext &context = streamer.getContext();
2787
2788 streamer.emitValueToAlignment(Align(4));
2789 EmitSymbolRefWithOfs(streamer, info->Begin, info->Begin);
2790 if (info->PackedInfo)
2791 streamer.emitInt32(info->PackedInfo);
2792 else
2793 streamer.emitValue(
2795 context),
2796 4);
2797}
2798
2800 // Emit the unwind info structs first.
2801 for (const auto &CFI : Streamer.getWinFrameInfos()) {
2802 WinEH::FrameInfo *Info = CFI.get();
2803 if (Info->empty())
2804 continue;
2805 MCSection *XData = Streamer.getAssociatedXDataSection(CFI->TextSection);
2806 Streamer.switchSection(XData);
2807 ARM64EmitUnwindInfo(Streamer, Info);
2808 }
2809
2810 // Now emit RUNTIME_FUNCTION entries.
2811 for (const auto &CFI : Streamer.getWinFrameInfos()) {
2812 WinEH::FrameInfo *Info = CFI.get();
2813 // ARM64EmitUnwindInfo above clears the info struct, so we can't check
2814 // empty here. But if a Symbol is set, we should create the corresponding
2815 // pdata entry.
2816 if (!Info->Symbol)
2817 continue;
2818 MCSection *PData = Streamer.getAssociatedPDataSection(CFI->TextSection);
2819 Streamer.switchSection(PData);
2820 ARM64EmitRuntimeFunction(Streamer, Info);
2821 }
2822}
2823
2826 bool HandlerData) const {
2827 // Called if there's an .seh_handlerdata directive before the end of the
2828 // function. This forces writing the xdata record already here - and
2829 // in this case, the function isn't actually ended already, but the xdata
2830 // record needs to know the function length. In these cases, if the funclet
2831 // end hasn't been marked yet, the xdata function length won't cover the
2832 // whole function, only up to this point.
2833 if (!info->FuncletOrFuncEnd) {
2834 Streamer.switchSection(info->TextSection);
2835 info->FuncletOrFuncEnd = Streamer.emitCFILabel();
2836 }
2837 // Switch sections (the static function above is meant to be called from
2838 // here and from Emit().
2839 MCSection *XData = Streamer.getAssociatedXDataSection(info->TextSection);
2840 Streamer.switchSection(XData);
2841 ARM64EmitUnwindInfo(Streamer, info, /* TryPacked = */ !HandlerData);
2842}
2843
2845 // Emit the unwind info structs first.
2846 for (const auto &CFI : Streamer.getWinFrameInfos()) {
2847 WinEH::FrameInfo *Info = CFI.get();
2848 if (Info->empty())
2849 continue;
2850 MCSection *XData = Streamer.getAssociatedXDataSection(CFI->TextSection);
2851 Streamer.switchSection(XData);
2852 ARMEmitUnwindInfo(Streamer, Info);
2853 }
2854
2855 // Now emit RUNTIME_FUNCTION entries.
2856 for (const auto &CFI : Streamer.getWinFrameInfos()) {
2857 WinEH::FrameInfo *Info = CFI.get();
2858 // ARMEmitUnwindInfo above clears the info struct, so we can't check
2859 // empty here. But if a Symbol is set, we should create the corresponding
2860 // pdata entry.
2861 if (!Info->Symbol)
2862 continue;
2863 MCSection *PData = Streamer.getAssociatedPDataSection(CFI->TextSection);
2864 Streamer.switchSection(PData);
2865 ARMEmitRuntimeFunction(Streamer, Info);
2866 }
2867}
2868
2871 bool HandlerData) const {
2872 // Called if there's an .seh_handlerdata directive before the end of the
2873 // function. This forces writing the xdata record already here - and
2874 // in this case, the function isn't actually ended already, but the xdata
2875 // record needs to know the function length. In these cases, if the funclet
2876 // end hasn't been marked yet, the xdata function length won't cover the
2877 // whole function, only up to this point.
2878 if (!info->FuncletOrFuncEnd) {
2879 Streamer.switchSection(info->TextSection);
2880 info->FuncletOrFuncEnd = Streamer.emitCFILabel();
2881 }
2882 // Switch sections (the static function above is meant to be called from
2883 // here and from Emit().
2884 MCSection *XData = Streamer.getAssociatedXDataSection(info->TextSection);
2885 Streamer.switchSection(XData);
2886 ARMEmitUnwindInfo(Streamer, info, /* TryPacked = */ !HandlerData);
2887}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
lazy value info
static int checkARM64PackedEpilog(MCStreamer &streamer, WinEH::FrameInfo *info, WinEH::FrameInfo::Segment *Seg, int PrologCodeBytes)
static void ARM64EmitUnwindInfoForSegment(MCStreamer &streamer, WinEH::FrameInfo *info, WinEH::FrameInfo::Segment &Seg, bool TryPacked=true)
static uint32_t ARMCountOfUnwindCodes(ArrayRef< WinEH::Instruction > Insns)
static uint32_t ARM64CountOfUnwindCodes(ArrayRef< WinEH::Instruction > Insns)
static void checkARMInstructions(MCStreamer &Streamer, ArrayRef< WinEH::Instruction > Insns, const MCSymbol *Begin, const MCSymbol *End, StringRef Name, StringRef Type)
static bool isARMTerminator(const WinEH::Instruction &inst)
static void ARM64EmitUnwindCode(MCStreamer &streamer, const WinEH::Instruction &inst)
static void simplifyARM64Opcodes(std::vector< WinEH::Instruction > &Instructions, bool Reverse)
static void ARMEmitUnwindCode(MCStreamer &streamer, const WinEH::Instruction &inst)
static std::optional< int64_t > GetOptionalAbsDifference(const MCAssembler &Assembler, const MCSymbol *LHS, const MCSymbol *RHS)
static int getARM64OffsetInProlog(const std::vector< WinEH::Instruction > &Prolog, const std::vector< WinEH::Instruction > &Epilog)
static void ARMEmitRuntimeFunction(MCStreamer &streamer, const WinEH::FrameInfo *info)
static bool tryARM64PackedUnwind(WinEH::FrameInfo *info, uint32_t FuncLength, int PackedEpilogOffset)
static void EmitUnwindInfo(MCStreamer &streamer, WinEH::FrameInfo *info)
static void EmitUnwindCode(MCStreamer &streamer, const MCSymbol *begin, WinEH::Instruction &inst)
static void ARM64EmitUnwindInfo(MCStreamer &streamer, WinEH::FrameInfo *info, bool TryPacked=true)
static int getARMOffsetInProlog(const std::vector< WinEH::Instruction > &Prolog, const std::vector< WinEH::Instruction > &Epilog, bool CanTweakProlog)
static void ARM64EmitRuntimeFunction(MCStreamer &streamer, const WinEH::FrameInfo *info)
static void EmitSymbolRefWithOfs(MCStreamer &streamer, const MCSymbol *Base, int64_t Offset)
static bool parseRegMask(unsigned Mask, bool &HasLR, bool &HasR11, unsigned &Folded, int &IntRegs)
static int checkARMPackedEpilog(MCStreamer &streamer, WinEH::FrameInfo *info, int PrologCodeBytes)
static int64_t GetAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS, const MCSymbol *RHS)
static void ARM64FindSegmentsInFunction(MCStreamer &streamer, WinEH::FrameInfo *info, int64_t RawFuncLength)
static bool tryARMPackedUnwind(MCStreamer &streamer, WinEH::FrameInfo *info, uint32_t FuncLength)
static MCSymbol * FindMatchingEpilog(const std::vector< WinEH::Instruction > &EpilogInstrs, const std::vector< MCSymbol * > &Epilogs, const WinEH::FrameInfo *info)
static void EmitRuntimeFunction(MCStreamer &streamer, const WinEH::FrameInfo *info)
static void checkARM64Instructions(MCStreamer &Streamer, ArrayRef< WinEH::Instruction > Insns, const MCSymbol *Begin, const MCSymbol *End, StringRef Name, StringRef Type)
static const MCExpr * GetSubDivExpr(MCStreamer &Streamer, const MCSymbol *LHS, const MCSymbol *RHS, int Div)
static void EmitAbsDifference(MCStreamer &Streamer, const MCSymbol *LHS, const MCSymbol *RHS)
static void ARMEmitUnwindInfo(MCStreamer &streamer, WinEH::FrameInfo *info, bool TryPacked=true)
static uint32_t ARMCountOfInstructionBytes(ArrayRef< WinEH::Instruction > Insns, bool *HasCustom=nullptr)
static void ARM64ProcessEpilogs(WinEH::FrameInfo *info, WinEH::FrameInfo::Segment *Seg, uint32_t &TotalCodeBytes, MapVector< MCSymbol *, uint32_t > &EpilogInfo)
static uint8_t CountOfUnwindCodes(std::vector< WinEH::Instruction > &Insns)
Definition MCWin64EH.cpp:72
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
Register Reg
static void printImpl(const MCAsmInfo &MAI, raw_ostream &OS, const MCSpecifierExpr &Expr)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static const MCPhysReg IntRegs[32]
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
Tagged union holding either a T or a Error.
Definition Error.h:485
MCContext & getContext() const
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:343
static const MCBinaryExpr * createOr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:408
static const MCBinaryExpr * createDiv(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:353
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:428
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Context object for machine code objects.
Definition MCContext.h:83
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
LLVM_ABI void reportError(SMLoc L, const Twine &Msg)
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
Streaming object file generation interface.
MCAssembler & getAssembler()
void appendContents(ArrayRef< char > Contents)
void addFixup(const MCExpr *Value, MCFixupKind Kind)
void ensureHeadroom(size_t Headroom)
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:516
Streaming machine code generation interface.
Definition MCStreamer.h:221
virtual MCSymbol * emitCFILabel()
When emitting an object file, create and emit a real label.
MCSection * getAssociatedPDataSection(const MCSection *TextSec)
Get the .pdata section used for the given section.
MCContext & getContext() const
Definition MCStreamer.h:322
MCSection * getAssociatedXDataSection(const MCSection *TextSec)
Get the .xdata section used for the given section.
void emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc=SMLoc())
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
virtual void emitValueToAlignment(Align Alignment, int64_t Fill=0, uint8_t FillLen=1, unsigned MaxBytesToEmit=0)
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
void emitInt16(uint64_t Value)
Definition MCStreamer.h:755
virtual void switchSection(MCSection *Section, uint32_t Subsec=0)
Set the current section where code is being emitted to Section.
void emitInt32(uint64_t Value)
Definition MCStreamer.h:756
ArrayRef< std::unique_ptr< WinEH::FrameInfo > > getWinFrameInfos() const
Definition MCStreamer.h:355
void emitInt8(uint64_t Value)
Definition MCStreamer.h:754
Represent a reference to a symbol from inside an expression.
Definition MCExpr.h:190
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:214
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
LLVM_ABI void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition MCSymbol.cpp:59
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
MCFragment * getFragment() const
Definition MCSymbol.h:345
static MCValue get(const MCSymbol *SymA, const MCSymbol *SymB=nullptr, int64_t Val=0, uint32_t Specifier=0)
Definition MCValue.h:56
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
Represents a location in source code.
Definition SMLoc.h:22
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:30
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
void EmitUnwindInfo(MCStreamer &Streamer, WinEH::FrameInfo *FI, bool HandlerData) const override
void Emit(MCStreamer &Streamer) const override
This emits the unwind info sections (.pdata and .xdata in PE/COFF).
void Emit(MCStreamer &Streamer) const override
This emits the unwind info sections (.pdata and .xdata in PE/COFF).
void EmitUnwindInfo(MCStreamer &Streamer, WinEH::FrameInfo *FI, bool HandlerData) const override
void Emit(MCStreamer &Streamer) const override
This emits the unwind info sections (.pdata and .xdata in PE/COFF).
void EmitUnwindInfo(MCStreamer &Streamer, WinEH::FrameInfo *FI, bool HandlerData) const override
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ UNW_TerminateHandler
UNW_TerminateHandler - Specifies that this function has a termination handler.
Definition Win64EH.h:143
@ UNW_ExceptionHandler
UNW_ExceptionHandler - Specifies that this function has an exception handler.
Definition Win64EH.h:140
@ UNW_ChainInfo
UNW_ChainInfo - Specifies that this UnwindInfo structure is chained to another one.
Definition Win64EH.h:146
UnwindOpcodes
UnwindOpcodes - Enumeration whose values specify a single operation in the prolog of a function.
Definition Win64EH.h:26
@ UOP_SaveAnyRegDPX
Definition Win64EH.h:75
@ UOP_SaveRegsR4R7LR
Definition Win64EH.h:98
@ UOP_ClearUnwoundToCall
Definition Win64EH.h:64
@ UOP_SaveNonVolBig
Definition Win64EH.h:35
@ UOP_WideAllocMedium
Definition Win64EH.h:92
@ UOP_SaveAnyRegDX
Definition Win64EH.h:74
@ UOP_SaveFRegD0D15
Definition Win64EH.h:103
@ UOP_SaveAnyRegQP
Definition Win64EH.h:71
@ UOP_SaveAnyRegD
Definition Win64EH.h:68
@ UOP_WideSaveRegsR4R11LR
Definition Win64EH.h:99
@ UOP_SaveAnyRegIPX
Definition Win64EH.h:73
@ UOP_WideAllocHuge
Definition Win64EH.h:94
@ UOP_SaveAnyRegQX
Definition Win64EH.h:76
@ UOP_SaveAnyRegIX
Definition Win64EH.h:72
@ UOP_SaveXMM128Big
Definition Win64EH.h:39
@ UOP_SaveAnyRegQ
Definition Win64EH.h:70
@ UOP_SaveAnyRegDP
Definition Win64EH.h:69
@ UOP_SaveFRegD8D15
Definition Win64EH.h:100
@ UOP_PushMachFrame
Definition Win64EH.h:40
@ UOP_SaveR19R20X
Definition Win64EH.h:44
@ UOP_SaveAnyRegQPX
Definition Win64EH.h:77
@ UOP_WideAllocLarge
Definition Win64EH.h:93
@ UOP_WideSaveRegMask
Definition Win64EH.h:96
@ UOP_AllocMedium
Definition Win64EH.h:43
@ UOP_SaveAnyRegIP
Definition Win64EH.h:67
@ UOP_SaveFRegD16D31
Definition Win64EH.h:104
@ UOP_SaveAnyRegI
Definition Win64EH.h:66
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:532
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
auto reverse_conditionally(ContainerTy &&C, bool ShouldReverse)
Return a range that conditionally reverses C.
Definition STLExtras.h:1423
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ FK_Data_2
A two-byte fixup.
Definition MCFixup.h:35
DWARFExpression::Operation Op
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
MapVector< MCSymbol *, int64_t > Epilogs
Definition MCWinEH.h:81
const MCSymbol * Function
Definition MCWinEH.h:46
const MCSymbol * End
Definition MCWinEH.h:43
const MCSymbol * Label
Definition MCWinEH.h:24