ArchHandler_arm.cpp 54.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
//===- lib/FileFormat/MachO/ArchHandler_arm.cpp ---------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "ArchHandler.h"
#include "Atoms.h"
#include "MachONormalizedFileBinaryUtils.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"

using namespace llvm::MachO;
using namespace lld::mach_o::normalized;

namespace lld {
namespace mach_o {

using llvm::support::ulittle32_t;
using llvm::support::little32_t;


class ArchHandler_arm : public ArchHandler {
public:
  ArchHandler_arm() = default;
  ~ArchHandler_arm() override = default;

  const Registry::KindStrings *kindStrings() override { return _sKindStrings; }

  Reference::KindArch kindArch() override { return Reference::KindArch::ARM; }

  const ArchHandler::StubInfo &stubInfo() override;
  bool isCallSite(const Reference &) override;
  bool isPointer(const Reference &) override;
  bool isPairedReloc(const normalized::Relocation &) override;
  bool isNonCallBranch(const Reference &) override;

  bool needsCompactUnwind() override {
    return false;
  }
  Reference::KindValue imageOffsetKind() override {
    return invalid;
  }
  Reference::KindValue imageOffsetKindIndirect() override {
    return invalid;
  }

  Reference::KindValue unwindRefToPersonalityFunctionKind() override {
    return invalid;
  }

  Reference::KindValue unwindRefToCIEKind() override {
    return invalid;
  }

  Reference::KindValue unwindRefToFunctionKind() override {
    return invalid;
  }

  Reference::KindValue unwindRefToEhFrameKind() override {
    return invalid;
  }

  Reference::KindValue lazyImmediateLocationKind() override {
    return lazyImmediateLocation;
  }

  Reference::KindValue pointerKind() override {
    return invalid;
  }

  uint32_t dwarfCompactUnwindType() override {
    // FIXME
    return -1;
  }

  llvm::Error getReferenceInfo(const normalized::Relocation &reloc,
                               const DefinedAtom *inAtom,
                               uint32_t offsetInAtom,
                               uint64_t fixupAddress, bool swap,
                               FindAtomBySectionAndAddress atomFromAddress,
                               FindAtomBySymbolIndex atomFromSymbolIndex,
                               Reference::KindValue *kind,
                               const lld::Atom **target,
                               Reference::Addend *addend) override;
  llvm::Error
      getPairReferenceInfo(const normalized::Relocation &reloc1,
                           const normalized::Relocation &reloc2,
                           const DefinedAtom *inAtom,
                           uint32_t offsetInAtom,
                           uint64_t fixupAddress, bool swap, bool scatterable,
                           FindAtomBySectionAndAddress atomFromAddress,
                           FindAtomBySymbolIndex atomFromSymbolIndex,
                           Reference::KindValue *kind,
                           const lld::Atom **target,
                           Reference::Addend *addend) override;

  void generateAtomContent(const DefinedAtom &atom, bool relocatable,
                           FindAddressForAtom findAddress,
                           FindAddressForAtom findSectionAddress,
                           uint64_t imageBaseAddress,
                           llvm::MutableArrayRef<uint8_t> atomContentBuffer) override;

  void appendSectionRelocations(const DefinedAtom &atom,
                                uint64_t atomSectionOffset,
                                const Reference &ref,
                                FindSymbolIndexForAtom,
                                FindSectionIndexForAtom,
                                FindAddressForAtom,
                                normalized::Relocations &) override;

  void addAdditionalReferences(MachODefinedAtom &atom) override;

  bool isDataInCodeTransition(Reference::KindValue refKind) override {
    switch (refKind) {
    case modeThumbCode:
    case modeArmCode:
    case modeData:
      return true;
    default:
      return false;
      break;
    }
  }

  Reference::KindValue dataInCodeTransitionStart(
                                        const MachODefinedAtom &atom) override {
    return modeData;
  }

  Reference::KindValue dataInCodeTransitionEnd(
                                        const MachODefinedAtom &atom) override {
    return atom.isThumb() ? modeThumbCode : modeArmCode;
  }

  bool isThumbFunction(const DefinedAtom &atom) override;
  const DefinedAtom *createShim(MachOFile &file, bool thumbToArm,
                                const DefinedAtom &) override;

private:
  friend class Thumb2ToArmShimAtom;
  friend class ArmToThumbShimAtom;

  static const Registry::KindStrings _sKindStrings[];
  static const StubInfo              _sStubInfoArmPIC;

  enum ArmKind : Reference::KindValue {
    invalid,               /// for error condition

    modeThumbCode,         /// Content starting at this offset is thumb.
    modeArmCode,           /// Content starting at this offset is arm.
    modeData,              /// Content starting at this offset is data.

    // Kinds found in mach-o .o files:
    thumb_bl22,            /// ex: bl _foo
    thumb_b22,             /// ex: b _foo
    thumb_movw,            /// ex: movw	r1, :lower16:_foo
    thumb_movt,            /// ex: movt	r1, :lower16:_foo
    thumb_movw_funcRel,    /// ex: movw	r1, :lower16:(_foo-(L1+4))
    thumb_movt_funcRel,    /// ex: movt r1, :upper16:(_foo-(L1+4))
    arm_bl24,              /// ex: bl _foo
    arm_b24,               /// ex: b _foo
    arm_movw,              /// ex: movw	r1, :lower16:_foo
    arm_movt,              /// ex: movt	r1, :lower16:_foo
    arm_movw_funcRel,      /// ex: movw	r1, :lower16:(_foo-(L1+4))
    arm_movt_funcRel,      /// ex: movt r1, :upper16:(_foo-(L1+4))
    pointer32,             /// ex: .long _foo
    delta32,               /// ex: .long _foo - .

    // Kinds introduced by Passes:
    lazyPointer,           /// Location contains a lazy pointer.
    lazyImmediateLocation, /// Location contains immediate value used in stub.
  };

  // Utility functions for inspecting/updating instructions.
  static bool isThumbMovw(uint32_t instruction);
  static bool isThumbMovt(uint32_t instruction);
  static bool isArmMovw(uint32_t instruction);
  static bool isArmMovt(uint32_t instruction);
  static int32_t getDisplacementFromThumbBranch(uint32_t instruction, uint32_t);
  static int32_t getDisplacementFromArmBranch(uint32_t instruction);
  static uint16_t getWordFromThumbMov(uint32_t instruction);
  static uint16_t getWordFromArmMov(uint32_t instruction);
  static uint32_t clearThumbBit(uint32_t value, const Atom *target);
  static uint32_t setDisplacementInArmBranch(uint32_t instr, int32_t disp,
                                             bool targetIsThumb);
  static uint32_t setDisplacementInThumbBranch(uint32_t instr, uint32_t ia,
                                               int32_t disp, bool targetThumb);
  static uint32_t setWordFromThumbMov(uint32_t instruction, uint16_t word);
  static uint32_t setWordFromArmMov(uint32_t instruction, uint16_t word);

  StringRef stubName(const DefinedAtom &);
  bool useExternalRelocationTo(const Atom &target);

  void applyFixupFinal(const Reference &ref, uint8_t *location,
                       uint64_t fixupAddress, uint64_t targetAddress,
                       uint64_t inAtomAddress, bool &thumbMode,
                       bool targetIsThumb);

