aboutsummaryrefslogtreecommitdiffstats
path: root/lib/Target/IA64/AsmPrinter/IA64AsmPrinter.cpp
blob: e7ed64e5c85ebfd439b60181e305c04a4d8a0dd9 (plain)
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
//===-- IA64AsmPrinter.cpp - Print out IA64 LLVM as assembly --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to assembly accepted by the GNU binutils 'gas'
// assembler. The Intel 'ias' and HP-UX 'as' assemblers *may* choke on this
// output, but if so that's a bug I'd like to hear about: please file a bug
// report in bugzilla. FYI, the not too bad 'ias' assembler is bundled with
// the Intel C/C++ compiler for Itanium Linux.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "asm-printer"
#include "IA64.h"
#include "IA64TargetMachine.h"
#include "llvm/Module.h"
#include "llvm/MDNode.h"
#include "llvm/Type.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/DwarfWriter.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Mangler.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/Statistic.h"
using namespace llvm;

STATISTIC(EmittedInsts, "Number of machine instrs printed");

namespace {
  class IA64AsmPrinter : public AsmPrinter {
    std::set<std::string> ExternalFunctionNames, ExternalObjectNames;
  public:
    explicit IA64AsmPrinter(raw_ostream &O, TargetMachine &TM,
                            const TargetAsmInfo *T, bool V)
      : AsmPrinter(O, TM, T, V) {}

    virtual const char *getPassName() const {
      return "IA64 Assembly Printer";
    }

    /// printInstruction - This method is automatically generated by tablegen
    /// from the instruction set description.  This method returns true if the
    /// machine instruction was sufficiently described to print it, otherwise it
    /// returns false.
    bool printInstruction(const MachineInstr *MI);

    // This method is used by the tablegen'erated instruction printer.
    void printOperand(const MachineInstr *MI, unsigned OpNo){
      const MachineOperand &MO = MI->getOperand(OpNo);
      if (MO.getType() == MachineOperand::MO_Register) {
        assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
               "Not physref??");
        //XXX Bug Workaround: See note in Printer::doInitialization about %.
        O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
      } else {
        printOp(MO);
      }
    }

    void printS8ImmOperand(const MachineInstr *MI, unsigned OpNo) {
      int val=(unsigned int)MI->getOperand(OpNo).getImm();
      if(val>=128) val=val-256; // if negative, flip sign
      O << val;
    }
    void printS14ImmOperand(const MachineInstr *MI, unsigned OpNo) {
      int val=(unsigned int)MI->getOperand(OpNo).getImm();
      if(val>=8192) val=val-16384; // if negative, flip sign
      O << val;
    }
    void printS22ImmOperand(const MachineInstr *MI, unsigned OpNo) {
      int val=(unsigned int)MI->getOperand(OpNo).getImm();
      if(val>=2097152) val=val-4194304; // if negative, flip sign
      O << val;
    }
    void printU64ImmOperand(const MachineInstr *MI, unsigned OpNo) {
      O << (uint64_t)MI->getOperand(OpNo).getImm();
    }
    void printS64ImmOperand(const MachineInstr *MI, unsigned OpNo) {
// XXX : nasty hack to avoid GPREL22 "relocation truncated to fit" linker
// errors - instead of add rX = @gprel(CPI<whatever>), r1;; we now
// emit movl rX = @gprel(CPI<whatever);;
//      add  rX = rX, r1;
// this gives us 64 bits instead of 22 (for the add long imm) to play
// with, which shuts up the linker. The problem is that the constant
// pool entries aren't immediates at this stage, so we check here.
// If it's an immediate, print it the old fashioned way. If it's
// not, we print it as a constant pool index.
      if (MI->getOperand(OpNo).isImm()) {
        O << (int64_t)MI->getOperand(OpNo).getImm();
      } else { // this is a constant pool reference: FIXME: assert this
        printOp(MI->getOperand(OpNo));
      }
    }

    void printGlobalOperand(const MachineInstr *MI, unsigned OpNo) {
      printOp(MI->getOperand(OpNo), false); // this is NOT a br.call instruction
    }

    void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
      printOp(MI->getOperand(OpNo), true); // this is a br.call instruction
    }

    void printMachineInstruction(const MachineInstr *MI);
    void printOp(const MachineOperand &MO, bool isBRCALLinsn= false);
    void printModuleLevelGV(const GlobalVariable* GVar);
    bool runOnMachineFunction(MachineFunction &F);
    bool doInitialization(Module &M);
    bool doFinalization(Module &M);
  };
} // end of anonymous namespace


