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