  void applyFixupRelocatable(const Reference &ref, uint8_t *location,
                             uint64_t fixupAddress,
                             uint64_t targetAddress,
                             uint64_t inAtomAddress, bool &thumbMode,
                             bool targetIsThumb);
};

//===----------------------------------------------------------------------===//
//  ArchHandler_arm
//===----------------------------------------------------------------------===//

const Registry::KindStrings ArchHandler_arm::_sKindStrings[] = {
  LLD_KIND_STRING_ENTRY(invalid),
  LLD_KIND_STRING_ENTRY(modeThumbCode),
  LLD_KIND_STRING_ENTRY(modeArmCode),
  LLD_KIND_STRING_ENTRY(modeData),
  LLD_KIND_STRING_ENTRY(thumb_bl22),
  LLD_KIND_STRING_ENTRY(thumb_b22),
  LLD_KIND_STRING_ENTRY(thumb_movw),
  LLD_KIND_STRING_ENTRY(thumb_movt),
  LLD_KIND_STRING_ENTRY(thumb_movw_funcRel),
  LLD_KIND_STRING_ENTRY(thumb_movt_funcRel),
  LLD_KIND_STRING_ENTRY(arm_bl24),
  LLD_KIND_STRING_ENTRY(arm_b24),
  LLD_KIND_STRING_ENTRY(arm_movw),
  LLD_KIND_STRING_ENTRY(arm_movt),
  LLD_KIND_STRING_ENTRY(arm_movw_funcRel),
  LLD_KIND_STRING_ENTRY(arm_movt_funcRel),
  LLD_KIND_STRING_ENTRY(pointer32),
  LLD_KIND_STRING_ENTRY(delta32),
  LLD_KIND_STRING_ENTRY(lazyPointer),
  LLD_KIND_STRING_ENTRY(lazyImmediateLocation),
  LLD_KIND_STRING_END
};

const ArchHandler::StubInfo ArchHandler_arm::_sStubInfoArmPIC = {
  "dyld_stub_binder",

  // References in lazy pointer
  { Reference::KindArch::ARM, pointer32, 0, 0 },
  { Reference::KindArch::ARM, lazyPointer, 0, 0 },

  // GOT pointer to dyld_stub_binder
  { Reference::KindArch::ARM, pointer32, 0, 0 },

  // arm code alignment 2^2
  2,

  // Stub size and code
  16,
  { 0x04, 0xC0, 0x9F, 0xE5,       // 	ldr ip, pc + 12
    0x0C, 0xC0, 0x8F, 0xE0,       //  add ip, pc, ip
    0x00, 0xF0, 0x9C, 0xE5,       // 	ldr pc, [ip]
    0x00, 0x00, 0x00, 0x00 },     // 	.long L_foo$lazy_ptr - (L1$scv + 8)
  { Reference::KindArch::ARM, delta32, 12, 0 },
  { false, 0, 0, 0 },

  // Stub Helper size and code
  12,
  { 0x00, 0xC0, 0x9F, 0xE5,       // ldr   ip, [pc, #0]
    0x00, 0x00, 0x00, 0xEA,       // b	     _helperhelper
    0x00, 0x00, 0x00, 0x00 },     // .long  lazy-info-offset
  { Reference::KindArch::ARM, lazyImmediateLocation, 8, 0 },
  { Reference::KindArch::ARM, arm_b24, 4, 0 },

  // Stub helper image cache content type
  DefinedAtom::typeGOT,

  // Stub Helper-Common size and code
  36,
  // Stub helper alignment
  2,
	{ // push lazy-info-offset
    0x04, 0xC0, 0x2D, 0xE5,       // str ip, [sp, #-4]!
		// push address of dyld_mageLoaderCache
    0x10, 0xC0, 0x9F, 0xE5,       // ldr	ip, L1
    0x0C, 0xC0, 0x8F, 0xE0,       // add	ip, pc, ip
    0x04, 0xC0, 0x2D, 0xE5,       // str ip, [sp, #-4]!
		// jump through dyld_stub_binder
    0x08, 0xC0, 0x9F, 0xE5,       // ldr	ip, L2
    0x0C, 0xC0, 0x8F, 0xE0,       // add	ip, pc, ip
    0x00, 0xF0, 0x9C, 0xE5,       // ldr	pc, [ip]
    0x00, 0x00, 0x00, 0x00,       // L1: .long fFastStubGOTAtom - (helper+16)
    0x00, 0x00, 0x00, 0x00 },     // L2: .long dyld_stub_binder - (helper+28)
  { Reference::KindArch::ARM, delta32, 28, 0xC },
  { false, 0, 0, 0 },
  { Reference::KindArch::ARM, delta32, 32, 0x04 },
  { false, 0, 0, 0 }
};

const ArchHandler::StubInfo &ArchHandler_arm::stubInfo() {
  // If multiple kinds of stubs are supported, select which StubInfo here.
  return _sStubInfoArmPIC;
}

bool ArchHandler_arm::isCallSite(const Reference &ref) {
  switch (ref.kindValue()) {
  case thumb_b22:
  case thumb_bl22:
  case arm_b24:
  case arm_bl24:
    return true;
  default:
    return false;
  }
}

bool ArchHandler_arm::isPointer(const Reference &ref) {
  return (ref.kindValue() == pointer32);
}

bool ArchHandler_arm::isNonCallBranch(const Reference &ref) {
  switch (ref.kindValue()) {
  case thumb_b22:
  case arm_b24:
    return true;
  default:
    return false;
  }
}

bool ArchHandler_arm::isPairedReloc(const Relocation &reloc) {
  switch (reloc.type) {
  case ARM_RELOC_SECTDIFF:
  case ARM_RELOC_LOCAL_SECTDIFF:
  case ARM_RELOC_HALF_SECTDIFF:
  case ARM_RELOC_HALF:
    return true;
  default:
    return false;
  }
}

/// Trace references from stub atom to lazy pointer to target and get its name.
StringRef ArchHandler_arm::stubName(const DefinedAtom &stubAtom) {
  assert(stubAtom.contentType() == DefinedAtom::typeStub);
  for (const Reference *ref : stubAtom) {
    if (const DefinedAtom* lp = dyn_cast<DefinedAtom>(ref->target())) {
      if (lp->contentType() != DefinedAtom::typeLazyPointer)
        continue;
      for (const Reference *ref2 : *lp) {
        if (ref2->kindValue() != lazyPointer)
          continue;
        return ref2->target()->name();
      }
    }
  }
  return "stub";
}

/// Extract displacement from an ARM b/bl/blx instruction.
int32_t ArchHandler_arm::getDisplacementFromArmBranch(uint32_t instruction) {
  // Sign-extend imm24
  int32_t displacement = (instruction & 0x00FFFFFF) << 2;
  if ((displacement & 0x02000000) != 0)
    displacement |= 0xFC000000;
  // If this is BLX and H bit set, add 2.
  if ((instruction & 0xFF000000) == 0xFB000000)
    displacement += 2;
  return displacement;
}

/// Update an ARM b/bl/blx instruction, switching bl <-> blx as needed.
uint32_t ArchHandler_arm::setDisplacementInArmBranch(uint32_t instruction,
                                                     int32_t displacement,
                                                     bool targetIsThumb) {
  assert((displacement <= 33554428) && (displacement > (-33554432))
                                              && "arm branch out of range");
  bool is_blx = ((instruction & 0xF0000000) == 0xF0000000);
  uint32_t newInstruction = (instruction & 0xFF000000);
  uint32_t h = 0;
  if (targetIsThumb) {
    // Force use of BLX.
    newInstruction = 0xFA000000;
    if (!is_blx) {
      assert(((instruction & 0xF0000000) == 0xE0000000)
                                                   && "no conditional arm blx");
      assert(((instruction & 0xFF000000) == 0xEB000000)
                                             && "no arm pc-rel BX instruction");
    }
    if (displacement & 2)
      h = 1;
  }
  else {
    // Force use of B/BL.
    if (is_blx)
      newInstruction = 0xEB000000;
  }
  newInstruction |= (h << 24) | ((displacement >> 2) & 0x00FFFFFF);
  return newInstruction;
}

/// Extract displacement from a thumb b/bl/blx instruction.
int32_t ArchHandler_arm::getDisplacementFromThumbBranch(uint32_t instruction,
                                                        uint32_t instrAddr) {
  bool is_blx = ((instruction & 0xD000F800) == 0xC000F000);
  uint32_t s = (instruction >> 10) & 0x1;
  uint32_t j1 = (instruction >> 29) & 0x1;
  uint32_t j2 = (instruction >> 27) & 0x1;
  uint32_t imm10 = instruction & 0x3FF;
  uint32_t imm11 = (instruction >> 16) & 0x7FF;
  uint32_t i1 = (j1 == s);
  uint32_t i2 = (j2 == s);
  uint32_t dis =
      (s << 24) | (i1 << 23) | (i2 << 22) | (imm10 << 12) | (imm11 << 1);
  int32_t sdis = dis;
  int32_t result = s ? (sdis | 0xFE000000) : sdis;
  if (is_blx && (instrAddr & 0x2)) {
    // The thumb blx instruction always has low bit of imm11 as zero.  The way
    // a 2-byte aligned blx can branch to a 4-byte aligned ARM target is that
    // the blx instruction always 4-byte aligns the pc before adding the
    // displacement from the blx.  We must emulate that when decoding this.
    result -= 2;
  }
  return result;
}

/// Update a thumb b/bl/blx instruction, switching bl <-> blx as needed.
uint32_t ArchHandler_arm::setDisplacementInThumbBranch(uint32_t instruction,
                                                       uint32_t instrAddr,
                                                       int32_t displacement,
                                                       bool targetIsThumb) {
  assert((displacement <= 16777214) && (displacement > (-16777216))
                                              && "thumb branch out of range");
	bool is_bl = ((instruction & 0xD000F800) == 0xD000F000);
	bool is_blx = ((instruction & 0xD000F800) == 0xC000F000);
	bool is_b = ((instruction & 0xD000F800) == 0x9000F000);
  uint32_t newInstruction = (instruction & 0xD000F800);
  if (is_bl || is_blx) {
    if (targetIsThumb) {
      newInstruction = 0xD000F000; // Use bl
    } else {
      newInstruction = 0xC000F000; // Use blx
      // See note in getDisplacementFromThumbBranch() about blx.
      if (instrAddr & 0x2)
        displacement += 2;
    }
  } else if (is_b) {
    assert(targetIsThumb && "no pc-rel thumb branch instruction that "
                             "switches to arm mode");
  }
  else {
    llvm_unreachable("thumb branch22 reloc on a non-branch instruction");
  }
  uint32_t s = (uint32_t)(displacement >> 24) & 0x1;
  uint32_t i1 = (uint32_t)(displacement >> 23) & 0x1;
  uint32_t i2 = (uint32_t)(displacement >> 22) & 0x1;
  uint32_t imm10 = (uint32_t)(displacement >> 12) & 0x3FF;
  uint32_t imm11 = (uint32_t)(displacement >> 1) & 0x7FF;
  uint32_t j1 = (i1 == s);
  uint32_t j2 = (i2 == s);
  uint32_t nextDisp = (j1 << 13) | (j2 << 11) | imm11;
  uint32_t firstDisp = (s << 10) | imm10;
  newInstruction |= (nextDisp << 16) | firstDisp;
  return newInstruction;
}

bool ArchHandler_arm::isThumbMovw(uint32_t instruction) {
  return (instruction & 0x8000FBF0) == 0x0000F240;
}

bool ArchHandler_arm::isThumbMovt(uint32_t instruction) {
  return (instruction & 0x8000FBF0) == 0x0000F2C0;
}

bool ArchHandler_arm::isArmMovw(uint32_t instruction) {
  return (instruction & 0x0FF00000) == 0x03000000;
}

bool ArchHandler_arm::isArmMovt(uint32_t instruction) {
  return (instruction & 0x0FF00000) == 0x03400000;
}

uint16_t ArchHandler_arm::getWordFromThumbMov(uint32_t instruction) {
  assert(isThumbMovw(instruction) || isThumbMovt(instruction));
  uint32_t i = ((instruction & 0x00000400) >> 10);
  uint32_t imm4 = (instruction & 0x0000000F);
  uint32_t imm3 = ((instruction & 0x70000000) >> 28);
  uint32_t imm8 = ((instruction & 0x00FF0000) >> 16);
  return (imm4 << 12) | (i << 11) | (imm3 << 8) | imm8;
}

uint16_t ArchHandler_arm::getWordFromArmMov(uint32_t instruction) {
  assert(isArmMovw(instruction) || isArmMovt(instruction));
  uint32_t imm4 = ((instruction & 0x000F0000) >> 16);
  uint32_t imm12 = (instruction & 0x00000FFF);
  return (imm4 << 12) | imm12;
}

uint32_t ArchHandler_arm::setWordFromThumbMov(uint32_t instr, uint16_t word) {
  assert(isThumbMovw(instr) || isThumbMovt(instr));
  uint32_t imm4 = (word & 0xF000) >> 12;
  uint32_t i =    (word & 0x0800) >> 11;
  uint32_t imm3 = (word & 0x0700) >> 8;
  uint32_t imm8 =  word & 0x00FF;
	return (instr & 0x8F00FBF0) | imm4 | (i << 10) | (imm3 << 28) | (imm8 << 16);
}

uint32_t ArchHandler_arm::setWordFromArmMov(uint32_t instr, uint16_t word) {
  assert(isArmMovw(instr) || isArmMovt(instr));
  uint32_t imm4 = (word & 0xF000) >> 12;
  uint32_t imm12 = word & 0x0FFF;
  return (instr & 0xFFF0F000) | (imm4 << 16) | imm12;
}

uint32_t ArchHandler_arm::clearThumbBit(uint32_t value, const Atom *target) {
  // The assembler often adds one to the address of a thumb function.
  // We need to undo that so it does not look like an addend.
  if (value & 1) {
    if (isa<DefinedAtom>(target)) {
      const MachODefinedAtom *machoTarget =
          reinterpret_cast<const MachODefinedAtom *>(target);
      if (machoTarget->isThumb())
        value &= -2; // mask off thumb-bit
    }
  }
  return value;
}

llvm::Error ArchHandler_arm::getReferenceInfo(
    const Relocation &reloc, const DefinedAtom *inAtom, uint32_t offsetInAtom,
    uint64_t fixupAddress, bool isBig,
    FindAtomBySectionAndAddress atomFromAddress,
    FindAtomBySymbolIndex atomFromSymbolIndex, Reference::KindValue *kind,
    const lld::Atom **target, Reference::Addend *addend) {
  const uint8_t *fixupContent = &inAtom->rawContent()[offsetInAtom];
  uint64_t targetAddress;
  uint32_t instruction = *(const ulittle32_t *)fixupContent;
  int32_t displacement;
  switch (relocPattern(reloc)) {
  case ARM_THUMB_RELOC_BR22 | rPcRel | rExtern | rLength4:
    // ex: bl _foo (and _foo is undefined)
    if ((instruction & 0xD000F800) == 0x9000F000)
      *kind = thumb_b22;
    else
      *kind = thumb_bl22;
    if (auto ec = atomFromSymbolIndex(reloc.symbol, target))
      return ec;
    // Instruction contains branch to addend.
    displacement = getDisplacementFromThumbBranch(instruction, fixupAddress);
    *addend = fixupAddress + 4 + displacement;
    return llvm::Error::success();
  case ARM_THUMB_RELOC_BR22 | rPcRel | rLength4:
    // ex: bl _foo (and _foo is defined)
    if ((instruction & 0xD000F800) == 0x9000F000)
      *kind = thumb_b22;
    else
      *kind = thumb_bl22;
    displacement = getDisplacementFromThumbBranch(instruction, fixupAddress);
    targetAddress = fixupAddress + 4 + displacement;
    return atomFromAddress(reloc.symbol, targetAddress, target, addend);
  case ARM_THUMB_RELOC_BR22 | rScattered | rPcRel | rLength4:
    // ex: bl _foo+4 (and _foo is defined)
    if ((instruction & 0xD000F800) == 0x9000F000)
      *kind = thumb_b22;
    else
      *kind = thumb_bl22;
    displacement = getDisplacementFromThumbBranch(instruction, fixupAddress);
    targetAddress = fixupAddress + 4 + displacement;
    if (auto ec = atomFromAddress(0, reloc.value, target, addend))
      return ec;
    // reloc.value is target atom's address.  Instruction contains branch
    // to atom+addend.
    *addend += (targetAddress - reloc.value);
    return llvm::Error::success();
  case ARM_RELOC_BR24 | rPcRel | rExtern | rLength4:
    // ex: bl _foo (and _foo is undefined)
    if (((instruction & 0x0F000000) == 0x0A000000)
        && ((instruction & 0xF0000000) != 0xF0000000))
      *kind = arm_b24;
    else
      *kind = arm_bl24;
    if (auto ec = atomFromSymbolIndex(reloc.symbol, target))
      return ec;
    // Instruction contains branch to addend.
    displacement = getDisplacementFromArmBranch(instruction);
    *addend = fixupAddress + 8 + displacement;
    return llvm::Error::success();
  case ARM_RELOC_BR24 | rPcRel | rLength4:
    // ex: bl _foo (and _foo is defined)
    if (((instruction & 0x0F000000) == 0x0A000000)
        && ((instruction & 0xF0000000) != 0xF0000000))
      *kind = arm_b24;
    else
      *kind = arm_bl24;
    displacement = getDisplacementFromArmBranch(instruction);
    targetAddress = fixupAddress + 8 + displacement;
    return atomFromAddress(reloc.symbol, targetAddress, target, addend);
  case ARM_RELOC_BR24 | rScattered | rPcRel | rLength4:
    // ex: bl _foo+4 (and _foo is defined)
    if (((instruction & 0x0F000000) == 0x0A000000)
        && ((instruction & 0xF0000000) != 0xF0000000))
      *kind = arm_b24;
    else
      *kind = arm_bl24;
    displacement = getDisplacementFromArmBranch(instruction);
    targetAddress = fixupAddress + 8 + displacement;
    if (auto ec = atomFromAddress(0, reloc.value, target, addend))
      return ec;
    // reloc.value is target atom's address.  Instruction contains branch
    // to atom+addend.
    *addend += (targetAddress - reloc.value);
    return llvm::Error::success();
  case ARM_RELOC_VANILLA | rExtern | rLength4:
    // ex: .long _foo (and _foo is undefined)
    *kind = pointer32;
    if (auto ec = atomFromSymbolIndex(reloc.symbol, target))
      return ec;
    *addend = instruction;
    return llvm::Error::success();
  case ARM_RELOC_VANILLA | rLength4:
    // ex: .long _foo (and _foo is defined)
    *kind = pointer32;
    if (auto ec = atomFromAddress(reloc.symbol, instruction, target, addend))
      return ec;
    *addend = clearThumbBit((uint32_t) * addend, *target);
    return llvm::Error::success();
  case ARM_RELOC_VANILLA | rScattered | rLength4:
    // ex: .long _foo+a (and _foo is defined)
    *kind = pointer32;
    if (auto ec = atomFromAddress(0, reloc.value, target, addend))
      return ec;
    *addend += (clearThumbBit(instruction, *target) - reloc.value);
    return llvm::Error::success();
  default:
    return llvm::make_error<GenericError>("unsupported arm relocation type");
  }
  return llvm::Error::success();
}

llvm::Error
ArchHandler_arm::getPairReferenceInfo(const normalized::Relocation &reloc1,
                                     const normalized::Relocation &reloc2,
                                     const DefinedAtom *inAtom,
                                     uint32_t offsetInAtom,
                                     uint64_t fixupAddress, bool isBig,
                                     bool scatterable,
                                     FindAtomBySectionAndAddress atomFromAddr,
                                     FindAtomBySymbolIndex atomFromSymbolIndex,
                                     Reference::KindValue *kind,
                                     const lld::Atom **target,
                                     Reference::Addend *addend) {
  bool pointerDiff = false;
  bool funcRel;
  bool top;
  bool thumbReloc;
  switch(relocPattern(reloc1) << 16 | relocPattern(reloc2)) {
  case ((ARM_RELOC_HALF_SECTDIFF  | rScattered | rLenThmbLo) << 16 |
         ARM_RELOC_PAIR           | rScattered | rLenThmbLo):
    // ex: movw	r1, :lower16:(_x-L1) [thumb mode]
    *kind = thumb_movw_funcRel;
    funcRel = true;
    top = false;
    thumbReloc = true;
    break;
  case ((ARM_RELOC_HALF_SECTDIFF  | rScattered | rLenThmbHi) << 16 |
         ARM_RELOC_PAIR           | rScattered | rLenThmbHi):
    // ex: movt	r1, :upper16:(_x-L1) [thumb mode]
    *kind = thumb_movt_funcRel;
    funcRel = true;
    top = true;
    thumbReloc = true;
    break;
  case ((ARM_RELOC_HALF_SECTDIFF  | rScattered | rLenArmLo) << 16 |
         ARM_RELOC_PAIR           | rScattered | rLenArmLo):
    // ex: movw	r1, :lower16:(_x-L1) [arm mode]
    *kind = arm_movw_funcRel;
    funcRel = true;
    top = false;
    thumbReloc = false;
    break;
  case ((ARM_RELOC_HALF_SECTDIFF  | rScattered | rLenArmHi) << 16 |
         ARM_RELOC_PAIR           | rScattered | rLenArmHi):
    // ex: movt	r1, :upper16:(_x-L1) [arm mode]
    *kind = arm_movt_funcRel;
    funcRel = true;
    top = true;
    thumbReloc = false;
    break;
  case ((ARM_RELOC_HALF     | rLenThmbLo) << 16 |
         ARM_RELOC_PAIR     | rLenThmbLo):
    // ex: movw	r1, :lower16:_x [thumb mode]
    *kind = thumb_movw;
    funcRel = false;
    top = false;
    thumbReloc = true;
    break;
  case ((ARM_RELOC_HALF     | rLenThmbHi) << 16 |
         ARM_RELOC_PAIR     | rLenThmbHi):
    // ex: movt	r1, :upper16:_x [thumb mode]
    *kind = thumb_movt;
    funcRel = false;
    top = true;
    thumbReloc = true;
    break;
  case ((ARM_RELOC_HALF     | rLenArmLo) << 16 |
         ARM_RELOC_PAIR     | rLenArmLo):
    // ex: movw	r1, :lower16:_x [arm mode]
    *kind = arm_movw;
    funcRel = false;
    top = false;
    thumbReloc = false;
    break;
  case ((ARM_RELOC_HALF     | rLenArmHi) << 16 |
         ARM_RELOC_PAIR     | rLenArmHi):
    // ex: movt	r1, :upper16:_x [arm mode]
    *kind = arm_movt;
    funcRel = false;
    top = true;
    thumbReloc = false;
    break;
  case ((ARM_RELOC_HALF | rScattered  | rLenThmbLo) << 16 |
         ARM_RELOC_PAIR               | rLenThmbLo):
    // ex: movw	r1, :lower16:_x+a [thumb mode]
    *kind = thumb_movw;
    funcRel = false;
    top = false;
    thumbReloc = true;
    break;
  case ((ARM_RELOC_HALF | rScattered  | rLenThmbHi) << 16 |
         ARM_RELOC_PAIR               | rLenThmbHi):
    // ex: movt	r1, :upper16:_x+a [thumb mode]
    *kind = thumb_movt;
    funcRel = false;
    top = true;
    thumbReloc = true;
    break;
  case ((ARM_RELOC_HALF | rScattered  | rLenArmLo) << 16 |
         ARM_RELOC_PAIR               | rLenArmLo):
    // ex: movw	r1, :lower16:_x+a [arm mode]
    *kind = arm_movw;
    funcRel = false;
    top = false;
    thumbReloc = false;
    break;
  case ((ARM_RELOC_HALF | rScattered  | rLenArmHi) << 16 |
         ARM_RELOC_PAIR               | rLenArmHi):
    // ex: movt	r1, :upper16:_x+a [arm mode]
    *kind = arm_movt;
    funcRel = false;
    top = true;
    thumbReloc = false;
    break;
  case ((ARM_RELOC_HALF | rExtern   | rLenThmbLo) << 16 |
         ARM_RELOC_PAIR             | rLenThmbLo):
    // ex: movw	r1, :lower16:_undef [thumb mode]
    *kind = thumb_movw;
    funcRel = false;
    top = false;
    thumbReloc = true;
    break;
  case ((ARM_RELOC_HALF | rExtern   | rLenThmbHi) << 16 |
         ARM_RELOC_PAIR             | rLenThmbHi):
    // ex: movt	r1, :upper16:_undef [thumb mode]
    *kind = thumb_movt;
    funcRel = false;
    top = true;
    thumbReloc = true;
    break;
  case ((ARM_RELOC_HALF | rExtern   | rLenArmLo) << 16 |
         ARM_RELOC_PAIR             | rLenArmLo):
    // ex: movw	r1, :lower16:_undef [arm mode]
    *kind = arm_movw;
    funcRel = false;
    top = false;
    thumbReloc = false;
    break;
  case ((ARM_RELOC_HALF | rExtern   | rLenArmHi) << 16 |
         ARM_RELOC_PAIR             | rLenArmHi):
    // ex: movt	r1, :upper16:_undef [arm mode]
    *kind = arm_movt;
    funcRel = false;
    top = true;
    thumbReloc = false;
    break;
  case ((ARM_RELOC_SECTDIFF       | rScattered | rLength4) << 16 |
         ARM_RELOC_PAIR           | rScattered | rLength4):
  case ((ARM_RELOC_LOCAL_SECTDIFF | rScattered | rLength4) << 16 |
         ARM_RELOC_PAIR           | rScattered | rLength4):
    // ex: .long _foo - .
    pointerDiff = true;
    break;
  default:
    return llvm::make_error<GenericError>("unsupported arm relocation pair");
  }
  const uint8_t *fixupContent = &inAtom->rawContent()[offsetInAtom];
  uint32_t instruction = *(const ulittle32_t *)fixupContent;
  uint32_t value;
  uint32_t fromAddress;
  uint32_t toAddress;
  uint16_t instruction16;
  uint16_t other16;
  const lld::Atom *fromTarget;
  Reference::Addend offsetInTo;
  Reference::Addend offsetInFrom;
  if (pointerDiff) {
    toAddress = reloc1.value;
    fromAddress = reloc2.value;
    if (auto ec = atomFromAddr(0, toAddress, target, &offsetInTo))
      return ec;
    if (auto ec = atomFromAddr(0, fromAddress, &fromTarget, &offsetInFrom))
      return ec;
    if (scatterable && (fromTarget != inAtom))
      return llvm::make_error<GenericError>(
          "SECTDIFF relocation where subtrahend label is not in atom");
    *kind = delta32;
    value = clearThumbBit(instruction, *target);
    *addend = (int32_t)(value - (toAddress - fixupAddress));
  } else if (funcRel) {
    toAddress = reloc1.value;
    fromAddress = reloc2.value;
    if (auto ec = atomFromAddr(0, toAddress, target, &offsetInTo))
      return ec;
    if (auto ec = atomFromAddr(0, fromAddress, &fromTarget, &offsetInFrom))
      return ec;
    if (fromTarget != inAtom)
      return llvm::make_error<GenericError>("ARM_RELOC_HALF_SECTDIFF relocation"
                                     " where subtrahend label is not in atom");
    other16 = (reloc2.offset & 0xFFFF);
    if (thumbReloc) {
      if (top) {
        if (!isThumbMovt(instruction))
          return llvm::make_error<GenericError>("expected movt instruction");
      }
      else {
        if (!isThumbMovw(instruction))
          return llvm::make_error<GenericError>("expected movw instruction");
      }
      instruction16 = getWordFromThumbMov(instruction);
    }
    else {
      if (top) {
        if (!isArmMovt(instruction))
          return llvm::make_error<GenericError>("expected movt instruction");
      }
      else {
        if (!isArmMovw(instruction))
          return llvm::make_error<GenericError>("expected movw instruction");
      }
      instruction16 = getWordFromArmMov(instruction);
    }
    if (top)
      value = (instruction16 << 16) | other16;
    else
      value = (other16 << 16) | instruction16;
    value = clearThumbBit(value, *target);
    int64_t ta = (int64_t) value - (toAddress - fromAddress);
    *addend = ta - offsetInFrom;
    return llvm::Error::success();
  } else {
    uint32_t sectIndex;
    if (thumbReloc) {
      if (top) {
        if (!isThumbMovt(instruction))
          return llvm::make_error<GenericError>("expected movt instruction");
      }
      else {
        if (!isThumbMovw(instruction))
          return llvm::make_error<GenericError>("expected movw instruction");
      }
      instruction16 = getWordFromThumbMov(instruction);
    }
    else {
      if (top) {
        if (!isArmMovt(instruction))
          return llvm::make_error<GenericError>("expected movt instruction");
      }
      else {
        if (!isArmMovw(instruction))
          return llvm::make_error<GenericError>("expected movw instruction");
      }
      instruction16 = getWordFromArmMov(instruction);
    }
    other16 = (reloc2.offset & 0xFFFF);
    if (top)
      value = (instruction16 << 16) | other16;
    else
      value = (other16 << 16) | instruction16;
    if (reloc1.isExtern) {
      if (auto ec = atomFromSymbolIndex(reloc1.symbol, target))
        return ec;
      *addend = value;
    } else {
      if (reloc1.scattered) {
        toAddress = reloc1.value;
        sectIndex = 0;
      } else {
        toAddress = value;
        sectIndex = reloc1.symbol;
      }
      if (auto ec = atomFromAddr(sectIndex, toAddress, target, &offsetInTo))
        return ec;
      *addend = value - toAddress;
    }
  }

  return llvm::Error::success();
}

void ArchHandler_arm::applyFixupFinal(const Reference &ref, uint8_t *loc,
                                      uint64_t fixupAddress,
                                      uint64_t targetAddress,
                                      uint64_t inAtomAddress,
                                      bool &thumbMode, bool targetIsThumb) {
  if (ref.kindNamespace() != Reference::KindNamespace::mach_o)
    return;
  assert(ref.kindArch() == Reference::KindArch::ARM);
  ulittle32_t *loc32 = reinterpret_cast<ulittle32_t *>(loc);
  int32_t displacement;
  uint16_t value16;
  uint32_t value32;
  switch (static_cast<ArmKind>(ref.kindValue())) {
  case modeThumbCode:
    thumbMode = true;
    break;
  case modeArmCode:
    thumbMode = false;
    break;
  case modeData:
    break;
  case thumb_b22:
  case thumb_bl22:
    assert(thumbMode);
    displacement = (targetAddress - (fixupAddress + 4)) + ref.addend();
    value32 = setDisplacementInThumbBranch(*loc32, fixupAddress,
                                           displacement, targetIsThumb);
    *loc32 = value32;
    break;
  case thumb_movw:
    assert(thumbMode);
    value16 = (targetAddress + ref.addend()) & 0xFFFF;
    if (targetIsThumb)
      value16 |= 1;
    *loc32 = setWordFromThumbMov(*loc32, value16);
    break;
  case thumb_movt:
    assert(thumbMode);
    value16 = (targetAddress + ref.addend()) >> 16;
    *loc32 = setWordFromThumbMov(*loc32, value16);
    break;
  case thumb_movw_funcRel:
    assert(thumbMode);
    value16 = (targetAddress - inAtomAddress + ref.addend()) & 0xFFFF;
    if (targetIsThumb)
      value16 |= 1;
    *loc32 = setWordFromThumbMov(*loc32, value16);
    break;
  case thumb_movt_funcRel:
    assert(thumbMode);
    value16 = (targetAddress - inAtomAddress + ref.addend()) >> 16;
    *loc32 = setWordFromThumbMov(*loc32, value16);
    break;
  case arm_b24:
  case arm_bl24:
   assert(!thumbMode);
    displacement = (targetAddress - (fixupAddress + 8)) + ref.addend();
    value32 = setDisplacementInArmBranch(*loc32, displacement, targetIsThumb);
    *loc32 = value32;
    break;
  case arm_movw:
    assert(!thumbMode);
    value16 = (targetAddress + ref.addend()) & 0xFFFF;
    if (targetIsThumb)
      value16 |= 1;
    *loc32 = setWordFromArmMov(*loc32, value16);
    break;
  case arm_movt:
    assert(!thumbMode);
    value16 = (targetAddress + ref.addend()) >> 16;
    *loc32 = setWordFromArmMov(*loc32, value16);
    break;
  case arm_movw_funcRel:
    assert(!thumbMode);
    value16 = (targetAddress - inAtomAddress + ref.addend()) & 0xFFFF;
    if (targetIsThumb)
      value16 |= 1;
    *loc32 = setWordFromArmMov(*loc32, value16);
    break;
  case arm_movt_funcRel:
    assert(!thumbMode);
    value16 = (targetAddress - inAtomAddress + ref.addend()) >> 16;
    *loc32 = setWordFromArmMov(*loc32, value16);
    break;
  case pointer32:
    if (targetIsThumb)
      *loc32 = targetAddress + ref.addend() + 1;
    else
      *loc32 = targetAddress + ref.addend();
    break;
  case delta32:
    if (targetIsThumb)
      *loc32 = targetAddress - fixupAddress + ref.addend() + 1;
    else
      *loc32 = targetAddress - fixupAddress + ref.addend();
    break;
  case lazyPointer:
    // do nothing
    break;
  case lazyImmediateLocation:
    *loc32 = ref.addend();
    break;
  case invalid:
    llvm_unreachable("invalid ARM Reference Kind");
    break;
  }
}

void ArchHandler_arm::generateAtomContent(const DefinedAtom &atom,
                                          bool relocatable,
                                          FindAddressForAtom findAddress,
                                          FindAddressForAtom findSectionAddress,
                                          uint64_t imageBaseAddress,
                            llvm::MutableArrayRef<uint8_t> atomContentBuffer) {
  // Copy raw bytes.
  std::copy(atom.rawContent().begin(), atom.rawContent().end(),
            atomContentBuffer.begin());
  // Apply fix-ups.
  bool thumbMode = false;
  for (const Reference *ref : atom) {
    uint32_t offset = ref->offsetInAtom();
    const Atom *target = ref->target();
    uint64_t targetAddress = 0;
    bool targetIsThumb = false;
    if (const DefinedAtom *defTarg = dyn_cast<DefinedAtom>(target)) {
      targetAddress = findAddress(*target);
      targetIsThumb = isThumbFunction(*defTarg);
    }
    uint64_t atomAddress = findAddress(atom);
    uint64_t fixupAddress = atomAddress + offset;
    if (relocatable) {
      applyFixupRelocatable(*ref, &atomContentBuffer[offset], fixupAddress,
                            targetAddress, atomAddress, thumbMode,
                            targetIsThumb);
    } else {
      applyFixupFinal(*ref, &atomContentBuffer[offset], fixupAddress,
                      targetAddress, atomAddress, thumbMode, targetIsThumb);
    }
  }
}

bool ArchHandler_arm::useExternalRelocationTo(const Atom &target) {
  // Undefined symbols are referenced via external relocations.
  if (isa<UndefinedAtom>(&target))
    return true;
  if (const DefinedAtom *defAtom = dyn_cast<DefinedAtom>(&target)) {
     switch (defAtom->merge()) {
     case DefinedAtom::mergeAsTentative:
       // Tentative definitions are referenced via external relocations.
       return true;
     case DefinedAtom::mergeAsWeak:
     case DefinedAtom::mergeAsWeakAndAddressUsed:
       // Global weak-defs are referenced via external relocations.
       return (defAtom->scope() == DefinedAtom::scopeGlobal);
     default:
       break;
    }
  }
  // Everything else is reference via an internal relocation.
  return false;
}

void ArchHandler_arm::applyFixupRelocatable(const Reference &ref, uint8_t *loc,
                                            uint64_t fixupAddress,
                                            uint64_t targetAddress,
                                            uint64_t inAtomAddress,
                                            bool &thumbMode,
                                            bool targetIsThumb) {
  if (ref.kindNamespace() != Reference::KindNamespace::mach_o)
    return;
  assert(ref.kindArch() == Reference::KindArch::ARM);
  bool useExternalReloc = useExternalRelocationTo(*ref.target());
  ulittle32_t *loc32 = reinterpret_cast<ulittle32_t *>(loc);
  int32_t displacement;
  uint16_t value16;
  uint32_t value32;
  bool targetIsUndef = isa<UndefinedAtom>(ref.target());
  switch (static_cast<ArmKind>(ref.kindValue())) {
  case modeThumbCode:
    thumbMode = true;
    break;
  case modeArmCode:
    thumbMode = false;
    break;
  case modeData:
    break;
  case thumb_b22:
  case thumb_bl22:
    assert(thumbMode);
    if (useExternalReloc)
      displacement = (ref.addend() - (fixupAddress + 4));
    else
      displacement = (targetAddress - (fixupAddress + 4)) + ref.addend();
    value32 = setDisplacementInThumbBranch(*loc32, fixupAddress,
                                           displacement,
                                           targetIsUndef || targetIsThumb);
    *loc32 = value32;
    break;
  case thumb_movw:
    assert(thumbMode);
    if (useExternalReloc)
      value16 = ref.addend() & 0xFFFF;
    else
      value16 = (targetAddress + ref.addend()) & 0xFFFF;
    *loc32 = setWordFromThumbMov(*loc32, value16);
    break;
  case thumb_movt:
    assert(thumbMode);
    if (useExternalReloc)
      value16 = ref.addend() >> 16;
    else
      value16 = (targetAddress + ref.addend()) >> 16;
    *loc32 = setWordFromThumbMov(*loc32, value16);
    break;
  case thumb_movw_funcRel:
    assert(thumbMode);
    value16 = (targetAddress - inAtomAddress + ref.addend()) & 0xFFFF;
    *loc32 = setWordFromThumbMov(*loc32, value16);
    break;
  case thumb_movt_funcRel:
    assert(thumbMode);
    value16 = (targetAddress - inAtomAddress + ref.addend()) >> 16;
    *loc32 = setWordFromThumbMov(*loc32, value16);
    break;
  case arm_b24:
  case arm_bl24:
    assert(!thumbMode);
    if (useExternalReloc)
      displacement = (ref.addend() - (fixupAddress + 8));
    else
      displacement = (targetAddress - (fixupAddress + 8)) + ref.addend();
    value32 = setDisplacementInArmBranch(*loc32, displacement,
                                         targetIsThumb);
    *loc32 = value32;
    break;
  case arm_movw:
    assert(!thumbMode);
    if (useExternalReloc)
      value16 = ref.addend() & 0xFFFF;
    else
      value16 = (targetAddress + ref.addend()) & 0xFFFF;
    *loc32 = setWordFromArmMov(*loc32, value16);
    break;
  case arm_movt:
    assert(!thumbMode);
    if (useExternalReloc)
      value16 = ref.addend() >> 16;
    else
      value16 = (targetAddress + ref.addend()) >> 16;
    *loc32 = setWordFromArmMov(*loc32, value16);
    break;
  case arm_movw_funcRel:
    assert(!thumbMode);
    value16 = (targetAddress - inAtomAddress + ref.addend()) & 0xFFFF;
    *loc32 = setWordFromArmMov(*loc32, value16);
    break;
  case arm_movt_funcRel:
    assert(!thumbMode);
    value16 = (targetAddress - inAtomAddress + ref.addend()) >> 16;
    *loc32 = setWordFromArmMov(*loc32, value16);
    break;
  case pointer32:
    *loc32 = targetAddress + ref.addend();
    break;
  case delta32:
    *loc32 = targetAddress - fixupAddress + ref.addend();
    break;
  case lazyPointer:
  case lazyImmediateLocation:
    // do nothing
    break;
  case invalid:
    llvm_unreachable("invalid ARM Reference Kind");
    break;
  }
}

void ArchHandler_arm::appendSectionRelocations(
                                   const DefinedAtom &atom,
                                   uint64_t atomSectionOffset,
                                   const Reference &ref,
                                   FindSymbolIndexForAtom symbolIndexForAtom,
                                   FindSectionIndexForAtom sectionIndexForAtom,
                                   FindAddressForAtom addressForAtom,
                                   normalized::Relocations &relocs) {
  if (ref.kindNamespace() != Reference::KindNamespace::mach_o)
    return;
  assert(ref.kindArch() == Reference::KindArch::ARM);
  uint32_t sectionOffset = atomSectionOffset + ref.offsetInAtom();
  bool useExternalReloc = useExternalRelocationTo(*ref.target());
  uint32_t targetAtomAddress;
  uint32_t fromAtomAddress;
  uint16_t other16;
  switch (static_cast<ArmKind>(ref.kindValue())) {
  case modeThumbCode:
  case modeArmCode:
  case modeData:
    // Do nothing.
    break;
  case thumb_b22:
  case thumb_bl22:
    if (useExternalReloc) {
      appendReloc(relocs, sectionOffset, symbolIndexForAtom(*ref.target()), 0,
                  ARM_THUMB_RELOC_BR22 | rExtern    | rPcRel | rLength4);
    } else {
      if (ref.addend() != 0)
        appendReloc(relocs, sectionOffset, 0, addressForAtom(*ref.target()),
                  ARM_THUMB_RELOC_BR22 | rScattered | rPcRel | rLength4);
      else
        appendReloc(relocs, sectionOffset, sectionIndexForAtom(*ref.target()),0,
                  ARM_THUMB_RELOC_BR22 |              rPcRel | rLength4);
    }
    break;
  case thumb_movw:
    if (useExternalReloc) {
      other16 = ref.addend() >> 16;
      appendReloc(relocs, sectionOffset, symbolIndexForAtom(*ref.target()), 0,
                  ARM_RELOC_HALF | rExtern    | rLenThmbLo);
      appendReloc(relocs, other16, 0, 0,
                  ARM_RELOC_PAIR              | rLenThmbLo);
    } else {
      targetAtomAddress = addressForAtom(*ref.target());
      if (ref.addend() != 0) {
        other16 = (targetAtomAddress + ref.addend()) >> 16;
        appendReloc(relocs, sectionOffset, 0, targetAtomAddress,
                  ARM_RELOC_HALF | rScattered | rLenThmbLo);
        appendReloc(relocs, other16, 0, 0,
                  ARM_RELOC_PAIR              | rLenThmbLo);
      } else {
        other16 = (targetAtomAddress + ref.addend()) >> 16;
        appendReloc(relocs, sectionOffset, sectionIndexForAtom(*ref.target()),0,
                  ARM_RELOC_HALF              | rLenThmbLo);
        appendReloc(relocs, other16, 0, 0,
                  ARM_RELOC_PAIR              | rLenThmbLo);
      }
    }
    break;
  case thumb_movt:
    if (useExternalReloc) {
      other16 = ref.addend() & 0xFFFF;
      appendReloc(relocs, sectionOffset, symbolIndexForAtom(*ref.target()), 0,
                  ARM_RELOC_HALF | rExtern    | rLenThmbHi);
      appendReloc(relocs, other16, 0, 0,
                  ARM_RELOC_PAIR              | rLenThmbHi);
    } else {
      targetAtomAddress = addressForAtom(*ref.target());
      if (ref.addend() != 0) {
        other16 = (targetAtomAddress + ref.addend()) & 0xFFFF;
        appendReloc(relocs, sectionOffset, 0, targetAtomAddress,
                    ARM_RELOC_HALF | rScattered | rLenThmbHi);
        appendReloc(relocs, other16, 0, 0,
                    ARM_RELOC_PAIR              | rLenThmbHi);
      } else {
        other16 = (targetAtomAddress + ref.addend()) & 0xFFFF;
        appendReloc(relocs, sectionOffset, sectionIndexForAtom(*ref.target()),0,
                    ARM_RELOC_HALF              | rLenThmbHi);
        appendReloc(relocs, other16, 0, 0,
                    ARM_RELOC_PAIR              | rLenThmbHi);
      }
    }
    break;
  case thumb_movw_funcRel:
    fromAtomAddress = addressForAtom(atom);
    targetAtomAddress = addressForAtom(*ref.target());
    other16 = (targetAtomAddress - fromAtomAddress + ref.addend()) >> 16;
    appendReloc(relocs, sectionOffset, 0, targetAtomAddress,
                ARM_RELOC_HALF_SECTDIFF | rScattered | rLenThmbLo);
    appendReloc(relocs, other16, 0, fromAtomAddress,
                ARM_RELOC_PAIR          | rScattered | rLenThmbLo);
    break;
  case thumb_movt_funcRel:
    fromAtomAddress = addressForAtom(atom);
    targetAtomAddress = addressForAtom(*ref.target());
    other16 = (targetAtomAddress - fromAtomAddress + ref.addend()) & 0xFFFF;
    appendReloc(relocs, sectionOffset, 0, targetAtomAddress,
                ARM_RELOC_HALF_SECTDIFF | rScattered | rLenThmbHi);
    appendReloc(relocs, other16, 0, fromAtomAddress,
                ARM_RELOC_PAIR          | rScattered | rLenThmbHi);
    break;
  case arm_b24:
  case arm_bl24:
    if (useExternalReloc) {
      appendReloc(relocs, sectionOffset, symbolIndexForAtom(*ref.target()), 0,
                  ARM_RELOC_BR24 | rExtern    | rPcRel | rLength4);
    } else {
      if (ref.addend() != 0)
        appendReloc(relocs, sectionOffset, 0, addressForAtom(*ref.target()),
                  ARM_RELOC_BR24 | rScattered | rPcRel | rLength4);
      else
        appendReloc(relocs, sectionOffset, sectionIndexForAtom(*ref.target()),0,
                  ARM_RELOC_BR24 |              rPcRel | rLength4);
    }
    break;
  case arm_movw:
    if (useExternalReloc) {
      other16 = ref.addend() >> 16;
      appendReloc(relocs, sectionOffset, symbolIndexForAtom(*ref.target()), 0,
                  ARM_RELOC_HALF | rExtern    | rLenArmLo);
      appendReloc(relocs, other16, 0, 0,
                  ARM_RELOC_PAIR              | rLenArmLo);
    } else {
      targetAtomAddress = addressForAtom(*ref.target());
      if (ref.addend() != 0) {
        other16 = (targetAtomAddress + ref.addend()) >> 16;
        appendReloc(relocs, sectionOffset, 0, targetAtomAddress,
                  ARM_RELOC_HALF | rScattered | rLenArmLo);
        appendReloc(relocs, other16, 0, 0,
                  ARM_RELOC_PAIR              | rLenArmLo);
      } else {
        other16 = (targetAtomAddress + ref.addend()) >> 16;
        appendReloc(relocs, sectionOffset, sectionIndexForAtom(*ref.target()),0,
                  ARM_RELOC_HALF              | rLenArmLo);
        appendReloc(relocs, other16, 0, 0,
                  ARM_RELOC_PAIR              | rLenArmLo);
      }
    }
    break;
  case arm_movt:
    if (useExternalReloc) {
      other16 = ref.addend() & 0xFFFF;
      appendReloc(relocs, sectionOffset, symbolIndexForAtom(*ref.target()), 0,
                  ARM_RELOC_HALF | rExtern    | rLenArmHi);
      appendReloc(relocs, other16, 0, 0,
                  ARM_RELOC_PAIR              | rLenArmHi);
    } else {
      targetAtomAddress = addressForAtom(*ref.target());
      if (ref.addend() != 0) {
        other16 = (targetAtomAddress + ref.addend()) & 0xFFFF;
        appendReloc(relocs, sectionOffset, 0, targetAtomAddress,
                  ARM_RELOC_HALF | rScattered | rLenArmHi);
        appendReloc(relocs, other16, 0, 0,
                  ARM_RELOC_PAIR              | rLenArmHi);
      } else {
        other16 = (targetAtomAddress + ref.addend()) & 0xFFFF;
        appendReloc(relocs, sectionOffset, sectionIndexForAtom(*ref.target()),0,
                  ARM_RELOC_HALF              | rLenArmHi);
        appendReloc(relocs, other16, 0, 0,
                  ARM_RELOC_PAIR              | rLenArmHi);
      }
    }
    break;
  case arm_movw_funcRel:
    fromAtomAddress = addressForAtom(atom);
    targetAtomAddress = addressForAtom(*ref.target());
    other16 = (targetAtomAddress - fromAtomAddress + ref.addend()) >> 16;
    appendReloc(relocs, sectionOffset, 0, targetAtomAddress,
                ARM_RELOC_HALF_SECTDIFF | rScattered | rLenArmLo);
    appendReloc(relocs, other16, 0, fromAtomAddress,
                ARM_RELOC_PAIR          | rScattered | rLenArmLo);
    break;
  case arm_movt_funcRel:
    fromAtomAddress = addressForAtom(atom);
    targetAtomAddress = addressForAtom(*ref.target());
    other16 = (targetAtomAddress - fromAtomAddress + ref.addend()) & 0xFFFF;
    appendReloc(relocs, sectionOffset, 0, targetAtomAddress,
                ARM_RELOC_HALF_SECTDIFF | rScattered | rLenArmHi);
    appendReloc(relocs, other16, 0, fromAtomAddress,
                ARM_RELOC_PAIR          | rScattered | rLenArmHi);
    break;
  case pointer32:
    if (useExternalReloc) {
      appendReloc(relocs, sectionOffset, symbolIndexForAtom(*ref.target()),  0,
                ARM_RELOC_VANILLA |    rExtern     |  rLength4);
    }
    else {
      if (ref.addend() != 0)
        appendReloc(relocs, sectionOffset, 0, addressForAtom(*ref.target()),
                ARM_RELOC_VANILLA |    rScattered  |  rLength4);
      else
        appendReloc(relocs, sectionOffset, sectionIndexForAtom(*ref.target()),0,
                ARM_RELOC_VANILLA |                   rLength4);
    }
    break;
  case delta32:
    appendReloc(relocs, sectionOffset, 0, addressForAtom(*ref.target()),
              ARM_RELOC_SECTDIFF  |  rScattered    | rLength4);
    appendReloc(relocs, sectionOffset, 0, addressForAtom(atom) +
                                                           ref.offsetInAtom(),
              ARM_RELOC_PAIR      |  rScattered    | rLength4);
    break;
  case lazyPointer:
  case lazyImmediateLocation:
    // do nothing
    break;
  case invalid:
    llvm_unreachable("invalid ARM Reference Kind");
    break;
  }
}

void ArchHandler_arm::addAdditionalReferences(MachODefinedAtom &atom) {
  if (atom.isThumb()) {
    atom.addReference(Reference::KindNamespace::mach_o,
                      Reference::KindArch::ARM, modeThumbCode, 0, &atom, 0);
  }
}

bool ArchHandler_arm::isThumbFunction(const DefinedAtom &atom) {
  for (const Reference *ref : atom) {
    if (ref->offsetInAtom() != 0)
      return false;
    if (ref->kindNamespace() != Reference::KindNamespace::mach_o)
      continue;
    assert(ref->kindArch() == Reference::KindArch::ARM);
    if (ref->kindValue() == modeThumbCode)
      return true;
  }
  return false;
}

class Thumb2ToArmShimAtom : public SimpleDefinedAtom {
public:
  Thumb2ToArmShimAtom(MachOFile &file, StringRef targetName,
                      const DefinedAtom &target)
      : SimpleDefinedAtom(file) {
    addReference(Reference::KindNamespace::mach_o, Reference::KindArch::ARM,
                 ArchHandler_arm::modeThumbCode, 0, this, 0);
    addReference(Reference::KindNamespace::mach_o, Reference::KindArch::ARM,
                 ArchHandler_arm::delta32, 8, &target, 0);
    std::string name = std::string(targetName) + "$shim";
    StringRef tmp(name);
    _name = tmp.copy(file.allocator());
  }