// Include the auto-generated portion of the assembly writer.
#include "IA64GenAsmWriter.inc"

/// runOnMachineFunction - This uses the printMachineInstruction()
/// method to print assembly for each instruction.
///
bool IA64AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
  this->MF = &MF;

  SetupMachineFunction(MF);
  O << "\n\n";

  // Print out constants referenced by the function
  EmitConstantPool(MF.getConstantPool());

  const Function *F = MF.getFunction();
  SwitchToSection(TAI->SectionForGlobal(F));

  // Print out labels for the function.
  EmitAlignment(MF.getAlignment());
  O << "\t.global\t" << CurrentFnName << '\n';

  printVisibility(CurrentFnName, F->getVisibility());

  O << "\t.type\t" << CurrentFnName << ", @function\n";
  O << CurrentFnName << ":\n";

  // Print out code for the function.
  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
       I != E; ++I) {
    // Print a label for the basic block if there are any predecessors.
    if (!I->pred_empty()) {
      printBasicBlockLabel(I, true, true);
      O << '\n';
    }
    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
         II != E; ++II) {
      // Print the assembly for the instruction.
      printMachineInstruction(II);
    }
  }

  // We didn't modify anything.
  return false;
}

void IA64AsmPrinter::printOp(const MachineOperand &MO,
                             bool isBRCALLinsn /* = false */) {
  const TargetRegisterInfo &RI = *TM.getRegisterInfo();
  switch (MO.getType()) {
  case MachineOperand::MO_Register:
    O << RI.get(MO.getReg()).AsmName;
    return;

  case MachineOperand::MO_Immediate:
    O << MO.getImm();
    return;
  case MachineOperand::MO_MachineBasicBlock:
    printBasicBlockLabel(MO.getMBB());
    return;
  case MachineOperand::MO_ConstantPoolIndex: {
    O << "@gprel(" << TAI->getPrivateGlobalPrefix()
      << "CPI" << getFunctionNumber() << "_" << MO.getIndex() << ")";
    return;
  }

  case MachineOperand::MO_GlobalAddress: {

    // functions need @ltoff(@fptr(fn_name)) form
    GlobalValue *GV = MO.getGlobal();
    Function *F = dyn_cast<Function>(GV);

    bool Needfptr=false; // if we're computing an address @ltoff(X), do
                         // we need to decorate it so it becomes
                         // @ltoff(@fptr(X)) ?
    if (F && !isBRCALLinsn /*&& F->isDeclaration()*/)
      Needfptr=true;

    // if this is the target of a call instruction, we should define
    // the function somewhere (GNU gas has no problem without this, but
    // Intel ias rightly complains of an 'undefined symbol')

    if (F /*&& isBRCALLinsn*/ && F->isDeclaration())
      ExternalFunctionNames.insert(Mang->getValueName(MO.getGlobal()));
    else
      if (GV->isDeclaration()) // e.g. stuff like 'stdin'
        ExternalObjectNames.insert(Mang->getValueName(MO.getGlobal()));

    if (!isBRCALLinsn)
      O << "@ltoff(";
    if (Needfptr)
      O << "@fptr(";
    O << Mang->getValueName(MO.getGlobal());

    if (Needfptr && !isBRCALLinsn)
      O << "#))"; // close both fptr( and ltoff(
    else {
      if (Needfptr)
        O << "#)"; // close only fptr(
      if (!isBRCALLinsn)
        O << "#)"; // close only ltoff(
    }

    int Offset = MO.getOffset();
    if (Offset > 0)
      O << " + " << Offset;
    else if (Offset < 0)
      O << " - " << -Offset;
    return;
  }
  case MachineOperand::MO_ExternalSymbol:
    O << MO.getSymbolName();
    ExternalFunctionNames.insert(MO.getSymbolName());
    return;
  default:
    O << "<AsmPrinter: unknown operand type: " << MO.getType() << " >"; return;
  }
}

/// printMachineInstruction -- Print out a single IA64 LLVM instruction
/// MI to the current output stream.
///
void IA64AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
  ++EmittedInsts;

  // Call the autogenerated instruction printer routines.
  printInstruction(MI);
}

bool IA64AsmPrinter::doInitialization(Module &M) {
  bool Result = AsmPrinter::doInitialization(M);

  O << "\n.ident \"LLVM-ia64\"\n\n"
    << "\t.psr    lsb\n"  // should be "msb" on HP-UX, for starters
    << "\t.radix  C\n"
    << "\t.psr    abi64\n"; // we only support 64 bits for now
  return Result;
}

