1 //===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a printer that converts from our internal representation
10 // of machine-dependent LLVM code to GAS-format ARM assembly language.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMAsmPrinter.h"
15 #include "ARM.h"
16 #include "ARMConstantPoolValue.h"
17 #include "ARMMachineFunctionInfo.h"
18 #include "ARMTargetMachine.h"
19 #include "ARMTargetObjectFile.h"
20 #include "InstPrinter/ARMInstPrinter.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "MCTargetDesc/ARMMCExpr.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/BinaryFormat/COFF.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCAssembler.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCELFStreamer.h"
38 #include "llvm/MC/MCInst.h"
39 #include "llvm/MC/MCInstBuilder.h"
40 #include "llvm/MC/MCObjectStreamer.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/Support/ARMBuildAttributes.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/TargetParser.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetMachine.h"
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "asm-printer"
53 
54 ARMAsmPrinter::ARMAsmPrinter(TargetMachine &TM,
55                              std::unique_ptr<MCStreamer> Streamer)
56     : AsmPrinter(TM, std::move(Streamer)), AFI(nullptr), MCP(nullptr),
57       InConstantPool(false), OptimizationGoals(-1) {}
58 
59 void ARMAsmPrinter::EmitFunctionBodyEnd() {
60   // Make sure to terminate any constant pools that were at the end
61   // of the function.
62   if (!InConstantPool)
63     return;
64   InConstantPool = false;
65   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
66 }
67 
68 void ARMAsmPrinter::EmitFunctionEntryLabel() {
69   if (AFI->isThumbFunction()) {
70     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
71     OutStreamer->EmitThumbFunc(CurrentFnSym);
72   } else {
73     OutStreamer->EmitAssemblerFlag(MCAF_Code32);
74   }
75   OutStreamer->EmitLabel(CurrentFnSym);
76 }
77 
78 void ARMAsmPrinter::EmitXXStructor(const DataLayout &DL, const Constant *CV) {
79   uint64_t Size = getDataLayout().getTypeAllocSize(CV->getType());
80   assert(Size && "C++ constructor pointer had zero size!");
81 
82   const GlobalValue *GV = dyn_cast<GlobalValue>(CV->stripPointerCasts());
83   assert(GV && "C++ constructor pointer was not a GlobalValue!");
84 
85   const MCExpr *E = MCSymbolRefExpr::create(GetARMGVSymbol(GV,
86                                                            ARMII::MO_NO_FLAG),
87                                             (Subtarget->isTargetELF()
88                                              ? MCSymbolRefExpr::VK_ARM_TARGET1
89                                              : MCSymbolRefExpr::VK_None),
90                                             OutContext);
91 
92   OutStreamer->EmitValue(E, Size);
93 }
94 
95 void ARMAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
96   if (PromotedGlobals.count(GV))
97     // The global was promoted into a constant pool. It should not be emitted.
98     return;
99   AsmPrinter::EmitGlobalVariable(GV);
100 }
101 
102 /// runOnMachineFunction - This uses the EmitInstruction()
103 /// method to print assembly for each instruction.
104 ///
105 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
106   AFI = MF.getInfo<ARMFunctionInfo>();
107   MCP = MF.getConstantPool();
108   Subtarget = &MF.getSubtarget<ARMSubtarget>();
109 
110   SetupMachineFunction(MF);
111   const Function &F = MF.getFunction();
112   const TargetMachine& TM = MF.getTarget();
113 
114   // Collect all globals that had their storage promoted to a constant pool.
115   // Functions are emitted before variables, so this accumulates promoted
116   // globals from all functions in PromotedGlobals.
117   for (auto *GV : AFI->getGlobalsPromotedToConstantPool())
118     PromotedGlobals.insert(GV);
119 
120   // Calculate this function's optimization goal.
121   unsigned OptimizationGoal;
122   if (F.hasOptNone())
123     // For best debugging illusion, speed and small size sacrificed
124     OptimizationGoal = 6;
125   else if (F.hasMinSize())
126     // Aggressively for small size, speed and debug illusion sacrificed
127     OptimizationGoal = 4;
128   else if (F.hasOptSize())
129     // For small size, but speed and debugging illusion preserved
130     OptimizationGoal = 3;
131   else if (TM.getOptLevel() == CodeGenOpt::Aggressive)
132     // Aggressively for speed, small size and debug illusion sacrificed
133     OptimizationGoal = 2;
134   else if (TM.getOptLevel() > CodeGenOpt::None)
135     // For speed, but small size and good debug illusion preserved
136     OptimizationGoal = 1;
137   else // TM.getOptLevel() == CodeGenOpt::None
138     // For good debugging, but speed and small size preserved
139     OptimizationGoal = 5;
140 
141   // Combine a new optimization goal with existing ones.
142   if (OptimizationGoals == -1) // uninitialized goals
143     OptimizationGoals = OptimizationGoal;
144   else if (OptimizationGoals != (int)OptimizationGoal) // conflicting goals
145     OptimizationGoals = 0;
146 
147   if (Subtarget->isTargetCOFF()) {
148     bool Internal = F.hasInternalLinkage();
149     COFF::SymbolStorageClass Scl = Internal ? COFF::IMAGE_SYM_CLASS_STATIC
150                                             : COFF::IMAGE_SYM_CLASS_EXTERNAL;
151     int Type = COFF::IMAGE_SYM_DTYPE_FUNCTION << COFF::SCT_COMPLEX_TYPE_SHIFT;
152 
153     OutStreamer->BeginCOFFSymbolDef(CurrentFnSym);
154     OutStreamer->EmitCOFFSymbolStorageClass(Scl);
155     OutStreamer->EmitCOFFSymbolType(Type);
156     OutStreamer->EndCOFFSymbolDef();
157   }
158 
159   // Emit the rest of the function body.
160   EmitFunctionBody();
161 
162   // Emit the XRay table for this function.
163   emitXRayTable();
164 
165   // If we need V4T thumb mode Register Indirect Jump pads, emit them.
166   // These are created per function, rather than per TU, since it's
167   // relatively easy to exceed the thumb branch range within a TU.
168   if (! ThumbIndirectPads.empty()) {
169     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
170     EmitAlignment(1);
171     for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
172       OutStreamer->EmitLabel(TIP.second);
173       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
174         .addReg(TIP.first)
175         // Add predicate operands.
176         .addImm(ARMCC::AL)
177         .addReg(0));
178     }
179     ThumbIndirectPads.clear();
180   }
181 
182   // We didn't modify anything.
183   return false;
184 }
185 
186 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
187                                  raw_ostream &O) {
188   const MachineOperand &MO = MI->getOperand(OpNum);
189   unsigned TF = MO.getTargetFlags();
190 
191   switch (MO.getType()) {
192   default: llvm_unreachable("<unknown operand type>");
193   case MachineOperand::MO_Register: {
194     unsigned Reg = MO.getReg();
195     assert(TargetRegisterInfo::isPhysicalRegister(Reg));
196     assert(!MO.getSubReg() && "Subregs should be eliminated!");
197     if(ARM::GPRPairRegClass.contains(Reg)) {
198       const MachineFunction &MF = *MI->getParent()->getParent();
199       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
200       Reg = TRI->getSubReg(Reg, ARM::gsub_0);
201     }
202     O << ARMInstPrinter::getRegisterName(Reg);
203     break;
204   }
205   case MachineOperand::MO_Immediate: {
206     int64_t Imm = MO.getImm();
207     O << '#';
208     if (TF == ARMII::MO_LO16)
209       O << ":lower16:";
210     else if (TF == ARMII::MO_HI16)
211       O << ":upper16:";
212     O << Imm;
213     break;
214   }
215   case MachineOperand::MO_MachineBasicBlock:
216     MO.getMBB()->getSymbol()->print(O, MAI);
217     return;
218   case MachineOperand::MO_GlobalAddress: {
219     const GlobalValue *GV = MO.getGlobal();
220     if (TF & ARMII::MO_LO16)
221       O << ":lower16:";
222     else if (TF & ARMII::MO_HI16)
223       O << ":upper16:";
224     GetARMGVSymbol(GV, TF)->print(O, MAI);
225 
226     printOffset(MO.getOffset(), O);
227     break;
228   }
229   case MachineOperand::MO_ConstantPoolIndex:
230     if (Subtarget->genExecuteOnly())
231       llvm_unreachable("execute-only should not generate constant pools");
232     GetCPISymbol(MO.getIndex())->print(O, MAI);
233     break;
234   }
235 }
236 
237 MCSymbol *ARMAsmPrinter::GetCPISymbol(unsigned CPID) const {
238   // The AsmPrinter::GetCPISymbol superclass method tries to use CPID as
239   // indexes in MachineConstantPool, which isn't in sync with indexes used here.
240   const DataLayout &DL = getDataLayout();
241   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
242                                       "CPI" + Twine(getFunctionNumber()) + "_" +
243                                       Twine(CPID));
244 }
245 
246 //===--------------------------------------------------------------------===//
247 
248 MCSymbol *ARMAsmPrinter::
249 GetARMJTIPICJumpTableLabel(unsigned uid) const {
250   const DataLayout &DL = getDataLayout();
251   SmallString<60> Name;
252   raw_svector_ostream(Name) << DL.getPrivateGlobalPrefix() << "JTI"
253                             << getFunctionNumber() << '_' << uid;
254   return OutContext.getOrCreateSymbol(Name);
255 }
256 
257 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
258                                     const char *ExtraCode, raw_ostream &O) {
259   // Does this asm operand have a single letter operand modifier?
260   if (ExtraCode && ExtraCode[0]) {
261     if (ExtraCode[1] != 0) return true; // Unknown modifier.
262 
263     switch (ExtraCode[0]) {
264     default:
265       // See if this is a generic print operand
266       return AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O);
267     case 'P': // Print a VFP double precision register.
268     case 'q': // Print a NEON quad precision register.
269       printOperand(MI, OpNum, O);
270       return false;
271     case 'y': // Print a VFP single precision register as indexed double.
272       if (MI->getOperand(OpNum).isReg()) {
273         unsigned Reg = MI->getOperand(OpNum).getReg();
274         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
275         // Find the 'd' register that has this 's' register as a sub-register,
276         // and determine the lane number.
277         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
278           if (!ARM::DPRRegClass.contains(*SR))
279             continue;
280           bool Lane0 = TRI->getSubReg(*SR, ARM::ssub_0) == Reg;
281           O << ARMInstPrinter::getRegisterName(*SR) << (Lane0 ? "[0]" : "[1]");
282           return false;
283         }
284       }
285       return true;
286     case 'B': // Bitwise inverse of integer or symbol without a preceding #.
287       if (!MI->getOperand(OpNum).isImm())
288         return true;
289       O << ~(MI->getOperand(OpNum).getImm());
290       return false;
291     case 'L': // The low 16 bits of an immediate constant.
292       if (!MI->getOperand(OpNum).isImm())
293         return true;
294       O << (MI->getOperand(OpNum).getImm() & 0xffff);
295       return false;
296     case 'M': { // A register range suitable for LDM/STM.
297       if (!MI->getOperand(OpNum).isReg())
298         return true;
299       const MachineOperand &MO = MI->getOperand(OpNum);
300       unsigned RegBegin = MO.getReg();
301       // This takes advantage of the 2 operand-ness of ldm/stm and that we've
302       // already got the operands in registers that are operands to the
303       // inline asm statement.
304       O << "{";
305       if (ARM::GPRPairRegClass.contains(RegBegin)) {
306         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
307         unsigned Reg0 = TRI->getSubReg(RegBegin, ARM::gsub_0);
308         O << ARMInstPrinter::getRegisterName(Reg0) << ", ";
309         RegBegin = TRI->getSubReg(RegBegin, ARM::gsub_1);
310       }
311       O << ARMInstPrinter::getRegisterName(RegBegin);
312 
313       // FIXME: The register allocator not only may not have given us the
314       // registers in sequence, but may not be in ascending registers. This
315       // will require changes in the register allocator that'll need to be
316       // propagated down here if the operands change.
317       unsigned RegOps = OpNum + 1;
318       while (MI->getOperand(RegOps).isReg()) {
319         O << ", "
320           << ARMInstPrinter::getRegisterName(MI->getOperand(RegOps).getReg());
321         RegOps++;
322       }
323 
324       O << "}";
325 
326       return false;
327     }
328     case 'R': // The most significant register of a pair.
329     case 'Q': { // The least significant register of a pair.
330       if (OpNum == 0)
331         return true;
332       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
333       if (!FlagsOP.isImm())
334         return true;
335       unsigned Flags = FlagsOP.getImm();
336 
337       // This operand may not be the one that actually provides the register. If
338       // it's tied to a previous one then we should refer instead to that one
339       // for registers and their classes.
340       unsigned TiedIdx;
341       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedIdx)) {
342         for (OpNum = InlineAsm::MIOp_FirstOperand; TiedIdx; --TiedIdx) {
343           unsigned OpFlags = MI->getOperand(OpNum).getImm();
344           OpNum += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
345         }
346         Flags = MI->getOperand(OpNum).getImm();
347 
348         // Later code expects OpNum to be pointing at the register rather than
349         // the flags.
350         OpNum += 1;
351       }
352 
353       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
354       unsigned RC;
355       bool FirstHalf;
356       const ARMBaseTargetMachine &ATM =
357         static_cast<const ARMBaseTargetMachine &>(TM);
358 
359       // 'Q' should correspond to the low order register and 'R' to the high
360       // order register.  Whether this corresponds to the upper or lower half
361       // depends on the endianess mode.
362       if (ExtraCode[0] == 'Q')
363         FirstHalf = ATM.isLittleEndian();
364       else
365         // ExtraCode[0] == 'R'.
366         FirstHalf = !ATM.isLittleEndian();
367       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
368       if (InlineAsm::hasRegClassConstraint(Flags, RC) &&
369           ARM::GPRPairRegClass.hasSubClassEq(TRI->getRegClass(RC))) {
370         if (NumVals != 1)
371           return true;
372         const MachineOperand &MO = MI->getOperand(OpNum);
373         if (!MO.isReg())
374           return true;
375         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
376         unsigned Reg = TRI->getSubReg(MO.getReg(), FirstHalf ?
377             ARM::gsub_0 : ARM::gsub_1);
378         O << ARMInstPrinter::getRegisterName(Reg);
379         return false;
380       }
381       if (NumVals != 2)
382         return true;
383       unsigned RegOp = FirstHalf ? OpNum : OpNum + 1;
384       if (RegOp >= MI->getNumOperands())
385         return true;
386       const MachineOperand &MO = MI->getOperand(RegOp);
387       if (!MO.isReg())
388         return true;
389       unsigned Reg = MO.getReg();
390       O << ARMInstPrinter::getRegisterName(Reg);
391       return false;
392     }
393 
394     case 'e': // The low doubleword register of a NEON quad register.
395     case 'f': { // The high doubleword register of a NEON quad register.
396       if (!MI->getOperand(OpNum).isReg())
397         return true;
398       unsigned Reg = MI->getOperand(OpNum).getReg();
399       if (!ARM::QPRRegClass.contains(Reg))
400         return true;
401       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
402       unsigned SubReg = TRI->getSubReg(Reg, ExtraCode[0] == 'e' ?
403                                        ARM::dsub_0 : ARM::dsub_1);
404       O << ARMInstPrinter::getRegisterName(SubReg);
405       return false;
406     }
407 
408     // This modifier is not yet supported.
409     case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
410       return true;
411     case 'H': { // The highest-numbered register of a pair.
412       const MachineOperand &MO = MI->getOperand(OpNum);
413       if (!MO.isReg())
414         return true;
415       const MachineFunction &MF = *MI->getParent()->getParent();
416       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
417       unsigned Reg = MO.getReg();
418       if(!ARM::GPRPairRegClass.contains(Reg))
419         return false;
420       Reg = TRI->getSubReg(Reg, ARM::gsub_1);
421       O << ARMInstPrinter::getRegisterName(Reg);
422       return false;
423     }
424     }
425   }
426 
427   printOperand(MI, OpNum, O);
428   return false;
429 }
430 
431 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
432                                           unsigned OpNum, const char *ExtraCode,
433                                           raw_ostream &O) {
434   // Does this asm operand have a single letter operand modifier?
435   if (ExtraCode && ExtraCode[0]) {
436     if (ExtraCode[1] != 0) return true; // Unknown modifier.
437 
438     switch (ExtraCode[0]) {
439       case 'A': // A memory operand for a VLD1/VST1 instruction.
440       default: return true;  // Unknown modifier.
441       case 'm': // The base register of a memory operand.
442         if (!MI->getOperand(OpNum).isReg())
443           return true;
444         O << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg());
445         return false;
446     }
447   }
448 
449   const MachineOperand &MO = MI->getOperand(OpNum);
450   assert(MO.isReg() && "unexpected inline asm memory operand");
451   O << "[" << ARMInstPrinter::getRegisterName(MO.getReg()) << "]";
452   return false;
453 }
454 
455 static bool isThumb(const MCSubtargetInfo& STI) {
456   return STI.getFeatureBits()[ARM::ModeThumb];
457 }
458 
459 void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
460                                      const MCSubtargetInfo *EndInfo) const {
461   // If either end mode is unknown (EndInfo == NULL) or different than
462   // the start mode, then restore the start mode.
463   const bool WasThumb = isThumb(StartInfo);
464   if (!EndInfo || WasThumb != isThumb(*EndInfo)) {
465     OutStreamer->EmitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
466   }
467 }
468 
469 void ARMAsmPrinter::EmitStartOfAsmFile(Module &M) {
470   const Triple &TT = TM.getTargetTriple();
471   // Use unified assembler syntax.
472   OutStreamer->EmitAssemblerFlag(MCAF_SyntaxUnified);
473 
474   // Emit ARM Build Attributes
475   if (TT.isOSBinFormatELF())
476     emitAttributes();
477 
478   // Use the triple's architecture and subarchitecture to determine
479   // if we're thumb for the purposes of the top level code16 assembler
480   // flag.
481   if (!M.getModuleInlineAsm().empty() && TT.isThumb())
482     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
483 }
484 
485 static void
486 emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
487                          MachineModuleInfoImpl::StubValueTy &MCSym) {
488   // L_foo$stub:
489   OutStreamer.EmitLabel(StubLabel);
490   //   .indirect_symbol _foo
491   OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
492 
493   if (MCSym.getInt())
494     // External to current translation unit.
495     OutStreamer.EmitIntValue(0, 4/*size*/);
496   else
497     // Internal to current translation unit.
498     //
499     // When we place the LSDA into the TEXT section, the type info
500     // pointers need to be indirect and pc-rel. We accomplish this by
501     // using NLPs; however, sometimes the types are local to the file.
502     // We need to fill in the value for the NLP in those cases.
503     OutStreamer.EmitValue(
504         MCSymbolRefExpr::create(MCSym.getPointer(), OutStreamer.getContext()),
505         4 /*size*/);
506 }
507 
508 
509 void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
510   const Triple &TT = TM.getTargetTriple();
511   if (TT.isOSBinFormatMachO()) {
512     // All darwin targets use mach-o.
513     const TargetLoweringObjectFileMachO &TLOFMacho =
514       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
515     MachineModuleInfoMachO &MMIMacho =
516       MMI->getObjFileInfo<MachineModuleInfoMachO>();
517 
518     // Output non-lazy-pointers for external and common global variables.
519     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
520 
521     if (!Stubs.empty()) {
522       // Switch with ".non_lazy_symbol_pointer" directive.
523       OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
524       EmitAlignment(2);
525 
526       for (auto &Stub : Stubs)
527         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
528 
529       Stubs.clear();
530       OutStreamer->AddBlankLine();
531     }
532 
533     Stubs = MMIMacho.GetThreadLocalGVStubList();
534     if (!Stubs.empty()) {
535       // Switch with ".non_lazy_symbol_pointer" directive.
536       OutStreamer->SwitchSection(TLOFMacho.getThreadLocalPointerSection());
537       EmitAlignment(2);
538 
539       for (auto &Stub : Stubs)
540         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
541 
542       Stubs.clear();
543       OutStreamer->AddBlankLine();
544     }
545 
546     // Funny Darwin hack: This flag tells the linker that no global symbols
547     // contain code that falls through to other global symbols (e.g. the obvious
548     // implementation of multiple entry points).  If this doesn't occur, the
549     // linker can safely perform dead code stripping.  Since LLVM never
550     // generates code that does this, it is always safe to set.
551     OutStreamer->EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
552   }
553 
554   // The last attribute to be emitted is ABI_optimization_goals
555   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
556   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
557 
558   if (OptimizationGoals > 0 &&
559       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
560        Subtarget->isTargetMuslAEABI()))
561     ATS.emitAttribute(ARMBuildAttrs::ABI_optimization_goals, OptimizationGoals);
562   OptimizationGoals = -1;
563 
564   ATS.finishAttributeSection();
565 }
566 
567 //===----------------------------------------------------------------------===//
568 // Helper routines for EmitStartOfAsmFile() and EmitEndOfAsmFile()
569 // FIXME:
570 // The following seem like one-off assembler flags, but they actually need
571 // to appear in the .ARM.attributes section in ELF.
572 // Instead of subclassing the MCELFStreamer, we do the work here.
573 
574 // Returns true if all functions have the same function attribute value.
575 // It also returns true when the module has no functions.
576 static bool checkFunctionsAttributeConsistency(const Module &M, StringRef Attr,
577                                                StringRef Value) {
578   return !any_of(M, [&](const Function &F) {
579     return F.getFnAttribute(Attr).getValueAsString() != Value;
580   });
581 }
582 
583 void ARMAsmPrinter::emitAttributes() {
584   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
585   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
586 
587   ATS.emitTextAttribute(ARMBuildAttrs::conformance, "2.09");
588 
589   ATS.switchVendor("aeabi");
590 
591   // Compute ARM ELF Attributes based on the default subtarget that
592   // we'd have constructed. The existing ARM behavior isn't LTO clean
593   // anyhow.
594   // FIXME: For ifunc related functions we could iterate over and look
595   // for a feature string that doesn't match the default one.
596   const Triple &TT = TM.getTargetTriple();
597   StringRef CPU = TM.getTargetCPU();
598   StringRef FS = TM.getTargetFeatureString();
599   std::string ArchFS = ARM_MC::ParseARMTriple(TT, CPU);
600   if (!FS.empty()) {
601     if (!ArchFS.empty())
602       ArchFS = (Twine(ArchFS) + "," + FS).str();
603     else
604       ArchFS = FS;
605   }
606   const ARMBaseTargetMachine &ATM =
607       static_cast<const ARMBaseTargetMachine &>(TM);
608   const ARMSubtarget STI(TT, CPU, ArchFS, ATM, ATM.isLittleEndian());
609 
610   // Emit build attributes for the available hardware.
611   ATS.emitTargetAttributes(STI);
612 
613   // RW data addressing.
614   if (isPositionIndependent()) {
615     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
616                       ARMBuildAttrs::AddressRWPCRel);
617   } else if (STI.isRWPI()) {
618     // RWPI specific attributes.
619     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
620                       ARMBuildAttrs::AddressRWSBRel);
621   }
622 
623   // RO data addressing.
624   if (isPositionIndependent() || STI.isROPI()) {
625     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
626                       ARMBuildAttrs::AddressROPCRel);
627   }
628 
629   // GOT use.
630   if (isPositionIndependent()) {
631     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
632                       ARMBuildAttrs::AddressGOT);
633   } else {
634     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
635                       ARMBuildAttrs::AddressDirect);
636   }
637 
638   // Set FP Denormals.
639   if (checkFunctionsAttributeConsistency(*MMI->getModule(),
640                                          "denormal-fp-math",
641                                          "preserve-sign") ||
642       TM.Options.FPDenormalMode == FPDenormal::PreserveSign)
643     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
644                       ARMBuildAttrs::PreserveFPSign);
645   else if (checkFunctionsAttributeConsistency(*MMI->getModule(),
646                                               "denormal-fp-math",
647                                               "positive-zero") ||
648            TM.Options.FPDenormalMode == FPDenormal::PositiveZero)
649     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
650                       ARMBuildAttrs::PositiveZero);
651   else if (!TM.Options.UnsafeFPMath)
652     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
653                       ARMBuildAttrs::IEEEDenormals);
654   else {
655     if (!STI.hasVFP2()) {
656       // When the target doesn't have an FPU (by design or
657       // intention), the assumptions made on the software support
658       // mirror that of the equivalent hardware support *if it
659       // existed*. For v7 and better we indicate that denormals are
660       // flushed preserving sign, and for V6 we indicate that
661       // denormals are flushed to positive zero.
662       if (STI.hasV7Ops())
663         ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
664                           ARMBuildAttrs::PreserveFPSign);
665     } else if (STI.hasVFP3()) {
666       // In VFPv4, VFPv4U, VFPv3, or VFPv3U, it is preserved. That is,
667       // the sign bit of the zero matches the sign bit of the input or
668       // result that is being flushed to zero.
669       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
670                         ARMBuildAttrs::PreserveFPSign);
671     }
672     // For VFPv2 implementations it is implementation defined as
673     // to whether denormals are flushed to positive zero or to
674     // whatever the sign of zero is (ARM v7AR ARM 2.7.5). Historically
675     // LLVM has chosen to flush this to positive zero (most likely for
676     // GCC compatibility), so that's the chosen value here (the
677     // absence of its emission implies zero).
678   }
679 
680   // Set FP exceptions and rounding
681   if (checkFunctionsAttributeConsistency(*MMI->getModule(),
682                                          "no-trapping-math", "true") ||
683       TM.Options.NoTrappingFPMath)
684     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
685                       ARMBuildAttrs::Not_Allowed);
686   else if (!TM.Options.UnsafeFPMath) {
687     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions, ARMBuildAttrs::Allowed);
688 
689     // If the user has permitted this code to choose the IEEE 754
690     // rounding at run-time, emit the rounding attribute.
691     if (TM.Options.HonorSignDependentRoundingFPMathOption)
692       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_rounding, ARMBuildAttrs::Allowed);
693   }
694 
695   // TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath is the
696   // equivalent of GCC's -ffinite-math-only flag.
697   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
698     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
699                       ARMBuildAttrs::Allowed);
700   else
701     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
702                       ARMBuildAttrs::AllowIEEE754);
703 
704   // FIXME: add more flags to ARMBuildAttributes.h
705   // 8-bytes alignment stuff.
706   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
707   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
708 
709   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
710   if (STI.isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
711     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
712 
713   // FIXME: To support emitting this build attribute as GCC does, the
714   // -mfp16-format option and associated plumbing must be
715   // supported. For now the __fp16 type is exposed by default, so this
716   // attribute should be emitted with value 1.
717   ATS.emitAttribute(ARMBuildAttrs::ABI_FP_16bit_format,
718                     ARMBuildAttrs::FP16FormatIEEE);
719 
720   if (MMI) {
721     if (const Module *SourceModule = MMI->getModule()) {
722       // ABI_PCS_wchar_t to indicate wchar_t width
723       // FIXME: There is no way to emit value 0 (wchar_t prohibited).
724       if (auto WCharWidthValue = mdconst::extract_or_null<ConstantInt>(
725               SourceModule->getModuleFlag("wchar_size"))) {
726         int WCharWidth = WCharWidthValue->getZExtValue();
727         assert((WCharWidth == 2 || WCharWidth == 4) &&
728                "wchar_t width must be 2 or 4 bytes");
729         ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
730       }
731 
732       // ABI_enum_size to indicate enum width
733       // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
734       //        (all enums contain a value needing 32 bits to encode).
735       if (auto EnumWidthValue = mdconst::extract_or_null<ConstantInt>(
736               SourceModule->getModuleFlag("min_enum_size"))) {
737         int EnumWidth = EnumWidthValue->getZExtValue();
738         assert((EnumWidth == 1 || EnumWidth == 4) &&
739                "Minimum enum width must be 1 or 4 bytes");
740         int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
741         ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
742       }
743     }
744   }
745 
746   // We currently do not support using R9 as the TLS pointer.
747   if (STI.isRWPI())
748     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
749                       ARMBuildAttrs::R9IsSB);
750   else if (STI.isR9Reserved())
751     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
752                       ARMBuildAttrs::R9Reserved);
753   else
754     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
755                       ARMBuildAttrs::R9IsGPR);
756 }
757 
758 //===----------------------------------------------------------------------===//
759 
760 static MCSymbol *getPICLabel(StringRef Prefix, unsigned FunctionNumber,
761                              unsigned LabelId, MCContext &Ctx) {
762 
763   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
764                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
765   return Label;
766 }
767 
768 static MCSymbolRefExpr::VariantKind
769 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
770   switch (Modifier) {
771   case ARMCP::no_modifier:
772     return MCSymbolRefExpr::VK_None;
773   case ARMCP::TLSGD:
774     return MCSymbolRefExpr::VK_TLSGD;
775   case ARMCP::TPOFF:
776     return MCSymbolRefExpr::VK_TPOFF;
777   case ARMCP::GOTTPOFF:
778     return MCSymbolRefExpr::VK_GOTTPOFF;
779   case ARMCP::SBREL:
780     return MCSymbolRefExpr::VK_ARM_SBREL;
781   case ARMCP::GOT_PREL:
782     return MCSymbolRefExpr::VK_ARM_GOT_PREL;
783   case ARMCP::SECREL:
784     return MCSymbolRefExpr::VK_SECREL;
785   }
786   llvm_unreachable("Invalid ARMCPModifier!");
787 }
788 
789 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
790                                         unsigned char TargetFlags) {
791   if (Subtarget->isTargetMachO()) {
792     bool IsIndirect =
793         (TargetFlags & ARMII::MO_NONLAZY) && Subtarget->isGVIndirectSymbol(GV);
794 
795     if (!IsIndirect)
796       return getSymbol(GV);
797 
798     // FIXME: Remove this when Darwin transition to @GOT like syntax.
799     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
800     MachineModuleInfoMachO &MMIMachO =
801       MMI->getObjFileInfo<MachineModuleInfoMachO>();
802     MachineModuleInfoImpl::StubValueTy &StubSym =
803         GV->isThreadLocal() ? MMIMachO.getThreadLocalGVStubEntry(MCSym)
804                             : MMIMachO.getGVStubEntry(MCSym);
805 
806     if (!StubSym.getPointer())
807       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
808                                                    !GV->hasInternalLinkage());
809     return MCSym;
810   } else if (Subtarget->isTargetCOFF()) {
811     assert(Subtarget->isTargetWindows() &&
812            "Windows is the only supported COFF target");
813 
814     bool IsIndirect =
815         (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB));
816     if (!IsIndirect)
817       return getSymbol(GV);
818 
819     SmallString<128> Name;
820     if (TargetFlags & ARMII::MO_DLLIMPORT)
821       Name = "__imp_";
822     else if (TargetFlags & ARMII::MO_COFFSTUB)
823       Name = ".refptr.";
824     getNameWithPrefix(Name, GV);
825 
826     MCSymbol *MCSym = OutContext.getOrCreateSymbol(Name);
827 
828     if (TargetFlags & ARMII::MO_COFFSTUB) {
829       MachineModuleInfoCOFF &MMICOFF =
830           MMI->getObjFileInfo<MachineModuleInfoCOFF>();
831       MachineModuleInfoImpl::StubValueTy &StubSym =
832           MMICOFF.getGVStubEntry(MCSym);
833 
834       if (!StubSym.getPointer())
835         StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV), true);
836     }
837 
838     return MCSym;
839   } else if (Subtarget->isTargetELF()) {
840     return getSymbol(GV);
841   }
842   llvm_unreachable("unexpected target");
843 }
844 
845 void ARMAsmPrinter::
846 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
847   const DataLayout &DL = getDataLayout();
848   int Size = DL.getTypeAllocSize(MCPV->getType());
849 
850   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
851 
852   if (ACPV->isPromotedGlobal()) {
853     // This constant pool entry is actually a global whose storage has been
854     // promoted into the constant pool. This global may be referenced still
855     // by debug information, and due to the way AsmPrinter is set up, the debug
856     // info is immutable by the time we decide to promote globals to constant
857     // pools. Because of this, we need to ensure we emit a symbol for the global
858     // with private linkage (the default) so debug info can refer to it.
859     //
860     // However, if this global is promoted into several functions we must ensure
861     // we don't try and emit duplicate symbols!
862     auto *ACPC = cast<ARMConstantPoolConstant>(ACPV);
863     for (const auto *GV : ACPC->promotedGlobals()) {
864       if (!EmittedPromotedGlobalLabels.count(GV)) {
865         MCSymbol *GVSym = getSymbol(GV);
866         OutStreamer->EmitLabel(GVSym);
867         EmittedPromotedGlobalLabels.insert(GV);
868       }
869     }
870     return EmitGlobalConstant(DL, ACPC->getPromotedGlobalInit());
871   }
872 
873   MCSymbol *MCSym;
874   if (ACPV->isLSDA()) {
875     MCSym = getCurExceptionSym();
876   } else if (ACPV->isBlockAddress()) {
877     const BlockAddress *BA =
878       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
879     MCSym = GetBlockAddressSymbol(BA);
880   } else if (ACPV->isGlobalValue()) {
881     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
882 
883     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
884     // flag the global as MO_NONLAZY.
885     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
886     MCSym = GetARMGVSymbol(GV, TF);
887   } else if (ACPV->isMachineBasicBlock()) {
888     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
889     MCSym = MBB->getSymbol();
890   } else {
891     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
892     auto Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
893     MCSym = GetExternalSymbolSymbol(Sym);
894   }
895 
896   // Create an MCSymbol for the reference.
897   const MCExpr *Expr =
898     MCSymbolRefExpr::create(MCSym, getModifierVariantKind(ACPV->getModifier()),
899                             OutContext);
900 
901   if (ACPV->getPCAdjustment()) {
902     MCSymbol *PCLabel =
903         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
904                     ACPV->getLabelId(), OutContext);
905     const MCExpr *PCRelExpr = MCSymbolRefExpr::create(PCLabel, OutContext);
906     PCRelExpr =
907       MCBinaryExpr::createAdd(PCRelExpr,
908                               MCConstantExpr::create(ACPV->getPCAdjustment(),
909                                                      OutContext),
910                               OutContext);
911     if (ACPV->mustAddCurrentAddress()) {
912       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
913       // label, so just emit a local label end reference that instead.
914       MCSymbol *DotSym = OutContext.createTempSymbol();
915       OutStreamer->EmitLabel(DotSym);
916       const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
917       PCRelExpr = MCBinaryExpr::createSub(PCRelExpr, DotExpr, OutContext);
918     }
919     Expr = MCBinaryExpr::createSub(Expr, PCRelExpr, OutContext);
920   }
921   OutStreamer->EmitValue(Expr, Size);
922 }
923 
924 void ARMAsmPrinter::EmitJumpTableAddrs(const MachineInstr *MI) {
925   const MachineOperand &MO1 = MI->getOperand(1);
926   unsigned JTI = MO1.getIndex();
927 
928   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
929   // ARM mode tables.
930   EmitAlignment(2);
931 
932   // Emit a label for the jump table.
933   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
934   OutStreamer->EmitLabel(JTISymbol);
935 
936   // Mark the jump table as data-in-code.
937   OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
938 
939   // Emit each entry of the table.
940   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
941   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
942   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
943 
944   for (MachineBasicBlock *MBB : JTBBs) {
945     // Construct an MCExpr for the entry. We want a value of the form:
946     // (BasicBlockAddr - TableBeginAddr)
947     //
948     // For example, a table with entries jumping to basic blocks BB0 and BB1
949     // would look like:
950     // LJTI_0_0:
951     //    .word (LBB0 - LJTI_0_0)
952     //    .word (LBB1 - LJTI_0_0)
953     const MCExpr *Expr = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
954 
955     if (isPositionIndependent() || Subtarget->isROPI())
956       Expr = MCBinaryExpr::createSub(Expr, MCSymbolRefExpr::create(JTISymbol,
957                                                                    OutContext),
958                                      OutContext);
959     // If we're generating a table of Thumb addresses in static relocation
960     // model, we need to add one to keep interworking correctly.
961     else if (AFI->isThumbFunction())
962       Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(1,OutContext),
963                                      OutContext);
964     OutStreamer->EmitValue(Expr, 4);
965   }
966   // Mark the end of jump table data-in-code region.
967   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
968 }
969 
970 void ARMAsmPrinter::EmitJumpTableInsts(const MachineInstr *MI) {
971   const MachineOperand &MO1 = MI->getOperand(1);
972   unsigned JTI = MO1.getIndex();
973 
974   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
975   // ARM mode tables.
976   EmitAlignment(2);
977 
978   // Emit a label for the jump table.
979   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
980   OutStreamer->EmitLabel(JTISymbol);
981 
982   // Emit each entry of the table.
983   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
984   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
985   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
986 
987   for (MachineBasicBlock *MBB : JTBBs) {
988     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
989                                                           OutContext);
990     // If this isn't a TBB or TBH, the entries are direct branch instructions.
991     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2B)
992         .addExpr(MBBSymbolExpr)
993         .addImm(ARMCC::AL)
994         .addReg(0));
995   }
996 }
997 
998 void ARMAsmPrinter::EmitJumpTableTBInst(const MachineInstr *MI,
999                                         unsigned OffsetWidth) {
1000   assert((OffsetWidth == 1 || OffsetWidth == 2) && "invalid tbb/tbh width");
1001   const MachineOperand &MO1 = MI->getOperand(1);
1002   unsigned JTI = MO1.getIndex();
1003 
1004   if (Subtarget->isThumb1Only())
1005     EmitAlignment(2);
1006 
1007   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1008   OutStreamer->EmitLabel(JTISymbol);
1009 
1010   // Emit each entry of the table.
1011   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1012   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1013   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1014 
1015   // Mark the jump table as data-in-code.
1016   OutStreamer->EmitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
1017                                                : MCDR_DataRegionJT16);
1018 
1019   for (auto MBB : JTBBs) {
1020     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1021                                                           OutContext);
1022     // Otherwise it's an offset from the dispatch instruction. Construct an
1023     // MCExpr for the entry. We want a value of the form:
1024     // (BasicBlockAddr - TBBInstAddr + 4) / 2
1025     //
1026     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1027     // would look like:
1028     // LJTI_0_0:
1029     //    .byte (LBB0 - (LCPI0_0 + 4)) / 2
1030     //    .byte (LBB1 - (LCPI0_0 + 4)) / 2
1031     // where LCPI0_0 is a label defined just before the TBB instruction using
1032     // this table.
1033     MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
1034     const MCExpr *Expr = MCBinaryExpr::createAdd(
1035         MCSymbolRefExpr::create(TBInstPC, OutContext),
1036         MCConstantExpr::create(4, OutContext), OutContext);
1037     Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
1038     Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
1039                                    OutContext);
1040     OutStreamer->EmitValue(Expr, OffsetWidth);
1041   }
1042   // Mark the end of jump table data-in-code region. 32-bit offsets use
1043   // actual branch instructions here, so we don't mark those as a data-region
1044   // at all.
1045   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1046 
1047   // Make sure the next instruction is 2-byte aligned.
1048   EmitAlignment(1);
1049 }
1050 
1051 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1052   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1053       "Only instruction which are involved into frame setup code are allowed");
1054 
1055   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1056   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1057   const MachineFunction &MF = *MI->getParent()->getParent();
1058   const TargetRegisterInfo *TargetRegInfo =
1059     MF.getSubtarget().getRegisterInfo();
1060   const MachineRegisterInfo &MachineRegInfo = MF.getRegInfo();
1061   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
1062 
1063   unsigned FramePtr = TargetRegInfo->getFrameRegister(MF);
1064   unsigned Opc = MI->getOpcode();
1065   unsigned SrcReg, DstReg;
1066 
1067   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1068     // Two special cases:
1069     // 1) tPUSH does not have src/dst regs.
1070     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1071     // load. Yes, this is pretty fragile, but for now I don't see better
1072     // way... :(
1073     SrcReg = DstReg = ARM::SP;
1074   } else {
1075     SrcReg = MI->getOperand(1).getReg();
1076     DstReg = MI->getOperand(0).getReg();
1077   }
1078 
1079   // Try to figure out the unwinding opcode out of src / dst regs.
1080   if (MI->mayStore()) {
1081     // Register saves.
1082     assert(DstReg == ARM::SP &&
1083            "Only stack pointer as a destination reg is supported");
1084 
1085     SmallVector<unsigned, 4> RegList;
1086     // Skip src & dst reg, and pred ops.
1087     unsigned StartOp = 2 + 2;
1088     // Use all the operands.
1089     unsigned NumOffset = 0;
1090     // Amount of SP adjustment folded into a push.
1091     unsigned Pad = 0;
1092 
1093     switch (Opc) {
1094     default:
1095       MI->print(errs());
1096       llvm_unreachable("Unsupported opcode for unwinding information");
1097     case ARM::tPUSH:
1098       // Special case here: no src & dst reg, but two extra imp ops.
1099       StartOp = 2; NumOffset = 2;
1100       LLVM_FALLTHROUGH;
1101     case ARM::STMDB_UPD:
1102     case ARM::t2STMDB_UPD:
1103     case ARM::VSTMDDB_UPD:
1104       assert(SrcReg == ARM::SP &&
1105              "Only stack pointer as a source reg is supported");
1106       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1107            i != NumOps; ++i) {
1108         const MachineOperand &MO = MI->getOperand(i);
1109         // Actually, there should never be any impdef stuff here. Skip it
1110         // temporary to workaround PR11902.
1111         if (MO.isImplicit())
1112           continue;
1113         // Registers, pushed as a part of folding an SP update into the
1114         // push instruction are marked as undef and should not be
1115         // restored when unwinding, because the function can modify the
1116         // corresponding stack slots.
1117         if (MO.isUndef()) {
1118           assert(RegList.empty() &&
1119                  "Pad registers must come before restored ones");
1120           unsigned Width =
1121             TargetRegInfo->getRegSizeInBits(MO.getReg(), MachineRegInfo) / 8;
1122           Pad += Width;
1123           continue;
1124         }
1125         RegList.push_back(MO.getReg());
1126       }
1127       break;
1128     case ARM::STR_PRE_IMM:
1129     case ARM::STR_PRE_REG:
1130     case ARM::t2STR_PRE:
1131       assert(MI->getOperand(2).getReg() == ARM::SP &&
1132              "Only stack pointer as a source reg is supported");
1133       RegList.push_back(SrcReg);
1134       break;
1135     }
1136     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1137       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1138       // Account for the SP adjustment, folded into the push.
1139       if (Pad)
1140         ATS.emitPad(Pad);
1141     }
1142   } else {
1143     // Changes of stack / frame pointer.
1144     if (SrcReg == ARM::SP) {
1145       int64_t Offset = 0;
1146       switch (Opc) {
1147       default:
1148         MI->print(errs());
1149         llvm_unreachable("Unsupported opcode for unwinding information");
1150       case ARM::MOVr:
1151       case ARM::tMOVr:
1152         Offset = 0;
1153         break;
1154       case ARM::ADDri:
1155       case ARM::t2ADDri:
1156         Offset = -MI->getOperand(2).getImm();
1157         break;
1158       case ARM::SUBri:
1159       case ARM::t2SUBri:
1160         Offset = MI->getOperand(2).getImm();
1161         break;
1162       case ARM::tSUBspi:
1163         Offset = MI->getOperand(2).getImm()*4;
1164         break;
1165       case ARM::tADDspi:
1166       case ARM::tADDrSPi:
1167         Offset = -MI->getOperand(2).getImm()*4;
1168         break;
1169       case ARM::tLDRpci: {
1170         // Grab the constpool index and check, whether it corresponds to
1171         // original or cloned constpool entry.
1172         unsigned CPI = MI->getOperand(1).getIndex();
1173         const MachineConstantPool *MCP = MF.getConstantPool();
1174         if (CPI >= MCP->getConstants().size())
1175           CPI = AFI.getOriginalCPIdx(CPI);
1176         assert(CPI != -1U && "Invalid constpool index");
1177 
1178         // Derive the actual offset.
1179         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1180         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1181         // FIXME: Check for user, it should be "add" instruction!
1182         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1183         break;
1184       }
1185       }
1186 
1187       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1188         if (DstReg == FramePtr && FramePtr != ARM::SP)
1189           // Set-up of the frame pointer. Positive values correspond to "add"
1190           // instruction.
1191           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1192         else if (DstReg == ARM::SP) {
1193           // Change of SP by an offset. Positive values correspond to "sub"
1194           // instruction.
1195           ATS.emitPad(Offset);
1196         } else {
1197           // Move of SP to a register.  Positive values correspond to an "add"
1198           // instruction.
1199           ATS.emitMovSP(DstReg, -Offset);
1200         }
1201       }
1202     } else if (DstReg == ARM::SP) {
1203       MI->print(errs());
1204       llvm_unreachable("Unsupported opcode for unwinding information");
1205     }
1206     else {
1207       MI->print(errs());
1208       llvm_unreachable("Unsupported opcode for unwinding information");
1209     }
1210   }
1211 }
1212 
1213 // Simple pseudo-instructions have their lowering (with expansion to real
1214 // instructions) auto-generated.
1215 #include "ARMGenMCPseudoLowering.inc"
1216 
1217 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1218   const DataLayout &DL = getDataLayout();
1219   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1220   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1221 
1222   const MachineFunction &MF = *MI->getParent()->getParent();
1223   const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>();
1224   unsigned FramePtr = STI.useR7AsFramePointer() ? ARM::R7 : ARM::R11;
1225 
1226   // If we just ended a constant pool, mark it as such.
1227   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1228     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1229     InConstantPool = false;
1230   }
1231 
1232   // Emit unwinding stuff for frame-related instructions
1233   if (Subtarget->isTargetEHABICompatible() &&
1234        MI->getFlag(MachineInstr::FrameSetup))
1235     EmitUnwindingInstruction(MI);
1236 
1237   // Do any auto-generated pseudo lowerings.
1238   if (emitPseudoExpansionLowering(*OutStreamer, MI))
1239     return;
1240 
1241   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1242          "Pseudo flag setting opcode should be expanded early");
1243 
1244   // Check for manual lowerings.
1245   unsigned Opc = MI->getOpcode();
1246   switch (Opc) {
1247   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1248   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1249   case ARM::LEApcrel:
1250   case ARM::tLEApcrel:
1251   case ARM::t2LEApcrel: {
1252     // FIXME: Need to also handle globals and externals
1253     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1254     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1255                                                ARM::t2LEApcrel ? ARM::t2ADR
1256                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1257                      : ARM::ADR))
1258       .addReg(MI->getOperand(0).getReg())
1259       .addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
1260       // Add predicate operands.
1261       .addImm(MI->getOperand(2).getImm())
1262       .addReg(MI->getOperand(3).getReg()));
1263     return;
1264   }
1265   case ARM::LEApcrelJT:
1266   case ARM::tLEApcrelJT:
1267   case ARM::t2LEApcrelJT: {
1268     MCSymbol *JTIPICSymbol =
1269       GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
1270     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1271                                                ARM::t2LEApcrelJT ? ARM::t2ADR
1272                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1273                      : ARM::ADR))
1274       .addReg(MI->getOperand(0).getReg())
1275       .addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
1276       // Add predicate operands.
1277       .addImm(MI->getOperand(2).getImm())
1278       .addReg(MI->getOperand(3).getReg()));
1279     return;
1280   }
1281   // Darwin call instructions are just normal call instructions with different
1282   // clobber semantics (they clobber R9).
1283   case ARM::BX_CALL: {
1284     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1285       .addReg(ARM::LR)
1286       .addReg(ARM::PC)
1287       // Add predicate operands.
1288       .addImm(ARMCC::AL)
1289       .addReg(0)
1290       // Add 's' bit operand (always reg0 for this)
1291       .addReg(0));
1292 
1293     assert(Subtarget->hasV4TOps());
1294     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1295       .addReg(MI->getOperand(0).getReg()));
1296     return;
1297   }
1298   case ARM::tBX_CALL: {
1299     if (Subtarget->hasV5TOps())
1300       llvm_unreachable("Expected BLX to be selected for v5t+");
1301 
1302     // On ARM v4t, when doing a call from thumb mode, we need to ensure
1303     // that the saved lr has its LSB set correctly (the arch doesn't
1304     // have blx).
1305     // So here we generate a bl to a small jump pad that does bx rN.
1306     // The jump pads are emitted after the function body.
1307 
1308     unsigned TReg = MI->getOperand(0).getReg();
1309     MCSymbol *TRegSym = nullptr;
1310     for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
1311       if (TIP.first == TReg) {
1312         TRegSym = TIP.second;
1313         break;
1314       }
1315     }
1316 
1317     if (!TRegSym) {
1318       TRegSym = OutContext.createTempSymbol();
1319       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
1320     }
1321 
1322     // Create a link-saving branch to the Reg Indirect Jump Pad.
1323     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
1324         // Predicate comes first here.
1325         .addImm(ARMCC::AL).addReg(0)
1326         .addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
1327     return;
1328   }
1329   case ARM::BMOVPCRX_CALL: {
1330     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1331       .addReg(ARM::LR)
1332       .addReg(ARM::PC)
1333       // Add predicate operands.
1334       .addImm(ARMCC::AL)
1335       .addReg(0)
1336       // Add 's' bit operand (always reg0 for this)
1337       .addReg(0));
1338 
1339     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1340       .addReg(ARM::PC)
1341       .addReg(MI->getOperand(0).getReg())
1342       // Add predicate operands.
1343       .addImm(ARMCC::AL)
1344       .addReg(0)
1345       // Add 's' bit operand (always reg0 for this)
1346       .addReg(0));
1347     return;
1348   }
1349   case ARM::BMOVPCB_CALL: {
1350     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1351       .addReg(ARM::LR)
1352       .addReg(ARM::PC)
1353       // Add predicate operands.
1354       .addImm(ARMCC::AL)
1355       .addReg(0)
1356       // Add 's' bit operand (always reg0 for this)
1357       .addReg(0));
1358 
1359     const MachineOperand &Op = MI->getOperand(0);
1360     const GlobalValue *GV = Op.getGlobal();
1361     const unsigned TF = Op.getTargetFlags();
1362     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1363     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1364     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
1365       .addExpr(GVSymExpr)
1366       // Add predicate operands.
1367       .addImm(ARMCC::AL)
1368       .addReg(0));
1369     return;
1370   }
1371   case ARM::MOVi16_ga_pcrel:
1372   case ARM::t2MOVi16_ga_pcrel: {
1373     MCInst TmpInst;
1374     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1375     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1376 
1377     unsigned TF = MI->getOperand(1).getTargetFlags();
1378     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1379     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1380     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1381 
1382     MCSymbol *LabelSym =
1383         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1384                     MI->getOperand(2).getImm(), OutContext);
1385     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1386     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1387     const MCExpr *PCRelExpr =
1388       ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
1389                                       MCBinaryExpr::createAdd(LabelSymExpr,
1390                                       MCConstantExpr::create(PCAdj, OutContext),
1391                                       OutContext), OutContext), OutContext);
1392       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1393 
1394     // Add predicate operands.
1395     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1396     TmpInst.addOperand(MCOperand::createReg(0));
1397     // Add 's' bit operand (always reg0 for this)
1398     TmpInst.addOperand(MCOperand::createReg(0));
1399     EmitToStreamer(*OutStreamer, TmpInst);
1400     return;
1401   }
1402   case ARM::MOVTi16_ga_pcrel:
1403   case ARM::t2MOVTi16_ga_pcrel: {
1404     MCInst TmpInst;
1405     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1406                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1407     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1408     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1409 
1410     unsigned TF = MI->getOperand(2).getTargetFlags();
1411     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1412     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1413     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1414 
1415     MCSymbol *LabelSym =
1416         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1417                     MI->getOperand(3).getImm(), OutContext);
1418     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1419     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1420     const MCExpr *PCRelExpr =
1421         ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
1422                                    MCBinaryExpr::createAdd(LabelSymExpr,
1423                                       MCConstantExpr::create(PCAdj, OutContext),
1424                                           OutContext), OutContext), OutContext);
1425       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1426     // Add predicate operands.
1427     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1428     TmpInst.addOperand(MCOperand::createReg(0));
1429     // Add 's' bit operand (always reg0 for this)
1430     TmpInst.addOperand(MCOperand::createReg(0));
1431     EmitToStreamer(*OutStreamer, TmpInst);
1432     return;
1433   }
1434   case ARM::tPICADD: {
1435     // This is a pseudo op for a label + instruction sequence, which looks like:
1436     // LPC0:
1437     //     add r0, pc
1438     // This adds the address of LPC0 to r0.
1439 
1440     // Emit the label.
1441     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1442                                        getFunctionNumber(),
1443                                        MI->getOperand(2).getImm(), OutContext));
1444 
1445     // Form and emit the add.
1446     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1447       .addReg(MI->getOperand(0).getReg())
1448       .addReg(MI->getOperand(0).getReg())
1449       .addReg(ARM::PC)
1450       // Add predicate operands.
1451       .addImm(ARMCC::AL)
1452       .addReg(0));
1453     return;
1454   }
1455   case ARM::PICADD: {
1456     // This is a pseudo op for a label + instruction sequence, which looks like:
1457     // LPC0:
1458     //     add r0, pc, r0
1459     // This adds the address of LPC0 to r0.
1460 
1461     // Emit the label.
1462     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1463                                        getFunctionNumber(),
1464                                        MI->getOperand(2).getImm(), OutContext));
1465 
1466     // Form and emit the add.
1467     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1468       .addReg(MI->getOperand(0).getReg())
1469       .addReg(ARM::PC)
1470       .addReg(MI->getOperand(1).getReg())
1471       // Add predicate operands.
1472       .addImm(MI->getOperand(3).getImm())
1473       .addReg(MI->getOperand(4).getReg())
1474       // Add 's' bit operand (always reg0 for this)
1475       .addReg(0));
1476     return;
1477   }
1478   case ARM::PICSTR:
1479   case ARM::PICSTRB:
1480   case ARM::PICSTRH:
1481   case ARM::PICLDR:
1482   case ARM::PICLDRB:
1483   case ARM::PICLDRH:
1484   case ARM::PICLDRSB:
1485   case ARM::PICLDRSH: {
1486     // This is a pseudo op for a label + instruction sequence, which looks like:
1487     // LPC0:
1488     //     OP r0, [pc, r0]
1489     // The LCP0 label is referenced by a constant pool entry in order to get
1490     // a PC-relative address at the ldr instruction.
1491 
1492     // Emit the label.
1493     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1494                                        getFunctionNumber(),
1495                                        MI->getOperand(2).getImm(), OutContext));
1496 
1497     // Form and emit the load
1498     unsigned Opcode;
1499     switch (MI->getOpcode()) {
1500     default:
1501       llvm_unreachable("Unexpected opcode!");
1502     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1503     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1504     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1505     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1506     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1507     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1508     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1509     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1510     }
1511     EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
1512       .addReg(MI->getOperand(0).getReg())
1513       .addReg(ARM::PC)
1514       .addReg(MI->getOperand(1).getReg())
1515       .addImm(0)
1516       // Add predicate operands.
1517       .addImm(MI->getOperand(3).getImm())
1518       .addReg(MI->getOperand(4).getReg()));
1519 
1520     return;
1521   }
1522   case ARM::CONSTPOOL_ENTRY: {
1523     if (Subtarget->genExecuteOnly())
1524       llvm_unreachable("execute-only should not generate constant pools");
1525 
1526     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1527     /// in the function.  The first operand is the ID# for this instruction, the
1528     /// second is the index into the MachineConstantPool that this is, the third
1529     /// is the size in bytes of this constant pool entry.
1530     /// The required alignment is specified on the basic block holding this MI.
1531     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1532     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1533 
1534     // If this is the first entry of the pool, mark it.
1535     if (!InConstantPool) {
1536       OutStreamer->EmitDataRegion(MCDR_DataRegion);
1537       InConstantPool = true;
1538     }
1539 
1540     OutStreamer->EmitLabel(GetCPISymbol(LabelId));
1541 
1542     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1543     if (MCPE.isMachineConstantPoolEntry())
1544       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1545     else
1546       EmitGlobalConstant(DL, MCPE.Val.ConstVal);
1547     return;
1548   }
1549   case ARM::JUMPTABLE_ADDRS:
1550     EmitJumpTableAddrs(MI);
1551     return;
1552   case ARM::JUMPTABLE_INSTS:
1553     EmitJumpTableInsts(MI);
1554     return;
1555   case ARM::JUMPTABLE_TBB:
1556   case ARM::JUMPTABLE_TBH:
1557     EmitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
1558     return;
1559   case ARM::t2BR_JT: {
1560     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1561       .addReg(ARM::PC)
1562       .addReg(MI->getOperand(0).getReg())
1563       // Add predicate operands.
1564       .addImm(ARMCC::AL)
1565       .addReg(0));
1566     return;
1567   }
1568   case ARM::t2TBB_JT:
1569   case ARM::t2TBH_JT: {
1570     unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
1571     // Lower and emit the PC label, then the instruction itself.
1572     OutStreamer->EmitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1573     EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1574                                      .addReg(MI->getOperand(0).getReg())
1575                                      .addReg(MI->getOperand(1).getReg())
1576                                      // Add predicate operands.
1577                                      .addImm(ARMCC::AL)
1578                                      .addReg(0));
1579     return;
1580   }
1581   case ARM::tTBB_JT:
1582   case ARM::tTBH_JT: {
1583 
1584     bool Is8Bit = MI->getOpcode() == ARM::tTBB_JT;
1585     unsigned Base = MI->getOperand(0).getReg();
1586     unsigned Idx = MI->getOperand(1).getReg();
1587     assert(MI->getOperand(1).isKill() && "We need the index register as scratch!");
1588 
1589     // Multiply up idx if necessary.
1590     if (!Is8Bit)
1591       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1592                                        .addReg(Idx)
1593                                        .addReg(ARM::CPSR)
1594                                        .addReg(Idx)
1595                                        .addImm(1)
1596                                        // Add predicate operands.
1597                                        .addImm(ARMCC::AL)
1598                                        .addReg(0));
1599 
1600     if (Base == ARM::PC) {
1601       // TBB [base, idx] =
1602       //    ADDS idx, idx, base
1603       //    LDRB idx, [idx, #4] ; or LDRH if TBH
1604       //    LSLS idx, #1
1605       //    ADDS pc, pc, idx
1606 
1607       // When using PC as the base, it's important that there is no padding
1608       // between the last ADDS and the start of the jump table. The jump table
1609       // is 4-byte aligned, so we ensure we're 4 byte aligned here too.
1610       //
1611       // FIXME: Ideally we could vary the LDRB index based on the padding
1612       // between the sequence and jump table, however that relies on MCExprs
1613       // for load indexes which are currently not supported.
1614       OutStreamer->EmitCodeAlignment(4);
1615       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1616                                        .addReg(Idx)
1617                                        .addReg(Idx)
1618                                        .addReg(Base)
1619                                        // Add predicate operands.
1620                                        .addImm(ARMCC::AL)
1621                                        .addReg(0));
1622 
1623       unsigned Opc = Is8Bit ? ARM::tLDRBi : ARM::tLDRHi;
1624       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1625                                        .addReg(Idx)
1626                                        .addReg(Idx)
1627                                        .addImm(Is8Bit ? 4 : 2)
1628                                        // Add predicate operands.
1629                                        .addImm(ARMCC::AL)
1630                                        .addReg(0));
1631     } else {
1632       // TBB [base, idx] =
1633       //    LDRB idx, [base, idx] ; or LDRH if TBH
1634       //    LSLS idx, #1
1635       //    ADDS pc, pc, idx
1636 
1637       unsigned Opc = Is8Bit ? ARM::tLDRBr : ARM::tLDRHr;
1638       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1639                                        .addReg(Idx)
1640                                        .addReg(Base)
1641                                        .addReg(Idx)
1642                                        // Add predicate operands.
1643                                        .addImm(ARMCC::AL)
1644                                        .addReg(0));
1645     }
1646 
1647     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1648                                      .addReg(Idx)
1649                                      .addReg(ARM::CPSR)
1650                                      .addReg(Idx)
1651                                      .addImm(1)
1652                                      // Add predicate operands.
1653                                      .addImm(ARMCC::AL)
1654                                      .addReg(0));
1655 
1656     OutStreamer->EmitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1657     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1658                                      .addReg(ARM::PC)
1659                                      .addReg(ARM::PC)
1660                                      .addReg(Idx)
1661                                      // Add predicate operands.
1662                                      .addImm(ARMCC::AL)
1663                                      .addReg(0));
1664     return;
1665   }
1666   case ARM::tBR_JTr:
1667   case ARM::BR_JTr: {
1668     // mov pc, target
1669     MCInst TmpInst;
1670     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1671       ARM::MOVr : ARM::tMOVr;
1672     TmpInst.setOpcode(Opc);
1673     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1674     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1675     // Add predicate operands.
1676     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1677     TmpInst.addOperand(MCOperand::createReg(0));
1678     // Add 's' bit operand (always reg0 for this)
1679     if (Opc == ARM::MOVr)
1680       TmpInst.addOperand(MCOperand::createReg(0));
1681     EmitToStreamer(*OutStreamer, TmpInst);
1682     return;
1683   }
1684   case ARM::BR_JTm_i12: {
1685     // ldr pc, target
1686     MCInst TmpInst;
1687     TmpInst.setOpcode(ARM::LDRi12);
1688     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1689     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1690     TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1691     // Add predicate operands.
1692     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1693     TmpInst.addOperand(MCOperand::createReg(0));
1694     EmitToStreamer(*OutStreamer, TmpInst);
1695     return;
1696   }
1697   case ARM::BR_JTm_rs: {
1698     // ldr pc, target
1699     MCInst TmpInst;
1700     TmpInst.setOpcode(ARM::LDRrs);
1701     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1702     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1703     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1704     TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1705     // Add predicate operands.
1706     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1707     TmpInst.addOperand(MCOperand::createReg(0));
1708     EmitToStreamer(*OutStreamer, TmpInst);
1709     return;
1710   }
1711   case ARM::BR_JTadd: {
1712     // add pc, target, idx
1713     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1714       .addReg(ARM::PC)
1715       .addReg(MI->getOperand(0).getReg())
1716       .addReg(MI->getOperand(1).getReg())
1717       // Add predicate operands.
1718       .addImm(ARMCC::AL)
1719       .addReg(0)
1720       // Add 's' bit operand (always reg0 for this)
1721       .addReg(0));
1722     return;
1723   }
1724   case ARM::SPACE:
1725     OutStreamer->EmitZeros(MI->getOperand(1).getImm());
1726     return;
1727   case ARM::TRAP: {
1728     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1729     // FIXME: Remove this special case when they do.
1730     if (!Subtarget->isTargetMachO()) {
1731       uint32_t Val = 0xe7ffdefeUL;
1732       OutStreamer->AddComment("trap");
1733       ATS.emitInst(Val);
1734       return;
1735     }
1736     break;
1737   }
1738   case ARM::TRAPNaCl: {
1739     uint32_t Val = 0xe7fedef0UL;
1740     OutStreamer->AddComment("trap");
1741     ATS.emitInst(Val);
1742     return;
1743   }
1744   case ARM::tTRAP: {
1745     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1746     // FIXME: Remove this special case when they do.
1747     if (!Subtarget->isTargetMachO()) {
1748       uint16_t Val = 0xdefe;
1749       OutStreamer->AddComment("trap");
1750       ATS.emitInst(Val, 'n');
1751       return;
1752     }
1753     break;
1754   }
1755   case ARM::t2Int_eh_sjlj_setjmp:
1756   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1757   case ARM::tInt_eh_sjlj_setjmp: {
1758     // Two incoming args: GPR:$src, GPR:$val
1759     // mov $val, pc
1760     // adds $val, #7
1761     // str $val, [$src, #4]
1762     // movs r0, #0
1763     // b LSJLJEH
1764     // movs r0, #1
1765     // LSJLJEH:
1766     unsigned SrcReg = MI->getOperand(0).getReg();
1767     unsigned ValReg = MI->getOperand(1).getReg();
1768     MCSymbol *Label = OutContext.createTempSymbol("SJLJEH", false, true);
1769     OutStreamer->AddComment("eh_setjmp begin");
1770     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1771       .addReg(ValReg)
1772       .addReg(ARM::PC)
1773       // Predicate.
1774       .addImm(ARMCC::AL)
1775       .addReg(0));
1776 
1777     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
1778       .addReg(ValReg)
1779       // 's' bit operand
1780       .addReg(ARM::CPSR)
1781       .addReg(ValReg)
1782       .addImm(7)
1783       // Predicate.
1784       .addImm(ARMCC::AL)
1785       .addReg(0));
1786 
1787     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
1788       .addReg(ValReg)
1789       .addReg(SrcReg)
1790       // The offset immediate is #4. The operand value is scaled by 4 for the
1791       // tSTR instruction.
1792       .addImm(1)
1793       // Predicate.
1794       .addImm(ARMCC::AL)
1795       .addReg(0));
1796 
1797     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1798       .addReg(ARM::R0)
1799       .addReg(ARM::CPSR)
1800       .addImm(0)
1801       // Predicate.
1802       .addImm(ARMCC::AL)
1803       .addReg(0));
1804 
1805     const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
1806     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
1807       .addExpr(SymbolExpr)
1808       .addImm(ARMCC::AL)
1809       .addReg(0));
1810 
1811     OutStreamer->AddComment("eh_setjmp end");
1812     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1813       .addReg(ARM::R0)
1814       .addReg(ARM::CPSR)
1815       .addImm(1)
1816       // Predicate.
1817       .addImm(ARMCC::AL)
1818       .addReg(0));
1819 
1820     OutStreamer->EmitLabel(Label);
1821     return;
1822   }
1823 
1824   case ARM::Int_eh_sjlj_setjmp_nofp:
1825   case ARM::Int_eh_sjlj_setjmp: {
1826     // Two incoming args: GPR:$src, GPR:$val
1827     // add $val, pc, #8
1828     // str $val, [$src, #+4]
1829     // mov r0, #0
1830     // add pc, pc, #0
1831     // mov r0, #1
1832     unsigned SrcReg = MI->getOperand(0).getReg();
1833     unsigned ValReg = MI->getOperand(1).getReg();
1834 
1835     OutStreamer->AddComment("eh_setjmp begin");
1836     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1837       .addReg(ValReg)
1838       .addReg(ARM::PC)
1839       .addImm(8)
1840       // Predicate.
1841       .addImm(ARMCC::AL)
1842       .addReg(0)
1843       // 's' bit operand (always reg0 for this).
1844       .addReg(0));
1845 
1846     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
1847       .addReg(ValReg)
1848       .addReg(SrcReg)
1849       .addImm(4)
1850       // Predicate.
1851       .addImm(ARMCC::AL)
1852       .addReg(0));
1853 
1854     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1855       .addReg(ARM::R0)
1856       .addImm(0)
1857       // Predicate.
1858       .addImm(ARMCC::AL)
1859       .addReg(0)
1860       // 's' bit operand (always reg0 for this).
1861       .addReg(0));
1862 
1863     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1864       .addReg(ARM::PC)
1865       .addReg(ARM::PC)
1866       .addImm(0)
1867       // Predicate.
1868       .addImm(ARMCC::AL)
1869       .addReg(0)
1870       // 's' bit operand (always reg0 for this).
1871       .addReg(0));
1872 
1873     OutStreamer->AddComment("eh_setjmp end");
1874     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1875       .addReg(ARM::R0)
1876       .addImm(1)
1877       // Predicate.
1878       .addImm(ARMCC::AL)
1879       .addReg(0)
1880       // 's' bit operand (always reg0 for this).
1881       .addReg(0));
1882     return;
1883   }
1884   case ARM::Int_eh_sjlj_longjmp: {
1885     // ldr sp, [$src, #8]
1886     // ldr $scratch, [$src, #4]
1887     // ldr r7, [$src]
1888     // bx $scratch
1889     unsigned SrcReg = MI->getOperand(0).getReg();
1890     unsigned ScratchReg = MI->getOperand(1).getReg();
1891     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1892       .addReg(ARM::SP)
1893       .addReg(SrcReg)
1894       .addImm(8)
1895       // Predicate.
1896       .addImm(ARMCC::AL)
1897       .addReg(0));
1898 
1899     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1900       .addReg(ScratchReg)
1901       .addReg(SrcReg)
1902       .addImm(4)
1903       // Predicate.
1904       .addImm(ARMCC::AL)
1905       .addReg(0));
1906 
1907     if (STI.isTargetDarwin() || STI.isTargetWindows()) {
1908       // These platforms always use the same frame register
1909       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1910         .addReg(FramePtr)
1911         .addReg(SrcReg)
1912         .addImm(0)
1913         // Predicate.
1914         .addImm(ARMCC::AL)
1915         .addReg(0));
1916     } else {
1917       // If the calling code might use either R7 or R11 as
1918       // frame pointer register, restore it into both.
1919       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1920         .addReg(ARM::R7)
1921         .addReg(SrcReg)
1922         .addImm(0)
1923         // Predicate.
1924         .addImm(ARMCC::AL)
1925         .addReg(0));
1926       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1927         .addReg(ARM::R11)
1928         .addReg(SrcReg)
1929         .addImm(0)
1930         // Predicate.
1931         .addImm(ARMCC::AL)
1932         .addReg(0));
1933     }
1934 
1935     assert(Subtarget->hasV4TOps());
1936     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1937       .addReg(ScratchReg)
1938       // Predicate.
1939       .addImm(ARMCC::AL)
1940       .addReg(0));
1941     return;
1942   }
1943   case ARM::tInt_eh_sjlj_longjmp: {
1944     // ldr $scratch, [$src, #8]
1945     // mov sp, $scratch
1946     // ldr $scratch, [$src, #4]
1947     // ldr r7, [$src]
1948     // bx $scratch
1949     unsigned SrcReg = MI->getOperand(0).getReg();
1950     unsigned ScratchReg = MI->getOperand(1).getReg();
1951 
1952     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1953       .addReg(ScratchReg)
1954       .addReg(SrcReg)
1955       // The offset immediate is #8. The operand value is scaled by 4 for the
1956       // tLDR instruction.
1957       .addImm(2)
1958       // Predicate.
1959       .addImm(ARMCC::AL)
1960       .addReg(0));
1961 
1962     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1963       .addReg(ARM::SP)
1964       .addReg(ScratchReg)
1965       // Predicate.
1966       .addImm(ARMCC::AL)
1967       .addReg(0));
1968 
1969     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1970       .addReg(ScratchReg)
1971       .addReg(SrcReg)
1972       .addImm(1)
1973       // Predicate.
1974       .addImm(ARMCC::AL)
1975       .addReg(0));
1976 
1977     if (STI.isTargetDarwin() || STI.isTargetWindows()) {
1978       // These platforms always use the same frame register
1979       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1980         .addReg(FramePtr)
1981         .addReg(SrcReg)
1982         .addImm(0)
1983         // Predicate.
1984         .addImm(ARMCC::AL)
1985         .addReg(0));
1986     } else {
1987       // If the calling code might use either R7 or R11 as
1988       // frame pointer register, restore it into both.
1989       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1990         .addReg(ARM::R7)
1991         .addReg(SrcReg)
1992         .addImm(0)
1993         // Predicate.
1994         .addImm(ARMCC::AL)
1995         .addReg(0));
1996       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1997         .addReg(ARM::R11)
1998         .addReg(SrcReg)
1999         .addImm(0)
2000         // Predicate.
2001         .addImm(ARMCC::AL)
2002         .addReg(0));
2003     }
2004 
2005     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
2006       .addReg(ScratchReg)
2007       // Predicate.
2008       .addImm(ARMCC::AL)
2009       .addReg(0));
2010     return;
2011   }
2012   case ARM::tInt_WIN_eh_sjlj_longjmp: {
2013     // ldr.w r11, [$src, #0]
2014     // ldr.w  sp, [$src, #8]
2015     // ldr.w  pc, [$src, #4]
2016 
2017     unsigned SrcReg = MI->getOperand(0).getReg();
2018 
2019     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2020                                      .addReg(ARM::R11)
2021                                      .addReg(SrcReg)
2022                                      .addImm(0)
2023                                      // Predicate
2024                                      .addImm(ARMCC::AL)
2025                                      .addReg(0));
2026     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2027                                      .addReg(ARM::SP)
2028                                      .addReg(SrcReg)
2029                                      .addImm(8)
2030                                      // Predicate
2031                                      .addImm(ARMCC::AL)
2032                                      .addReg(0));
2033     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2034                                      .addReg(ARM::PC)
2035                                      .addReg(SrcReg)
2036                                      .addImm(4)
2037                                      // Predicate
2038                                      .addImm(ARMCC::AL)
2039                                      .addReg(0));
2040     return;
2041   }
2042   case ARM::PATCHABLE_FUNCTION_ENTER:
2043     LowerPATCHABLE_FUNCTION_ENTER(*MI);
2044     return;
2045   case ARM::PATCHABLE_FUNCTION_EXIT:
2046     LowerPATCHABLE_FUNCTION_EXIT(*MI);
2047     return;
2048   case ARM::PATCHABLE_TAIL_CALL:
2049     LowerPATCHABLE_TAIL_CALL(*MI);
2050     return;
2051   }
2052 
2053   MCInst TmpInst;
2054   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
2055 
2056   EmitToStreamer(*OutStreamer, TmpInst);
2057 }
2058 
2059 //===----------------------------------------------------------------------===//
2060 // Target Registry Stuff
2061 //===----------------------------------------------------------------------===//
2062 
2063 // Force static initialization.
2064 extern "C" void LLVMInitializeARMAsmPrinter() {
2065   RegisterAsmPrinter<ARMAsmPrinter> X(getTheARMLETarget());
2066   RegisterAsmPrinter<ARMAsmPrinter> Y(getTheARMBETarget());
2067   RegisterAsmPrinter<ARMAsmPrinter> A(getTheThumbLETarget());
2068   RegisterAsmPrinter<ARMAsmPrinter> B(getTheThumbBETarget());
2069 }
2070