  ~Thumb2ToArmShimAtom() override = default;

  StringRef name() const override {
    return _name;
  }

  ContentType contentType() const override {
    return DefinedAtom::typeCode;
  }

  Alignment alignment() const override { return 4; }

  uint64_t size() const override {
    return 12;
  }

  ContentPermissions permissions() const override {
    return DefinedAtom::permR_X;
  }

  ArrayRef<uint8_t> rawContent() const override {
    static const uint8_t bytes[] =
    { 0xDF, 0xF8, 0x04, 0xC0,       //  ldr ip, pc + 4
      0xFF, 0x44,                   //  add ip, pc, ip
      0x60, 0x47,                   //  ldr pc, [ip]
      0x00, 0x00, 0x00, 0x00 };     //  .long target - this
    assert(sizeof(bytes) == size());
    return llvm::makeArrayRef(bytes, sizeof(bytes));
  }
private:
  StringRef _name;
};

class ArmToThumbShimAtom : public SimpleDefinedAtom {
public:
  ArmToThumbShimAtom(MachOFile &file, StringRef targetName,
                     const DefinedAtom &target)
      : SimpleDefinedAtom(file) {
    addReference(Reference::KindNamespace::mach_o, Reference::KindArch::ARM,
                 ArchHandler_arm::delta32, 12, &target, 0);
    std::string name = std::string(targetName) + "$shim";
    StringRef tmp(name);
    _name = tmp.copy(file.allocator());
  }