void IA64AsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
  const TargetData *TD = TM.getTargetData();

  if (!GVar->hasInitializer())
    return; // External global require no code

  // Check to see if this is a special global used by LLVM, if so, emit it.
  if (EmitSpecialLLVMGlobal(GVar))
    return;

  O << "\n\n";
  std::string name = Mang->getValueName(GVar);
  Constant *C = GVar->getInitializer();
  if (isa<MDNode>(C) || isa<MDString>(C))
    return;
  unsigned Size = TD->getTypeAllocSize(C->getType());
  unsigned Align = TD->getPreferredAlignmentLog(GVar);

  printVisibility(name, GVar->getVisibility());

  SwitchToSection(TAI->SectionForGlobal(GVar));

  if (C->isNullValue() && !GVar->hasSection()) {
    if (!GVar->isThreadLocal() &&
        (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
      if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.

      if (GVar->hasLocalLinkage()) {
        O << "\t.lcomm " << name << "#," << Size
          << ',' << (1 << Align);
        O << '\n';
      } else {
        O << "\t.common " << name << "#," << Size
          << ',' << (1 << Align);
        O << '\n';
      }

      return;
    }
  }

  switch (GVar->getLinkage()) {
   case GlobalValue::LinkOnceAnyLinkage:
   case GlobalValue::LinkOnceODRLinkage:
   case GlobalValue::CommonLinkage:
   case GlobalValue::WeakAnyLinkage:
   case GlobalValue::WeakODRLinkage:
    // Nonnull linkonce -> weak
    O << "\t.weak " << name << '\n';
    break;
   case GlobalValue::AppendingLinkage:
    // FIXME: appending linkage variables should go into a section of
    // their name or something.  For now, just emit them as external.
   case GlobalValue::ExternalLinkage:
    // If external or appending, declare as a global symbol
    O << TAI->getGlobalDirective() << name << '\n';
    // FALL THROUGH
   case GlobalValue::InternalLinkage:
   case GlobalValue::PrivateLinkage:
    break;
   case GlobalValue::GhostLinkage:
    llvm_unreachable("GhostLinkage cannot appear in IA64AsmPrinter!");
   case GlobalValue::DLLImportLinkage:
    llvm_unreachable("DLLImport linkage is not supported by this target!");
   case GlobalValue::DLLExportLinkage:
    llvm_unreachable("DLLExport linkage is not supported by this target!");
   default:
    llvm_unreachable("Unknown linkage type!");
  }

  EmitAlignment(Align, GVar);

  if (TAI->hasDotTypeDotSizeDirective()) {
    O << "\t.type " << name << ",@object\n";
    O << "\t.size " << name << ',' << Size << '\n';
  }

  O << name << ":\n";
  EmitGlobalConstant(C);
}


bool IA64AsmPrinter::doFinalization(Module &M) {
  // Print out module-level global variables here.
  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
       I != E; ++I)
    printModuleLevelGV(I);

  // we print out ".global X \n .type X, @function" for each external function
  O << "\n\n// br.call targets referenced (and not defined) above: \n";
  for (std::set<std::string>::iterator i = ExternalFunctionNames.begin(),
       e = ExternalFunctionNames.end(); i!=e; ++i) {
    O << "\t.global " << *i << "\n\t.type " << *i << ", @function\n";
  }
  O << "\n\n";

  // we print out ".global X \n .type X, @object" for each external object
  O << "\n\n// (external) symbols referenced (and not defined) above: \n";
  for (std::set<std::string>::iterator i = ExternalObjectNames.begin(),
       e = ExternalObjectNames.end(); i!=e; ++i) {
    O << "\t.global " << *i << "\n\t.type " << *i << ", @object\n";
  }
  O << "\n\n";

  return AsmPrinter::doFinalization(M);
}

/// createIA64CodePrinterPass - Returns a pass that prints the IA64
/// assembly code for a MachineFunction to the given output stream, using
/// the given target machine description.
///
FunctionPass *llvm::createIA64CodePrinterPass(raw_ostream &o,
                                              IA64TargetMachine &tm,
                                              bool verbose) {
  return new IA64AsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
}

namespace {
  static struct Register {
    Register() {
      IA64TargetMachine::registerAsmPrinter(createIA64CodePrinterPass);
    }
  } Registrator;
}


// Force static initialization.
extern "C" void LLVMInitializeIA64AsmPrinter() { }