  ~ArmToThumbShimAtom() override = default;

  StringRef name() const override {
    return _name;
  }

  ContentType contentType() const override {
    return DefinedAtom::typeCode;
  }

  Alignment alignment() const override { return 4; }

  uint64_t size() const override {
    return 16;
  }

  ContentPermissions permissions() const override {
    return DefinedAtom::permR_X;
  }

  ArrayRef<uint8_t> rawContent() const override {
    static const uint8_t bytes[] =
    { 0x04, 0xC0, 0x9F, 0xE5,       //  ldr ip, pc + 4
      0x0C, 0xC0, 0x8F, 0xE0,       //  add ip, pc, ip
      0x1C, 0xFF, 0x2F, 0xE1,       //  ldr pc, [ip]
      0x00, 0x00, 0x00, 0x00 };     //  .long target - this
    assert(sizeof(bytes) == size());
    return llvm::makeArrayRef(bytes, sizeof(bytes));
  }
private:
  StringRef _name;
};

const DefinedAtom *ArchHandler_arm::createShim(MachOFile &file,
                                               bool thumbToArm,
                                               const DefinedAtom &target) {
  bool isStub = (target.contentType() == DefinedAtom::typeStub);
  StringRef targetName = isStub ? stubName(target) : target.name();
  if (thumbToArm)
    return new (file.allocator()) Thumb2ToArmShimAtom(file, targetName, target);
  else
    return new (file.allocator()) ArmToThumbShimAtom(file, targetName, target);
}

std::unique_ptr<mach_o::ArchHandler> ArchHandler::create_arm() {
  return std::unique_ptr<mach_o::ArchHandler>(new ArchHandler_arm());
}

} // namespace mach_o
} // namespace lld