blob: 12f18c478acfb14565653dbd1a7b7fdd622ac5da [file] [log] [blame]
Justin Holewinskiae556d32012-05-04 20:18:50 +00001//===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a printer that converts from our internal representation
11// of machine-dependent LLVM code to NVPTX assembly language.
12//
13//===----------------------------------------------------------------------===//
14
Bill Wendlinge38859d2012-06-28 00:05:13 +000015#include "NVPTXAsmPrinter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "MCTargetDesc/NVPTXMCAsmInfo.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000017#include "NVPTX.h"
18#include "NVPTXInstrInfo.h"
Justin Holewinskia2a63d22013-08-06 14:13:27 +000019#include "NVPTXMCExpr.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "NVPTXRegisterInfo.h"
21#include "NVPTXTargetMachine.h"
22#include "NVPTXUtilities.h"
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +000023#include "InstPrinter/NVPTXInstPrinter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "cl_common_defines.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000025#include "llvm/ADT/StringExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/ConstantFolding.h"
27#include "llvm/Assembly/Writer.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000028#include "llvm/CodeGen/Analysis.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
32#include "llvm/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/GlobalVariable.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/Operator.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000038#include "llvm/MC/MCStreamer.h"
39#include "llvm/MC/MCSymbol.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Support/CommandLine.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000041#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/FormattedStream.h"
Justin Holewinskiae556d32012-05-04 20:18:50 +000043#include "llvm/Support/Path.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TimeValue.h"
46#include "llvm/Target/Mangler.h"
47#include "llvm/Target/TargetLoweringObjectFile.h"
Bill Wendlinge38859d2012-06-28 00:05:13 +000048#include <sstream>
Justin Holewinskiae556d32012-05-04 20:18:50 +000049using namespace llvm;
50
Justin Holewinskiae556d32012-05-04 20:18:50 +000051bool RegAllocNilUsed = true;
52
53#define DEPOTNAME "__local_depot"
54
55static cl::opt<bool>
56EmitLineNumbers("nvptx-emit-line-numbers",
57 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
58 cl::init(true));
59
Justin Holewinski0497ab12013-03-30 14:29:21 +000060namespace llvm { bool InterleaveSrcInPtx = false; }
Justin Holewinskiae556d32012-05-04 20:18:50 +000061
Justin Holewinski0497ab12013-03-30 14:29:21 +000062static cl::opt<bool, true>
63InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore,
64 cl::desc("NVPTX Specific: Emit source line in ptx file"),
65 cl::location(llvm::InterleaveSrcInPtx));
Justin Holewinskiae556d32012-05-04 20:18:50 +000066
Justin Holewinski2c5ac702012-11-16 21:03:51 +000067namespace {
68/// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
69/// depends.
Justin Holewinski01f89f02013-05-20 12:13:32 +000070void DiscoverDependentGlobals(const Value *V,
71 DenseSet<const GlobalVariable *> &Globals) {
72 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
Justin Holewinski2c5ac702012-11-16 21:03:51 +000073 Globals.insert(GV);
74 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +000075 if (const User *U = dyn_cast<User>(V)) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000076 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
77 DiscoverDependentGlobals(U->getOperand(i), Globals);
78 }
79 }
80 }
81}
Justin Holewinskiae556d32012-05-04 20:18:50 +000082
Justin Holewinski2c5ac702012-11-16 21:03:51 +000083/// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
84/// instances to be emitted, but only after any dependents have been added
85/// first.
Justin Holewinski0497ab12013-03-30 14:29:21 +000086void VisitGlobalVariableForEmission(
Justin Holewinski01f89f02013-05-20 12:13:32 +000087 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
88 DenseSet<const GlobalVariable *> &Visited,
89 DenseSet<const GlobalVariable *> &Visiting) {
Justin Holewinski2c5ac702012-11-16 21:03:51 +000090 // Have we already visited this one?
Justin Holewinski0497ab12013-03-30 14:29:21 +000091 if (Visited.count(GV))
92 return;
Justin Holewinski2c5ac702012-11-16 21:03:51 +000093
94 // Do we have a circular dependency?
95 if (Visiting.count(GV))
96 report_fatal_error("Circular dependency found in global variable set");
97
98 // Start visiting this global
99 Visiting.insert(GV);
100
101 // Make sure we visit all dependents first
Justin Holewinski01f89f02013-05-20 12:13:32 +0000102 DenseSet<const GlobalVariable *> Others;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000103 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
104 DiscoverDependentGlobals(GV->getOperand(i), Others);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000105
Justin Holewinski01f89f02013-05-20 12:13:32 +0000106 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
107 E = Others.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000108 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000109 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
110
111 // Now we can visit ourself
112 Order.push_back(GV);
113 Visited.insert(GV);
114 Visiting.erase(GV);
115}
116}
Justin Holewinskiae556d32012-05-04 20:18:50 +0000117
118// @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
119// cannot just link to the existing version.
120/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
121///
122using namespace nvptx;
123const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
124 MCContext &Ctx = AP.OutContext;
125
126 if (CV->isNullValue() || isa<UndefValue>(CV))
127 return MCConstantExpr::Create(0, Ctx);
128
129 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
130 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
131
132 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
133 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
134
135 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
136 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
137
138 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
139 if (CE == 0)
140 llvm_unreachable("Unknown constant value to lower!");
141
Justin Holewinskiae556d32012-05-04 20:18:50 +0000142 switch (CE->getOpcode()) {
143 default:
144 // If the code isn't optimized, there may be outstanding folding
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000145 // opportunities. Attempt to fold the expression using DataLayout as a
Justin Holewinskiae556d32012-05-04 20:18:50 +0000146 // last resort before giving up.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000147 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000148 if (C != CE)
149 return LowerConstant(C, AP);
150
151 // Otherwise report the problem to the user.
152 {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000153 std::string S;
154 raw_string_ostream OS(S);
155 OS << "Unsupported expression in static initializer: ";
156 WriteAsOperand(OS, CE, /*PrintType=*/ false,
157 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
158 report_fatal_error(OS.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000159 }
160 case Instruction::GetElementPtr: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000161 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000162 // Generate a symbolic expression for the byte address
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000163 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
164 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000165
166 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000167 if (!OffsetAI)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000168 return Base;
169
Nuno Lopesb6ad9822012-12-30 16:25:48 +0000170 int64_t Offset = OffsetAI.getSExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000171 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
172 Ctx);
173 }
174
175 case Instruction::Trunc:
176 // We emit the value and depend on the assembler to truncate the generated
177 // expression properly. This is important for differences between
178 // blockaddress labels. Since the two labels are in the same function, it
179 // is reasonable to treat their delta as a 32-bit value.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000180 // FALL THROUGH.
Justin Holewinskiae556d32012-05-04 20:18:50 +0000181 case Instruction::BitCast:
182 return LowerConstant(CE->getOperand(0), AP);
183
184 case Instruction::IntToPtr: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000185 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000186 // Handle casts to pointers by changing them into casts to the appropriate
187 // integer type. This promotes constant folding and simplifies this code.
188 Constant *Op = CE->getOperand(0);
Chandler Carruth7ec50852012-11-01 08:07:29 +0000189 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
Justin Holewinski0497ab12013-03-30 14:29:21 +0000190 false /*ZExt*/);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000191 return LowerConstant(Op, AP);
192 }
193
194 case Instruction::PtrToInt: {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000195 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000196 // Support only foldable casts to/from pointers that can be eliminated by
197 // changing the pointer to the appropriately sized integer type.
198 Constant *Op = CE->getOperand(0);
199 Type *Ty = CE->getType();
200
201 const MCExpr *OpExpr = LowerConstant(Op, AP);
202
203 // We can emit the pointer value into this slot if the slot is an
204 // integer slot equal to the size of the pointer.
205 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
206 return OpExpr;
207
208 // Otherwise the pointer is smaller than the resultant integer, mask off
209 // the high bits so we are sure to get a proper truncation if the input is
210 // a constant expr.
211 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +0000212 const MCExpr *MaskExpr =
213 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000214 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
215 }
216
Justin Holewinski0497ab12013-03-30 14:29:21 +0000217 // The MC library also has a right-shift operator, but it isn't consistently
Justin Holewinskiae556d32012-05-04 20:18:50 +0000218 // signed or unsigned between different targets.
219 case Instruction::Add:
220 case Instruction::Sub:
221 case Instruction::Mul:
222 case Instruction::SDiv:
223 case Instruction::SRem:
224 case Instruction::Shl:
225 case Instruction::And:
226 case Instruction::Or:
227 case Instruction::Xor: {
228 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
229 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
230 switch (CE->getOpcode()) {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000231 default:
232 llvm_unreachable("Unknown binary operator constant cast expr");
233 case Instruction::Add:
234 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
235 case Instruction::Sub:
236 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
237 case Instruction::Mul:
238 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
239 case Instruction::SDiv:
240 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
241 case Instruction::SRem:
242 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
243 case Instruction::Shl:
244 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
245 case Instruction::And:
246 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
247 case Instruction::Or:
248 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
249 case Instruction::Xor:
250 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000251 }
252 }
253 }
254}
255
Justin Holewinski0497ab12013-03-30 14:29:21 +0000256void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000257 if (!EmitLineNumbers)
258 return;
259 if (ignoreLoc(MI))
260 return;
261
262 DebugLoc curLoc = MI.getDebugLoc();
263
264 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
265 return;
266
267 if (prevDebugLoc == curLoc)
268 return;
269
270 prevDebugLoc = curLoc;
271
272 if (curLoc.isUnknown())
273 return;
274
Justin Holewinskiae556d32012-05-04 20:18:50 +0000275 const MachineFunction *MF = MI.getParent()->getParent();
276 //const TargetMachine &TM = MF->getTarget();
277
278 const LLVMContext &ctx = MF->getFunction()->getContext();
279 DIScope Scope(curLoc.getScope(ctx));
280
Manman Ren983a16c2013-06-28 05:43:10 +0000281 assert((!Scope || Scope.isScope()) &&
282 "Scope of a DebugLoc should be null or a DIScope.");
283 if (!Scope)
284 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000285
286 StringRef fileName(Scope.getFilename());
287 StringRef dirName(Scope.getDirectory());
288 SmallString<128> FullPathName = dirName;
289 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
290 sys::path::append(FullPathName, fileName);
291 fileName = FullPathName.str();
292 }
293
294 if (filenameMap.find(fileName.str()) == filenameMap.end())
295 return;
296
Justin Holewinskiae556d32012-05-04 20:18:50 +0000297 // Emit the line from the source file.
298 if (llvm::InterleaveSrcInPtx)
299 this->emitSrcInText(fileName.str(), curLoc.getLine());
300
301 std::stringstream temp;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000302 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
303 << " " << curLoc.getCol();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000304 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
305}
306
307void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
308 SmallString<128> Str;
309 raw_svector_ostream OS(Str);
310 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
311 emitLineNumberAsDotLoc(*MI);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000312
313 MCInst Inst;
314 lowerToMCInst(MI, Inst);
315 OutStreamer.EmitInstruction(Inst);
316}
317
318void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
319 OutMI.setOpcode(MI->getOpcode());
320
321 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
322 const MachineOperand &MO = MI->getOperand(i);
323
324 MCOperand MCOp;
325 if (lowerOperand(MO, MCOp))
326 OutMI.addOperand(MCOp);
327 }
328}
329
330bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
331 MCOperand &MCOp) {
332 switch (MO.getType()) {
333 default: llvm_unreachable("unknown operand type");
334 case MachineOperand::MO_Register:
335 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
336 break;
337 case MachineOperand::MO_Immediate:
338 MCOp = MCOperand::CreateImm(MO.getImm());
339 break;
340 case MachineOperand::MO_MachineBasicBlock:
341 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
342 MO.getMBB()->getSymbol(), OutContext));
343 break;
344 case MachineOperand::MO_ExternalSymbol:
345 MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
346 break;
347 case MachineOperand::MO_GlobalAddress:
348 MCOp = GetSymbolRef(MO, Mang->getSymbol(MO.getGlobal()));
349 break;
350 case MachineOperand::MO_FPImmediate: {
351 const ConstantFP *Cnt = MO.getFPImm();
352 APFloat Val = Cnt->getValueAPF();
353
354 switch (Cnt->getType()->getTypeID()) {
355 default: report_fatal_error("Unsupported FP type"); break;
356 case Type::FloatTyID:
357 MCOp = MCOperand::CreateExpr(
358 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
359 break;
360 case Type::DoubleTyID:
361 MCOp = MCOperand::CreateExpr(
362 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
363 break;
364 }
365 break;
366 }
367 }
368 return true;
369}
370
371unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
Justin Holewinski871ec932013-08-06 14:13:31 +0000372 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
373 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000374
Justin Holewinski871ec932013-08-06 14:13:31 +0000375 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
376 unsigned RegNum = RegMap[Reg];
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000377
Justin Holewinski871ec932013-08-06 14:13:31 +0000378 // Encode the register class in the upper 4 bits
379 // Must be kept in sync with NVPTXInstPrinter::printRegName
380 unsigned Ret = 0;
381 if (RC == &NVPTX::Int1RegsRegClass) {
382 Ret = (1 << 28);
383 } else if (RC == &NVPTX::Int16RegsRegClass) {
384 Ret = (2 << 28);
385 } else if (RC == &NVPTX::Int32RegsRegClass) {
386 Ret = (3 << 28);
387 } else if (RC == &NVPTX::Int64RegsRegClass) {
388 Ret = (4 << 28);
389 } else if (RC == &NVPTX::Float32RegsRegClass) {
390 Ret = (5 << 28);
391 } else if (RC == &NVPTX::Float64RegsRegClass) {
392 Ret = (6 << 28);
393 } else {
394 report_fatal_error("Bad register class");
395 }
396
397 // Insert the vreg number
398 Ret |= (RegNum & 0x0FFFFFFF);
399 return Ret;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000400 } else {
Justin Holewinski871ec932013-08-06 14:13:31 +0000401 // Some special-use registers are actually physical registers.
402 // Encode this as the register class ID of 0 and the real register ID.
403 return Reg & 0x0FFFFFFF;
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000404 }
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000405}
406
407MCOperand NVPTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
408 const MCSymbol *Symbol) {
409 const MCExpr *Expr;
Justin Holewinski8b24e1e2013-08-06 23:06:42 +0000410 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
411 OutContext);
Justin Holewinskia2a63d22013-08-06 14:13:27 +0000412 return MCOperand::CreateExpr(Expr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000413}
414
Justin Holewinski0497ab12013-03-30 14:29:21 +0000415void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000416 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000417 const TargetLowering *TLI = TM.getTargetLowering();
418
419 Type *Ty = F->getReturnType();
420
421 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
422
423 if (Ty->getTypeID() == Type::VoidTyID)
424 return;
425
426 O << " (";
427
428 if (isABI) {
429 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
430 unsigned size = 0;
431 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
432 size = ITy->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000433 if (size < 32)
434 size = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000435 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000436 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000437 size = Ty->getPrimitiveSizeInBits();
438 }
439
440 O << ".param .b" << size << " func_retval0";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000441 } else if (isa<PointerType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000442 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
Justin Holewinski0497ab12013-03-30 14:29:21 +0000443 << " func_retval0";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000444 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000445 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000446 SmallVector<EVT, 16> vtparts;
447 ComputeValueVTs(*TLI, Ty, vtparts);
448 unsigned totalsz = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000449 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000450 unsigned elems = 1;
451 EVT elemtype = vtparts[i];
452 if (vtparts[i].isVector()) {
453 elems = vtparts[i].getVectorNumElements();
454 elemtype = vtparts[i].getVectorElementType();
455 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000456 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000457 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000458 if (elemtype.isInteger() && (sz < 8))
459 sz = 8;
460 totalsz += sz / 8;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000461 }
462 }
463 unsigned retAlignment = 0;
464 if (!llvm::getAlign(*F, 0, retAlignment))
465 retAlignment = TD->getABITypeAlignment(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +0000466 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
467 << "]";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000468 } else
Justin Holewinski0497ab12013-03-30 14:29:21 +0000469 assert(false && "Unknown return type");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000470 }
471 } else {
472 SmallVector<EVT, 16> vtparts;
473 ComputeValueVTs(*TLI, Ty, vtparts);
474 unsigned idx = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000475 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000476 unsigned elems = 1;
477 EVT elemtype = vtparts[i];
478 if (vtparts[i].isVector()) {
479 elems = vtparts[i].getVectorNumElements();
480 elemtype = vtparts[i].getVectorElementType();
481 }
482
Justin Holewinski0497ab12013-03-30 14:29:21 +0000483 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000484 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000485 if (elemtype.isInteger() && (sz < 32))
486 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000487 O << ".reg .b" << sz << " func_retval" << idx;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000488 if (j < je - 1)
489 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000490 ++idx;
491 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000492 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000493 O << ", ";
494 }
495 }
496 O << ") ";
497 return;
498}
499
500void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
501 raw_ostream &O) {
502 const Function *F = MF.getFunction();
503 printReturnValStr(F, O);
504}
505
506void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
507 SmallString<128> Str;
508 raw_svector_ostream O(Str);
509
Justin Holewinski01f89f02013-05-20 12:13:32 +0000510 if (!GlobalsEmitted) {
511 emitGlobals(*MF->getFunction()->getParent());
512 GlobalsEmitted = true;
513 }
514
Justin Holewinskiae556d32012-05-04 20:18:50 +0000515 // Set up
516 MRI = &MF->getRegInfo();
517 F = MF->getFunction();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000518 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000519 if (llvm::isKernelFunction(*F))
520 O << ".entry ";
521 else {
522 O << ".func ";
523 printReturnValStr(*MF, O);
524 }
525
526 O << *CurrentFnSym;
527
528 emitFunctionParamList(*MF, O);
529
530 if (llvm::isKernelFunction(*F))
531 emitKernelFunctionDirectives(*F, O);
532
533 OutStreamer.EmitRawText(O.str());
534
535 prevDebugLoc = DebugLoc();
536}
537
538void NVPTXAsmPrinter::EmitFunctionBodyStart() {
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000539 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000540 OutStreamer.EmitRawText(StringRef("{\n"));
541 setAndEmitFunctionVirtualRegisters(*MF);
542
543 SmallString<128> Str;
544 raw_svector_ostream O(Str);
545 emitDemotedVars(MF->getFunction(), O);
546 OutStreamer.EmitRawText(O.str());
547}
548
549void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
550 OutStreamer.EmitRawText(StringRef("}\n"));
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000551 VRegMapping.clear();
Justin Holewinskiae556d32012-05-04 20:18:50 +0000552}
553
Justin Holewinski0497ab12013-03-30 14:29:21 +0000554void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
555 raw_ostream &O) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000556 // If the NVVM IR has some of reqntid* specified, then output
557 // the reqntid directive, and set the unspecified ones to 1.
558 // If none of reqntid* is specified, don't output reqntid directive.
559 unsigned reqntidx, reqntidy, reqntidz;
560 bool specified = false;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000561 if (llvm::getReqNTIDx(F, reqntidx) == false)
562 reqntidx = 1;
563 else
564 specified = true;
565 if (llvm::getReqNTIDy(F, reqntidy) == false)
566 reqntidy = 1;
567 else
568 specified = true;
569 if (llvm::getReqNTIDz(F, reqntidz) == false)
570 reqntidz = 1;
571 else
572 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000573
574 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000575 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
576 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000577
578 // If the NVVM IR has some of maxntid* specified, then output
579 // the maxntid directive, and set the unspecified ones to 1.
580 // If none of maxntid* is specified, don't output maxntid directive.
581 unsigned maxntidx, maxntidy, maxntidz;
582 specified = false;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000583 if (llvm::getMaxNTIDx(F, maxntidx) == false)
584 maxntidx = 1;
585 else
586 specified = true;
587 if (llvm::getMaxNTIDy(F, maxntidy) == false)
588 maxntidy = 1;
589 else
590 specified = true;
591 if (llvm::getMaxNTIDz(F, maxntidz) == false)
592 maxntidz = 1;
593 else
594 specified = true;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000595
596 if (specified)
Justin Holewinski0497ab12013-03-30 14:29:21 +0000597 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
598 << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000599
600 unsigned mincta;
601 if (llvm::getMinCTASm(F, mincta))
602 O << ".minnctapersm " << mincta << "\n";
603}
604
Justin Holewinski0497ab12013-03-30 14:29:21 +0000605void NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
606 raw_ostream &O) {
607 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000608
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +0000609 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +0000610 unsigned mapped_vr = regmap[vr];
611
612 if (!isVec) {
613 O << getNVPTXRegClassStr(RC) << mapped_vr;
614 return;
615 }
Justin Holewinskibe8dc642013-02-12 14:18:49 +0000616 report_fatal_error("Bad register!");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000617}
618
Justin Holewinski0497ab12013-03-30 14:29:21 +0000619void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
620 raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000621 getVirtualRegisterName(vr, isVec, O);
622}
623
Justin Holewinski0497ab12013-03-30 14:29:21 +0000624void NVPTXAsmPrinter::printVecModifiedImmediate(
625 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
626 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
627 int Imm = (int) MO.getImm();
628 if (0 == strcmp(Modifier, "vecelem"))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000629 O << "_" << vecelem[Imm];
Justin Holewinski0497ab12013-03-30 14:29:21 +0000630 else if (0 == strcmp(Modifier, "vecv4comm1")) {
631 if ((Imm < 0) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000632 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000633 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
634 if ((Imm < 4) || (Imm > 7))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000635 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000636 } else if (0 == strcmp(Modifier, "vecv4pos")) {
637 if (Imm < 0)
638 Imm = 0;
639 O << "_" << vecelem[Imm % 4];
640 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
641 if ((Imm < 0) || (Imm > 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000642 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000643 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
644 if ((Imm < 2) || (Imm > 3))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000645 O << "//";
Justin Holewinski0497ab12013-03-30 14:29:21 +0000646 } else if (0 == strcmp(Modifier, "vecv2pos")) {
647 if (Imm < 0)
648 Imm = 0;
649 O << "_" << vecelem[Imm % 2];
650 } else
Craig Topperbdf39a42012-05-24 07:02:50 +0000651 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinskiae556d32012-05-04 20:18:50 +0000652}
653
Justin Holewinskidc5e3b62013-06-28 17:58:04 +0000654
655
Justin Holewinski0497ab12013-03-30 14:29:21 +0000656void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000657
Justin Holewinski0497ab12013-03-30 14:29:21 +0000658 emitLinkageDirective(F, O);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000659 if (llvm::isKernelFunction(*F))
660 O << ".entry ";
661 else
662 O << ".func ";
663 printReturnValStr(F, O);
Justin Holewinski4c47d872013-05-20 16:42:18 +0000664 O << *Mang->getSymbol(F) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000665 emitFunctionParamList(F, O);
666 O << ";\n";
667}
668
Justin Holewinski0497ab12013-03-30 14:29:21 +0000669static bool usedInGlobalVarDef(const Constant *C) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000670 if (!C)
671 return false;
672
673 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
674 if (GV->getName().str() == "llvm.used")
675 return false;
676 return true;
677 }
678
Justin Holewinski0497ab12013-03-30 14:29:21 +0000679 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
680 ui != ue; ++ui) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000681 const Constant *C = dyn_cast<Constant>(*ui);
682 if (usedInGlobalVarDef(C))
683 return true;
684 }
685 return false;
686}
687
Justin Holewinski0497ab12013-03-30 14:29:21 +0000688static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000689 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
690 if (othergv->getName().str() == "llvm.used")
691 return true;
692 }
693
694 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
695 if (instr->getParent() && instr->getParent()->getParent()) {
696 const Function *curFunc = instr->getParent()->getParent();
697 if (oneFunc && (curFunc != oneFunc))
698 return false;
699 oneFunc = curFunc;
700 return true;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000701 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +0000702 return false;
703 }
704
705 if (const MDNode *md = dyn_cast<MDNode>(U))
706 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
Justin Holewinski0497ab12013-03-30 14:29:21 +0000707 (md->getName().str() == "llvm.dbg.sp")))
Justin Holewinskiae556d32012-05-04 20:18:50 +0000708 return true;
709
Justin Holewinski0497ab12013-03-30 14:29:21 +0000710 for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
711 ui != ue; ++ui) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000712 if (usedInOneFunc(*ui, oneFunc) == false)
713 return false;
714 }
715 return true;
716}
717
718/* Find out if a global variable can be demoted to local scope.
719 * Currently, this is valid for CUDA shared variables, which have local
720 * scope and global lifetime. So the conditions to check are :
721 * 1. Is the global variable in shared address space?
722 * 2. Does it have internal linkage?
723 * 3. Is the global variable referenced only in one function?
724 */
725static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
726 if (gv->hasInternalLinkage() == false)
727 return false;
728 const PointerType *Pty = gv->getType();
729 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
730 return false;
731
732 const Function *oneFunc = 0;
733
734 bool flag = usedInOneFunc(gv, oneFunc);
735 if (flag == false)
736 return false;
737 if (!oneFunc)
738 return false;
739 f = oneFunc;
740 return true;
741}
742
743static bool useFuncSeen(const Constant *C,
744 llvm::DenseMap<const Function *, bool> &seenMap) {
Justin Holewinski0497ab12013-03-30 14:29:21 +0000745 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
746 ui != ue; ++ui) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000747 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
748 if (useFuncSeen(cu, seenMap))
749 return true;
750 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
751 const BasicBlock *bb = I->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000752 if (!bb)
753 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000754 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000755 if (!caller)
756 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000757 if (seenMap.find(caller) != seenMap.end())
758 return true;
759 }
760 }
761 return false;
762}
763
Justin Holewinski01f89f02013-05-20 12:13:32 +0000764void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000765 llvm::DenseMap<const Function *, bool> seenMap;
Justin Holewinski0497ab12013-03-30 14:29:21 +0000766 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000767 const Function *F = FI;
768
769 if (F->isDeclaration()) {
770 if (F->use_empty())
771 continue;
772 if (F->getIntrinsicID())
773 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000774 emitDeclaration(F, O);
775 continue;
776 }
Justin Holewinski0497ab12013-03-30 14:29:21 +0000777 for (Value::const_use_iterator iter = F->use_begin(),
778 iterEnd = F->use_end();
779 iter != iterEnd; ++iter) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000780 if (const Constant *C = dyn_cast<Constant>(*iter)) {
781 if (usedInGlobalVarDef(C)) {
782 // The use is in the initialization of a global variable
783 // that is a function pointer, so print a declaration
784 // for the original function
Justin Holewinskiae556d32012-05-04 20:18:50 +0000785 emitDeclaration(F, O);
786 break;
787 }
788 // Emit a declaration of this function if the function that
789 // uses this constant expr has already been seen.
790 if (useFuncSeen(C, seenMap)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000791 emitDeclaration(F, O);
792 break;
793 }
794 }
795
Justin Holewinski0497ab12013-03-30 14:29:21 +0000796 if (!isa<Instruction>(*iter))
797 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000798 const Instruction *instr = cast<Instruction>(*iter);
799 const BasicBlock *bb = instr->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000800 if (!bb)
801 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000802 const Function *caller = bb->getParent();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000803 if (!caller)
804 continue;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000805
806 // If a caller has already been seen, then the caller is
807 // appearing in the module before the callee. so print out
808 // a declaration for the callee.
809 if (seenMap.find(caller) != seenMap.end()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000810 emitDeclaration(F, O);
811 break;
812 }
813 }
814 seenMap[F] = true;
815 }
816}
817
818void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
819 DebugInfoFinder DbgFinder;
820 DbgFinder.processModule(M);
821
Justin Holewinski0497ab12013-03-30 14:29:21 +0000822 unsigned i = 1;
Justin Holewinskiae556d32012-05-04 20:18:50 +0000823 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
Justin Holewinski0497ab12013-03-30 14:29:21 +0000824 E = DbgFinder.compile_unit_end();
825 I != E; ++I) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000826 DICompileUnit DIUnit(*I);
827 StringRef Filename(DIUnit.getFilename());
828 StringRef Dirname(DIUnit.getDirectory());
829 SmallString<128> FullPathName = Dirname;
830 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
831 sys::path::append(FullPathName, Filename);
832 Filename = FullPathName.str();
833 }
834 if (filenameMap.find(Filename.str()) != filenameMap.end())
835 continue;
836 filenameMap[Filename.str()] = i;
837 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
838 ++i;
839 }
840
841 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
Justin Holewinski0497ab12013-03-30 14:29:21 +0000842 E = DbgFinder.subprogram_end();
843 I != E; ++I) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000844 DISubprogram SP(*I);
845 StringRef Filename(SP.getFilename());
846 StringRef Dirname(SP.getDirectory());
847 SmallString<128> FullPathName = Dirname;
848 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
849 sys::path::append(FullPathName, Filename);
850 Filename = FullPathName.str();
851 }
852 if (filenameMap.find(Filename.str()) != filenameMap.end())
853 continue;
854 filenameMap[Filename.str()] = i;
855 ++i;
856 }
857}
858
Justin Holewinski0497ab12013-03-30 14:29:21 +0000859bool NVPTXAsmPrinter::doInitialization(Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000860
861 SmallString<128> Str1;
862 raw_svector_ostream OS1(Str1);
863
864 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
865 MMI->AnalyzeModule(M);
866
867 // We need to call the parent's one explicitly.
868 //bool Result = AsmPrinter::doInitialization(M);
869
870 // Initialize TargetLoweringObjectFile.
Justin Holewinski0497ab12013-03-30 14:29:21 +0000871 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
872 .Initialize(OutContext, TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000873
Bill Wendling70b14002013-05-29 20:37:19 +0000874 Mang = new Mangler(OutContext, &TM);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000875
876 // Emit header before any dwarf directives are emitted below.
877 emitHeader(M, OS1);
878 OutStreamer.EmitRawText(OS1.str());
879
Justin Holewinskiae556d32012-05-04 20:18:50 +0000880 // Already commented out
881 //bool Result = AsmPrinter::doInitialization(M);
882
Justin Holewinskid2bbdf02013-07-01 13:00:14 +0000883 // Emit module-level inline asm if it exists.
884 if (!M.getModuleInlineAsm().empty()) {
885 OutStreamer.AddComment("Start of file scope inline assembly");
886 OutStreamer.AddBlankLine();
887 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
888 OutStreamer.AddBlankLine();
889 OutStreamer.AddComment("End of file scope inline assembly");
890 OutStreamer.AddBlankLine();
891 }
892
Justin Holewinskiae556d32012-05-04 20:18:50 +0000893 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
894 recordAndEmitFilenames(M);
895
Justin Holewinski01f89f02013-05-20 12:13:32 +0000896 GlobalsEmitted = false;
897
898 return false; // success
899}
900
901void NVPTXAsmPrinter::emitGlobals(const Module &M) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000902 SmallString<128> Str2;
903 raw_svector_ostream OS2(Str2);
904
905 emitDeclarations(M, OS2);
906
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000907 // As ptxas does not support forward references of globals, we need to first
908 // sort the list of module-level globals in def-use order. We visit each
909 // global variable in order, and ensure that we emit it *after* its dependent
910 // globals. We use a little extra memory maintaining both a set and a list to
911 // have fast searches while maintaining a strict ordering.
Justin Holewinski01f89f02013-05-20 12:13:32 +0000912 SmallVector<const GlobalVariable *, 8> Globals;
913 DenseSet<const GlobalVariable *> GVVisited;
914 DenseSet<const GlobalVariable *> GVVisiting;
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000915
916 // Visit each global variable, in order
Justin Holewinski01f89f02013-05-20 12:13:32 +0000917 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
918 I != E; ++I)
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000919 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
920
Justin Holewinski0497ab12013-03-30 14:29:21 +0000921 assert(GVVisited.size() == M.getGlobalList().size() &&
Justin Holewinski2c5ac702012-11-16 21:03:51 +0000922 "Missed a global variable");
923 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
924
925 // Print out module-level global variables in proper order
926 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
927 printModuleLevelGV(Globals[i], OS2);
Justin Holewinskiae556d32012-05-04 20:18:50 +0000928
929 OS2 << '\n';
930
931 OutStreamer.EmitRawText(OS2.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +0000932}
933
Justin Holewinski0497ab12013-03-30 14:29:21 +0000934void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +0000935 O << "//\n";
936 O << "// Generated by LLVM NVPTX Back-End\n";
937 O << "//\n";
938 O << "\n";
939
Justin Holewinski1812ee92012-11-12 03:16:43 +0000940 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
941 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +0000942
943 O << ".target ";
944 O << nvptxSubtarget.getTargetName();
945
946 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
947 O << ", texmode_independent";
948 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
949 if (!nvptxSubtarget.hasDouble())
950 O << ", map_f64_to_f32";
951 }
952
953 if (MAI->doesSupportDebugInformation())
954 O << ", debug";
955
956 O << "\n";
957
958 O << ".address_size ";
959 if (nvptxSubtarget.is64Bit())
960 O << "64";
961 else
962 O << "32";
963 O << "\n";
964
965 O << "\n";
966}
967
968bool NVPTXAsmPrinter::doFinalization(Module &M) {
Justin Holewinski01f89f02013-05-20 12:13:32 +0000969
970 // If we did not emit any functions, then the global declarations have not
971 // yet been emitted.
972 if (!GlobalsEmitted) {
973 emitGlobals(M);
974 GlobalsEmitted = true;
975 }
976
Justin Holewinskiae556d32012-05-04 20:18:50 +0000977 // XXX Temproarily remove global variables so that doFinalization() will not
978 // emit them again (global variables are emitted at beginning).
979
980 Module::GlobalListType &global_list = M.getGlobalList();
981 int i, n = global_list.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000982 GlobalVariable **gv_array = new GlobalVariable *[n];
Justin Holewinskiae556d32012-05-04 20:18:50 +0000983
984 // first, back-up GlobalVariable in gv_array
985 i = 0;
986 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
Justin Holewinski0497ab12013-03-30 14:29:21 +0000987 I != E; ++I)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000988 gv_array[i++] = &*I;
989
990 // second, empty global_list
991 while (!global_list.empty())
992 global_list.remove(global_list.begin());
993
994 // call doFinalization
995 bool ret = AsmPrinter::doFinalization(M);
996
997 // now we restore global variables
Justin Holewinski0497ab12013-03-30 14:29:21 +0000998 for (i = 0; i < n; i++)
Justin Holewinskiae556d32012-05-04 20:18:50 +0000999 global_list.insert(global_list.end(), gv_array[i]);
1000
1001 delete[] gv_array;
1002 return ret;
1003
Justin Holewinskiae556d32012-05-04 20:18:50 +00001004 //bool Result = AsmPrinter::doFinalization(M);
1005 // Instead of calling the parents doFinalization, we may
1006 // clone parents doFinalization and customize here.
1007 // Currently, we if NVISA out the EmitGlobals() in
1008 // parent's doFinalization, which is too intrusive.
1009 //
1010 // Same for the doInitialization.
1011 //return Result;
1012}
1013
1014// This function emits appropriate linkage directives for
1015// functions and global variables.
1016//
1017// extern function declaration -> .extern
1018// extern function definition -> .visible
1019// external global variable with init -> .visible
1020// external without init -> .extern
1021// appending -> not allowed, assert.
1022
Justin Holewinski0497ab12013-03-30 14:29:21 +00001023void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1024 raw_ostream &O) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001025 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1026 if (V->hasExternalLinkage()) {
1027 if (isa<GlobalVariable>(V)) {
1028 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1029 if (GVar) {
1030 if (GVar->hasInitializer())
1031 O << ".visible ";
1032 else
1033 O << ".extern ";
1034 }
1035 } else if (V->isDeclaration())
1036 O << ".extern ";
1037 else
1038 O << ".visible ";
1039 } else if (V->hasAppendingLinkage()) {
1040 std::string msg;
1041 msg.append("Error: ");
1042 msg.append("Symbol ");
1043 if (V->hasName())
1044 msg.append(V->getName().str());
1045 msg.append("has unsupported appending linkage type");
1046 llvm_unreachable(msg.c_str());
1047 }
1048 }
1049}
1050
Justin Holewinski01f89f02013-05-20 12:13:32 +00001051void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1052 raw_ostream &O,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001053 bool processDemoted) {
1054
1055 // Skip meta data
1056 if (GVar->hasSection()) {
1057 if (GVar->getSection() == "llvm.metadata")
1058 return;
1059 }
1060
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001061 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001062
1063 // GlobalVariables are always constant pointers themselves.
1064 const PointerType *PTy = GVar->getType();
1065 Type *ETy = PTy->getElementType();
1066
1067 if (GVar->hasExternalLinkage()) {
1068 if (GVar->hasInitializer())
1069 O << ".visible ";
1070 else
1071 O << ".extern ";
1072 }
1073
1074 if (llvm::isTexture(*GVar)) {
1075 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1076 return;
1077 }
1078
1079 if (llvm::isSurface(*GVar)) {
1080 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1081 return;
1082 }
1083
1084 if (GVar->isDeclaration()) {
1085 // (extern) declarations, no definition or initializer
1086 // Currently the only known declaration is for an automatic __local
1087 // (.shared) promoted to global.
1088 emitPTXGlobalVariable(GVar, O);
1089 O << ";\n";
1090 return;
1091 }
1092
1093 if (llvm::isSampler(*GVar)) {
1094 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1095
Justin Holewinski01f89f02013-05-20 12:13:32 +00001096 const Constant *Initializer = NULL;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001097 if (GVar->hasInitializer())
1098 Initializer = GVar->getInitializer();
Justin Holewinski01f89f02013-05-20 12:13:32 +00001099 const ConstantInt *CI = NULL;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001100 if (Initializer)
1101 CI = dyn_cast<ConstantInt>(Initializer);
1102 if (CI) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001103 unsigned sample = CI->getZExtValue();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001104
1105 O << " = { ";
1106
Justin Holewinski0497ab12013-03-30 14:29:21 +00001107 for (int i = 0,
1108 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1109 i < 3; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001110 O << "addr_mode_" << i << " = ";
1111 switch (addr) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001112 case 0:
1113 O << "wrap";
1114 break;
1115 case 1:
1116 O << "clamp_to_border";
1117 break;
1118 case 2:
1119 O << "clamp_to_edge";
1120 break;
1121 case 3:
1122 O << "wrap";
1123 break;
1124 case 4:
1125 O << "mirror";
1126 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001127 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001128 O << ", ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001129 }
1130 O << "filter_mode = ";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001131 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1132 case 0:
1133 O << "nearest";
1134 break;
1135 case 1:
1136 O << "linear";
1137 break;
1138 case 2:
1139 assert(0 && "Anisotropic filtering is not supported");
1140 default:
1141 O << "nearest";
1142 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001143 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001144 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001145 O << ", force_unnormalized_coords = 1";
1146 }
1147 O << " }";
1148 }
1149
1150 O << ";\n";
1151 return;
1152 }
1153
1154 if (GVar->hasPrivateLinkage()) {
1155
1156 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1157 return;
1158
1159 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1160 if (!strncmp(GVar->getName().data(), "filename", 8))
1161 return;
1162 if (GVar->use_empty())
1163 return;
1164 }
1165
1166 const Function *demotedFunc = 0;
1167 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1168 O << "// " << GVar->getName().str() << " has been demoted\n";
1169 if (localDecls.find(demotedFunc) != localDecls.end())
1170 localDecls[demotedFunc].push_back(GVar);
1171 else {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001172 std::vector<const GlobalVariable *> temp;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001173 temp.push_back(GVar);
1174 localDecls[demotedFunc] = temp;
1175 }
1176 return;
1177 }
1178
1179 O << ".";
1180 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1181 if (GVar->getAlignment() == 0)
1182 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1183 else
1184 O << " .align " << GVar->getAlignment();
1185
Justin Holewinskiae556d32012-05-04 20:18:50 +00001186 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1187 O << " .";
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001188 // Special case: ABI requires that we use .u8 for predicates
1189 if (ETy->isIntegerTy(1))
1190 O << "u8";
1191 else
1192 O << getPTXFundamentalTypeStr(ETy, false);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001193 O << " ";
1194 O << *Mang->getSymbol(GVar);
1195
1196 // Ptx allows variable initilization only for constant and global state
1197 // spaces.
1198 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001199 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1200 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001201 const Constant *Initializer = GVar->getInitializer();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001202 if (!Initializer->isNullValue()) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001203 O << " = ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001204 printScalarConstant(Initializer, O);
1205 }
1206 }
1207 } else {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001208 unsigned int ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001209
1210 // Although PTX has direct support for struct type and array type and
1211 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1212 // targets that support these high level field accesses. Structs, arrays
1213 // and vectors are lowered into arrays of bytes.
1214 switch (ETy->getTypeID()) {
1215 case Type::StructTyID:
1216 case Type::ArrayTyID:
1217 case Type::VectorTyID:
1218 ElementSize = TD->getTypeStoreSize(ETy);
1219 // Ptx allows variable initilization only for constant and
1220 // global state spaces.
1221 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
Justin Holewinski0497ab12013-03-30 14:29:21 +00001222 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1223 GVar->hasInitializer()) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001224 const Constant *Initializer = GVar->getInitializer();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001225 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001226 AggBuffer aggBuffer(ElementSize, O, *this);
1227 bufferAggregateConstant(Initializer, &aggBuffer);
1228 if (aggBuffer.numSymbols) {
1229 if (nvptxSubtarget.is64Bit()) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001230 O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1231 O << ElementSize / 8;
1232 } else {
1233 O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1234 O << ElementSize / 4;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001235 }
1236 O << "]";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001237 } else {
1238 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001239 O << ElementSize;
1240 O << "]";
1241 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001242 O << " = {";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001243 aggBuffer.print();
1244 O << "}";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001245 } else {
1246 O << " .b8 " << *Mang->getSymbol(GVar);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001247 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001248 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001249 O << ElementSize;
1250 O << "]";
1251 }
1252 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001253 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001254 O << " .b8 " << *Mang->getSymbol(GVar);
1255 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001256 O << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001257 O << ElementSize;
1258 O << "]";
1259 }
1260 }
1261 break;
1262 default:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001263 assert(0 && "type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001264 }
1265
1266 }
1267 O << ";\n";
1268}
1269
1270void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1271 if (localDecls.find(f) == localDecls.end())
1272 return;
1273
Justin Holewinski01f89f02013-05-20 12:13:32 +00001274 std::vector<const GlobalVariable *> &gvars = localDecls[f];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001275
Justin Holewinski0497ab12013-03-30 14:29:21 +00001276 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001277 O << "\t// demoted variable\n\t";
1278 printModuleLevelGV(gvars[i], O, true);
1279 }
1280}
1281
1282void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1283 raw_ostream &O) const {
1284 switch (AddressSpace) {
1285 case llvm::ADDRESS_SPACE_LOCAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001286 O << "local";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001287 break;
1288 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001289 O << "global";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001290 break;
1291 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001292 O << "const";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001293 break;
1294 case llvm::ADDRESS_SPACE_SHARED:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001295 O << "shared";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001296 break;
1297 default:
Justin Holewinski36a50992013-02-09 13:34:15 +00001298 report_fatal_error("Bad address space found while emitting PTX");
1299 break;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001300 }
1301}
1302
Justin Holewinski0497ab12013-03-30 14:29:21 +00001303std::string
1304NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001305 switch (Ty->getTypeID()) {
1306 default:
1307 llvm_unreachable("unexpected type");
1308 break;
1309 case Type::IntegerTyID: {
1310 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1311 if (NumBits == 1)
1312 return "pred";
1313 else if (NumBits <= 64) {
1314 std::string name = "u";
1315 return name + utostr(NumBits);
1316 } else {
1317 llvm_unreachable("Integer too large");
1318 break;
1319 }
1320 break;
1321 }
1322 case Type::FloatTyID:
1323 return "f32";
1324 case Type::DoubleTyID:
1325 return "f64";
1326 case Type::PointerTyID:
1327 if (nvptxSubtarget.is64Bit())
Justin Holewinski0497ab12013-03-30 14:29:21 +00001328 if (useB4PTR)
1329 return "b64";
1330 else
1331 return "u64";
1332 else if (useB4PTR)
1333 return "b32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001334 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001335 return "u32";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001336 }
1337 llvm_unreachable("unexpected type");
1338 return NULL;
1339}
1340
Justin Holewinski0497ab12013-03-30 14:29:21 +00001341void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001342 raw_ostream &O) {
1343
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001344 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001345
1346 // GlobalVariables are always constant pointers themselves.
1347 const PointerType *PTy = GVar->getType();
1348 Type *ETy = PTy->getElementType();
1349
1350 O << ".";
1351 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1352 if (GVar->getAlignment() == 0)
1353 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1354 else
1355 O << " .align " << GVar->getAlignment();
1356
1357 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1358 O << " .";
1359 O << getPTXFundamentalTypeStr(ETy);
1360 O << " ";
1361 O << *Mang->getSymbol(GVar);
1362 return;
1363 }
1364
Justin Holewinski0497ab12013-03-30 14:29:21 +00001365 int64_t ElementSize = 0;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001366
1367 // Although PTX has direct support for struct type and array type and LLVM IR
1368 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1369 // support these high level field accesses. Structs and arrays are lowered
1370 // into arrays of bytes.
1371 switch (ETy->getTypeID()) {
1372 case Type::StructTyID:
1373 case Type::ArrayTyID:
1374 case Type::VectorTyID:
1375 ElementSize = TD->getTypeStoreSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001376 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001377 if (ElementSize) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001378 O << itostr(ElementSize);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001379 }
1380 O << "]";
1381 break;
1382 default:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001383 assert(0 && "type not supported yet");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001384 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001385 return;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001386}
1387
Justin Holewinski0497ab12013-03-30 14:29:21 +00001388static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001389 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1390 return TD->getPrefTypeAlignment(Ty);
1391
1392 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1393 if (ATy)
1394 return getOpenCLAlignment(TD, ATy->getElementType());
1395
1396 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1397 if (VTy) {
1398 Type *ETy = VTy->getElementType();
1399 unsigned int numE = VTy->getNumElements();
1400 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1401 if (numE == 3)
Justin Holewinski0497ab12013-03-30 14:29:21 +00001402 return 4 * alignE;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001403 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001404 return numE * alignE;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001405 }
1406
1407 const StructType *STy = dyn_cast<StructType>(Ty);
1408 if (STy) {
1409 unsigned int alignStruct = 1;
1410 // Go through each element of the struct and find the
1411 // largest alignment.
Justin Holewinski0497ab12013-03-30 14:29:21 +00001412 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001413 Type *ETy = STy->getElementType(i);
1414 unsigned int align = getOpenCLAlignment(TD, ETy);
1415 if (align > alignStruct)
1416 alignStruct = align;
1417 }
1418 return alignStruct;
1419 }
1420
1421 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1422 if (FTy)
Chandler Carruth5da3f052012-11-01 09:14:31 +00001423 return TD->getPointerPrefAlignment();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001424 return TD->getPrefTypeAlignment(Ty);
1425}
1426
1427void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1428 int paramIndex, raw_ostream &O) {
1429 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1430 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
Justin Holewinski4c47d872013-05-20 16:42:18 +00001431 O << *Mang->getSymbol(I->getParent()) << "_param_" << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001432 else {
1433 std::string argName = I->getName();
1434 const char *p = argName.c_str();
1435 while (*p) {
1436 if (*p == '.')
1437 O << "_";
1438 else
1439 O << *p;
1440 p++;
1441 }
1442 }
1443}
1444
1445void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1446 Function::const_arg_iterator I, E;
1447 int i = 0;
1448
1449 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1450 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1451 O << *CurrentFnSym << "_param_" << paramIndex;
1452 return;
1453 }
1454
1455 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001456 if (i == paramIndex) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001457 printParamName(I, paramIndex, O);
1458 return;
1459 }
1460 }
1461 llvm_unreachable("paramIndex out of bound");
1462}
1463
Justin Holewinski0497ab12013-03-30 14:29:21 +00001464void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001465 const DataLayout *TD = TM.getDataLayout();
Bill Wendlinge94d8432012-12-07 23:16:57 +00001466 const AttributeSet &PAL = F->getAttributes();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001467 const TargetLowering *TLI = TM.getTargetLowering();
1468 Function::const_arg_iterator I, E;
1469 unsigned paramIndex = 0;
1470 bool first = true;
1471 bool isKernelFunc = llvm::isKernelFunction(*F);
1472 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1473 MVT thePointerTy = TLI->getPointerTy();
1474
1475 O << "(\n";
1476
1477 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001478 Type *Ty = I->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001479
1480 if (!first)
1481 O << ",\n";
1482
1483 first = false;
1484
1485 // Handle image/sampler parameters
1486 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1487 if (llvm::isImage(*I)) {
1488 std::string sname = I->getName();
1489 if (llvm::isImageWriteOnly(*I))
Justin Holewinski4c47d872013-05-20 16:42:18 +00001490 O << "\t.param .surfref " << *Mang->getSymbol(F) << "_param_"
1491 << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001492 else // Default image is read_only
Justin Holewinski4c47d872013-05-20 16:42:18 +00001493 O << "\t.param .texref " << *Mang->getSymbol(F) << "_param_"
1494 << paramIndex;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001495 } else // Should be llvm::isSampler(*I)
Justin Holewinski4c47d872013-05-20 16:42:18 +00001496 O << "\t.param .samplerref " << *Mang->getSymbol(F) << "_param_"
Justin Holewinski0497ab12013-03-30 14:29:21 +00001497 << paramIndex;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001498 continue;
1499 }
1500
Justin Holewinski0497ab12013-03-30 14:29:21 +00001501 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
Justin Holewinskie9884092013-03-24 21:17:47 +00001502 if (Ty->isVectorTy()) {
1503 // Just print .param .b8 .align <a> .param[size];
1504 // <a> = PAL.getparamalignment
1505 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001506 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinskie9884092013-03-24 21:17:47 +00001507 if (align == 0)
1508 align = TD->getABITypeAlignment(Ty);
1509
1510 unsigned sz = TD->getTypeAllocSize(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001511 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskie9884092013-03-24 21:17:47 +00001512 printParamName(I, paramIndex, O);
1513 O << "[" << sz << "]";
1514
1515 continue;
1516 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001517 // Just a scalar
1518 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1519 if (isKernelFunc) {
1520 if (PTy) {
1521 // Special handling for pointer arguments to kernel
1522 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1523
1524 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1525 Type *ETy = PTy->getElementType();
1526 int addrSpace = PTy->getAddressSpace();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001527 switch (addrSpace) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001528 default:
1529 O << ".ptr ";
1530 break;
Justin Holewinskib96d1392013-06-10 13:29:47 +00001531 case llvm::ADDRESS_SPACE_CONST:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001532 O << ".ptr .const ";
1533 break;
1534 case llvm::ADDRESS_SPACE_SHARED:
1535 O << ".ptr .shared ";
1536 break;
1537 case llvm::ADDRESS_SPACE_GLOBAL:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001538 O << ".ptr .global ";
1539 break;
1540 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001541 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001542 }
1543 printParamName(I, paramIndex, O);
1544 continue;
1545 }
1546
1547 // non-pointer scalar to kernel func
Justin Holewinski700b6fa2013-05-20 12:13:28 +00001548 O << "\t.param .";
1549 // Special case: predicate operands become .u8 types
1550 if (Ty->isIntegerTy(1))
1551 O << "u8";
1552 else
1553 O << getPTXFundamentalTypeStr(Ty);
1554 O << " ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001555 printParamName(I, paramIndex, O);
1556 continue;
1557 }
1558 // Non-kernel function, just print .param .b<size> for ABI
1559 // and .reg .b<size> for non ABY
1560 unsigned sz = 0;
1561 if (isa<IntegerType>(Ty)) {
1562 sz = cast<IntegerType>(Ty)->getBitWidth();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001563 if (sz < 32)
1564 sz = 32;
1565 } else if (isa<PointerType>(Ty))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001566 sz = thePointerTy.getSizeInBits();
1567 else
1568 sz = Ty->getPrimitiveSizeInBits();
1569 if (isABI)
1570 O << "\t.param .b" << sz << " ";
1571 else
1572 O << "\t.reg .b" << sz << " ";
1573 printParamName(I, paramIndex, O);
1574 continue;
1575 }
1576
1577 // param has byVal attribute. So should be a pointer
1578 const PointerType *PTy = dyn_cast<PointerType>(Ty);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001579 assert(PTy && "Param with byval attribute should be a pointer type");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001580 Type *ETy = PTy->getElementType();
1581
1582 if (isABI || isKernelFunc) {
1583 // Just print .param .b8 .align <a> .param[size];
1584 // <a> = PAL.getparamalignment
1585 // size = typeallocsize of element type
Justin Holewinski0497ab12013-03-30 14:29:21 +00001586 unsigned align = PAL.getParamAlignment(paramIndex + 1);
Justin Holewinski2dc9d072012-11-09 23:50:24 +00001587 if (align == 0)
1588 align = TD->getABITypeAlignment(ETy);
1589
Justin Holewinskiae556d32012-05-04 20:18:50 +00001590 unsigned sz = TD->getTypeAllocSize(ETy);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001591 O << "\t.param .align " << align << " .b8 ";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001592 printParamName(I, paramIndex, O);
1593 O << "[" << sz << "]";
1594 continue;
1595 } else {
1596 // Split the ETy into constituent parts and
1597 // print .param .b<size> <name> for each part.
1598 // Further, if a part is vector, print the above for
1599 // each vector element.
1600 SmallVector<EVT, 16> vtparts;
1601 ComputeValueVTs(*TLI, ETy, vtparts);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001602 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001603 unsigned elems = 1;
1604 EVT elemtype = vtparts[i];
1605 if (vtparts[i].isVector()) {
1606 elems = vtparts[i].getVectorNumElements();
1607 elemtype = vtparts[i].getVectorElementType();
1608 }
1609
Justin Holewinski0497ab12013-03-30 14:29:21 +00001610 for (unsigned j = 0, je = elems; j != je; ++j) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001611 unsigned sz = elemtype.getSizeInBits();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001612 if (elemtype.isInteger() && (sz < 32))
1613 sz = 32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001614 O << "\t.reg .b" << sz << " ";
1615 printParamName(I, paramIndex, O);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001616 if (j < je - 1)
1617 O << ",\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001618 ++paramIndex;
1619 }
Justin Holewinski0497ab12013-03-30 14:29:21 +00001620 if (i < e - 1)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001621 O << ",\n";
1622 }
1623 --paramIndex;
1624 continue;
1625 }
1626 }
1627
1628 O << "\n)\n";
1629}
1630
1631void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1632 raw_ostream &O) {
1633 const Function *F = MF.getFunction();
1634 emitFunctionParamList(F, O);
1635}
1636
Justin Holewinski0497ab12013-03-30 14:29:21 +00001637void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1638 const MachineFunction &MF) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001639 SmallString<128> Str;
1640 raw_svector_ostream O(Str);
1641
1642 // Map the global virtual register number to a register class specific
1643 // virtual register number starting from 1 with that class.
1644 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1645 //unsigned numRegClasses = TRI->getNumRegClasses();
1646
1647 // Emit the Fake Stack Object
1648 const MachineFrameInfo *MFI = MF.getFrameInfo();
1649 int NumBytes = (int) MFI->getStackSize();
1650 if (NumBytes) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001651 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1652 << getFunctionNumber() << "[" << NumBytes << "];\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001653 if (nvptxSubtarget.is64Bit()) {
1654 O << "\t.reg .b64 \t%SP;\n";
1655 O << "\t.reg .b64 \t%SPL;\n";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001656 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001657 O << "\t.reg .b32 \t%SP;\n";
1658 O << "\t.reg .b32 \t%SPL;\n";
1659 }
1660 }
1661
1662 // Go through all virtual registers to establish the mapping between the
1663 // global virtual
1664 // register number and the per class virtual register number.
1665 // We use the per class virtual register number in the ptx output.
1666 unsigned int numVRs = MRI->getNumVirtRegs();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001667 for (unsigned i = 0; i < numVRs; i++) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001668 unsigned int vr = TRI->index2VirtReg(i);
1669 const TargetRegisterClass *RC = MRI->getRegClass(vr);
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001670 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
Justin Holewinskiae556d32012-05-04 20:18:50 +00001671 int n = regmap.size();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001672 regmap.insert(std::make_pair(vr, n + 1));
Justin Holewinskiae556d32012-05-04 20:18:50 +00001673 }
1674
1675 // Emit register declarations
1676 // @TODO: Extract out the real register usage
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001677 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1678 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1679 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1680 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1681 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1682 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1683 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
Justin Holewinskiae556d32012-05-04 20:18:50 +00001684
1685 // Emit declaration of the virtual registers or 'physical' registers for
1686 // each register class
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001687 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1688 const TargetRegisterClass *RC = TRI->getRegClass(i);
1689 DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1690 std::string rcname = getNVPTXRegClassName(RC);
1691 std::string rcStr = getNVPTXRegClassStr(RC);
1692 int n = regmap.size();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001693
Justin Holewinskidbb3b2f2013-05-31 12:14:49 +00001694 // Only declare those registers that may be used.
1695 if (n) {
1696 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1697 << ">;\n";
1698 }
1699 }
Justin Holewinskiae556d32012-05-04 20:18:50 +00001700
1701 OutStreamer.EmitRawText(O.str());
1702}
1703
Justin Holewinskiae556d32012-05-04 20:18:50 +00001704void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001705 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
Justin Holewinskiae556d32012-05-04 20:18:50 +00001706 bool ignored;
1707 unsigned int numHex;
1708 const char *lead;
1709
Justin Holewinski0497ab12013-03-30 14:29:21 +00001710 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001711 numHex = 8;
1712 lead = "0f";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001713 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001714 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1715 numHex = 16;
1716 lead = "0d";
Justin Holewinski0497ab12013-03-30 14:29:21 +00001717 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001718 } else
1719 llvm_unreachable("unsupported fp type");
1720
1721 APInt API = APF.bitcastToAPInt();
1722 std::string hexstr(utohexstr(API.getZExtValue()));
1723 O << lead;
1724 if (hexstr.length() < numHex)
1725 O << std::string(numHex - hexstr.length(), '0');
1726 O << utohexstr(API.getZExtValue());
1727}
1728
Justin Holewinski01f89f02013-05-20 12:13:32 +00001729void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1730 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001731 O << CI->getValue();
1732 return;
1733 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001734 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001735 printFPConstant(CFP, O);
1736 return;
1737 }
1738 if (isa<ConstantPointerNull>(CPV)) {
1739 O << "0";
1740 return;
1741 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001742 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001743 O << *Mang->getSymbol(GVar);
1744 return;
1745 }
Justin Holewinski01f89f02013-05-20 12:13:32 +00001746 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1747 const Value *v = Cexpr->stripPointerCasts();
1748 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001749 O << *Mang->getSymbol(GVar);
1750 return;
1751 } else {
1752 O << *LowerConstant(CPV, *this);
1753 return;
1754 }
1755 }
1756 llvm_unreachable("Not scalar type found in printScalarConstant()");
1757}
1758
Justin Holewinski01f89f02013-05-20 12:13:32 +00001759void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001760 AggBuffer *aggBuffer) {
1761
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001762 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001763
1764 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1765 int s = TD->getTypeAllocSize(CPV->getType());
Justin Holewinski0497ab12013-03-30 14:29:21 +00001766 if (s < Bytes)
Justin Holewinskiae556d32012-05-04 20:18:50 +00001767 s = Bytes;
1768 aggBuffer->addZeros(s);
1769 return;
1770 }
1771
1772 unsigned char *ptr;
1773 switch (CPV->getType()->getTypeID()) {
1774
1775 case Type::IntegerTyID: {
1776 const Type *ETy = CPV->getType();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001777 if (ETy == Type::getInt8Ty(CPV->getContext())) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001778 unsigned char c =
1779 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1780 ptr = &c;
1781 aggBuffer->addBytes(ptr, 1, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001782 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1783 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1784 ptr = (unsigned char *)&int16;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001785 aggBuffer->addBytes(ptr, 2, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001786 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001787 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001788 int int32 = (int)(constInt->getZExtValue());
1789 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001790 aggBuffer->addBytes(ptr, 4, Bytes);
1791 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001792 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1793 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Justin Holewinski0497ab12013-03-30 14:29:21 +00001794 ConstantFoldConstantExpression(Cexpr, TD))) {
1795 int int32 = (int)(constInt->getZExtValue());
1796 ptr = (unsigned char *)&int32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001797 aggBuffer->addBytes(ptr, 4, Bytes);
1798 break;
1799 }
1800 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1801 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1802 aggBuffer->addSymbol(v);
1803 aggBuffer->addZeros(4);
1804 break;
1805 }
1806 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001807 llvm_unreachable("unsupported integer const type");
Justin Holewinski0497ab12013-03-30 14:29:21 +00001808 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001809 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001810 long long int64 = (long long)(constInt->getZExtValue());
1811 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001812 aggBuffer->addBytes(ptr, 8, Bytes);
1813 break;
Justin Holewinski01f89f02013-05-20 12:13:32 +00001814 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1815 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
Justin Holewinski0497ab12013-03-30 14:29:21 +00001816 ConstantFoldConstantExpression(Cexpr, TD))) {
1817 long long int64 = (long long)(constInt->getZExtValue());
1818 ptr = (unsigned char *)&int64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001819 aggBuffer->addBytes(ptr, 8, Bytes);
1820 break;
1821 }
1822 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1823 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1824 aggBuffer->addSymbol(v);
1825 aggBuffer->addZeros(8);
1826 break;
1827 }
1828 }
1829 llvm_unreachable("unsupported integer const type");
Craig Topperbdf39a42012-05-24 07:02:50 +00001830 } else
Justin Holewinskiae556d32012-05-04 20:18:50 +00001831 llvm_unreachable("unsupported integer const type");
1832 break;
1833 }
1834 case Type::FloatTyID:
1835 case Type::DoubleTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001836 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001837 const Type *Ty = CFP->getType();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001838 if (Ty == Type::getFloatTy(CPV->getContext())) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001839 float float32 = (float) CFP->getValueAPF().convertToFloat();
1840 ptr = (unsigned char *)&float32;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001841 aggBuffer->addBytes(ptr, 4, Bytes);
1842 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1843 double float64 = CFP->getValueAPF().convertToDouble();
Justin Holewinski0497ab12013-03-30 14:29:21 +00001844 ptr = (unsigned char *)&float64;
Justin Holewinskiae556d32012-05-04 20:18:50 +00001845 aggBuffer->addBytes(ptr, 8, Bytes);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001846 } else {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001847 llvm_unreachable("unsupported fp const type");
1848 }
1849 break;
1850 }
1851 case Type::PointerTyID: {
Justin Holewinski01f89f02013-05-20 12:13:32 +00001852 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001853 aggBuffer->addSymbol(GVar);
Justin Holewinski01f89f02013-05-20 12:13:32 +00001854 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1855 const Value *v = Cexpr->stripPointerCasts();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001856 aggBuffer->addSymbol(v);
1857 }
1858 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1859 aggBuffer->addZeros(s);
1860 break;
1861 }
1862
1863 case Type::ArrayTyID:
1864 case Type::VectorTyID:
1865 case Type::StructTyID: {
1866 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1867 isa<ConstantStruct>(CPV)) {
1868 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1869 bufferAggregateConstant(CPV, aggBuffer);
Justin Holewinski0497ab12013-03-30 14:29:21 +00001870 if (Bytes > ElementSize)
1871 aggBuffer->addZeros(Bytes - ElementSize);
1872 } else if (isa<ConstantAggregateZero>(CPV))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001873 aggBuffer->addZeros(Bytes);
1874 else
1875 llvm_unreachable("Unexpected Constant type");
1876 break;
1877 }
1878
1879 default:
1880 llvm_unreachable("unsupported type");
1881 }
1882}
1883
Justin Holewinski01f89f02013-05-20 12:13:32 +00001884void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
Justin Holewinskiae556d32012-05-04 20:18:50 +00001885 AggBuffer *aggBuffer) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001886 const DataLayout *TD = TM.getDataLayout();
Justin Holewinskiae556d32012-05-04 20:18:50 +00001887 int Bytes;
1888
1889 // Old constants
1890 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1891 if (CPV->getNumOperands())
1892 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1893 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1894 return;
1895 }
1896
1897 if (const ConstantDataSequential *CDS =
Justin Holewinski0497ab12013-03-30 14:29:21 +00001898 dyn_cast<ConstantDataSequential>(CPV)) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001899 if (CDS->getNumElements())
1900 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1901 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1902 aggBuffer);
1903 return;
1904 }
1905
Justin Holewinskiae556d32012-05-04 20:18:50 +00001906 if (isa<ConstantStruct>(CPV)) {
1907 if (CPV->getNumOperands()) {
1908 StructType *ST = cast<StructType>(CPV->getType());
1909 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00001910 if (i == (e - 1))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001911 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
Justin Holewinski0497ab12013-03-30 14:29:21 +00001912 TD->getTypeAllocSize(ST) -
1913 TD->getStructLayout(ST)->getElementOffset(i);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001914 else
Justin Holewinski0497ab12013-03-30 14:29:21 +00001915 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1916 TD->getStructLayout(ST)->getElementOffset(i);
1917 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
Justin Holewinskiae556d32012-05-04 20:18:50 +00001918 }
1919 }
1920 return;
1921 }
Craig Topperbdf39a42012-05-24 07:02:50 +00001922 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinskiae556d32012-05-04 20:18:50 +00001923}
1924
1925// buildTypeNameMap - Run through symbol table looking for type names.
1926//
1927
Justin Holewinskiae556d32012-05-04 20:18:50 +00001928bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1929
1930 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1931
Justin Holewinski0497ab12013-03-30 14:29:21 +00001932 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1933 !PI->second.compare("struct._image2d_t") ||
1934 !PI->second.compare("struct._image3d_t")))
Justin Holewinskiae556d32012-05-04 20:18:50 +00001935 return true;
1936
1937 return false;
1938}
1939
Justin Holewinskiae556d32012-05-04 20:18:50 +00001940
Justin Holewinski0497ab12013-03-30 14:29:21 +00001941bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1942 switch (MI.getOpcode()) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00001943 default:
1944 return false;
Justin Holewinski0497ab12013-03-30 14:29:21 +00001945 case NVPTX::CallArgBeginInst:
1946 case NVPTX::CallArgEndInst0:
1947 case NVPTX::CallArgEndInst1:
1948 case NVPTX::CallArgF32:
1949 case NVPTX::CallArgF64:
1950 case NVPTX::CallArgI16:
1951 case NVPTX::CallArgI32:
1952 case NVPTX::CallArgI32imm:
1953 case NVPTX::CallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001954 case NVPTX::CallArgParam:
1955 case NVPTX::CallVoidInst:
1956 case NVPTX::CallVoidInstReg:
1957 case NVPTX::Callseq_End:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001958 case NVPTX::CallVoidInstReg64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001959 case NVPTX::DeclareParamInst:
1960 case NVPTX::DeclareRetMemInst:
1961 case NVPTX::DeclareRetRegInst:
1962 case NVPTX::DeclareRetScalarInst:
1963 case NVPTX::DeclareScalarParamInst:
1964 case NVPTX::DeclareScalarRegInst:
1965 case NVPTX::StoreParamF32:
1966 case NVPTX::StoreParamF64:
1967 case NVPTX::StoreParamI16:
1968 case NVPTX::StoreParamI32:
1969 case NVPTX::StoreParamI64:
1970 case NVPTX::StoreParamI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001971 case NVPTX::StoreRetvalF32:
1972 case NVPTX::StoreRetvalF64:
1973 case NVPTX::StoreRetvalI16:
1974 case NVPTX::StoreRetvalI32:
1975 case NVPTX::StoreRetvalI64:
1976 case NVPTX::StoreRetvalI8:
1977 case NVPTX::LastCallArgF32:
1978 case NVPTX::LastCallArgF64:
1979 case NVPTX::LastCallArgI16:
1980 case NVPTX::LastCallArgI32:
1981 case NVPTX::LastCallArgI32imm:
1982 case NVPTX::LastCallArgI64:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001983 case NVPTX::LastCallArgParam:
1984 case NVPTX::LoadParamMemF32:
1985 case NVPTX::LoadParamMemF64:
1986 case NVPTX::LoadParamMemI16:
1987 case NVPTX::LoadParamMemI32:
1988 case NVPTX::LoadParamMemI64:
1989 case NVPTX::LoadParamMemI8:
Justin Holewinski0497ab12013-03-30 14:29:21 +00001990 case NVPTX::PrototypeInst:
1991 case NVPTX::DBG_VALUE:
Justin Holewinskiae556d32012-05-04 20:18:50 +00001992 return true;
1993 }
1994 return false;
1995}
1996
Justin Holewinskiaaa8b6e2013-08-24 01:17:23 +00001997/// PrintAsmOperand - Print out an operand for an inline asm expression.
1998///
1999bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2000 unsigned AsmVariant,
2001 const char *ExtraCode, raw_ostream &O) {
2002 if (ExtraCode && ExtraCode[0]) {
2003 if (ExtraCode[1] != 0)
2004 return true; // Unknown modifier.
2005
2006 switch (ExtraCode[0]) {
2007 default:
2008 // See if this is a generic print operand
2009 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2010 case 'r':
2011 break;
2012 }
2013 }
2014
2015 printOperand(MI, OpNo, O);
2016
2017 return false;
2018}
2019
2020bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2021 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2022 const char *ExtraCode, raw_ostream &O) {
2023 if (ExtraCode && ExtraCode[0])
2024 return true; // Unknown modifier
2025
2026 O << '[';
2027 printMemOperand(MI, OpNo, O);
2028 O << ']';
2029
2030 return false;
2031}
2032
2033void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2034 raw_ostream &O, const char *Modifier) {
2035 const MachineOperand &MO = MI->getOperand(opNum);
2036 switch (MO.getType()) {
2037 case MachineOperand::MO_Register:
2038 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2039 if (MO.getReg() == NVPTX::VRDepot)
2040 O << DEPOTNAME << getFunctionNumber();
2041 else
2042 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2043 } else {
2044 emitVirtualRegister(MO.getReg(), false, O);
2045 }
2046 return;
2047
2048 case MachineOperand::MO_Immediate:
2049 if (!Modifier)
2050 O << MO.getImm();
2051 else if (strstr(Modifier, "vec") == Modifier)
2052 printVecModifiedImmediate(MO, Modifier, O);
2053 else
2054 llvm_unreachable(
2055 "Don't know how to handle modifier on immediate operand");
2056 return;
2057
2058 case MachineOperand::MO_FPImmediate:
2059 printFPConstant(MO.getFPImm(), O);
2060 break;
2061
2062 case MachineOperand::MO_GlobalAddress:
2063 O << *Mang->getSymbol(MO.getGlobal());
2064 break;
2065
2066 case MachineOperand::MO_ExternalSymbol: {
2067 const char *symbname = MO.getSymbolName();
2068 if (strstr(symbname, ".PARAM") == symbname) {
2069 unsigned index;
2070 sscanf(symbname + 6, "%u[];", &index);
2071 printParamName(index, O);
2072 } else if (strstr(symbname, ".HLPPARAM") == symbname) {
2073 unsigned index;
2074 sscanf(symbname + 9, "%u[];", &index);
2075 O << *CurrentFnSym << "_param_" << index << "_offset";
2076 } else
2077 O << symbname;
2078 break;
2079 }
2080
2081 case MachineOperand::MO_MachineBasicBlock:
2082 O << *MO.getMBB()->getSymbol();
2083 return;
2084
2085 default:
2086 llvm_unreachable("Operand type not supported.");
2087 }
2088}
2089
2090void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2091 raw_ostream &O, const char *Modifier) {
2092 printOperand(MI, opNum, O);
2093
2094 if (Modifier && !strcmp(Modifier, "add")) {
2095 O << ", ";
2096 printOperand(MI, opNum + 1, O);
2097 } else {
2098 if (MI->getOperand(opNum + 1).isImm() &&
2099 MI->getOperand(opNum + 1).getImm() == 0)
2100 return; // don't print ',0' or '+0'
2101 O << "+";
2102 printOperand(MI, opNum + 1, O);
2103 }
2104}
2105
2106
Justin Holewinskiae556d32012-05-04 20:18:50 +00002107// Force static initialization.
2108extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2109 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2110 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2111}
2112
Justin Holewinskiae556d32012-05-04 20:18:50 +00002113void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2114 std::stringstream temp;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002115 LineReader *reader = this->getReader(filename.str());
Justin Holewinskiae556d32012-05-04 20:18:50 +00002116 temp << "\n//";
2117 temp << filename.str();
2118 temp << ":";
2119 temp << line;
2120 temp << " ";
2121 temp << reader->readLine(line);
2122 temp << "\n";
2123 this->OutStreamer.EmitRawText(Twine(temp.str()));
2124}
2125
Justin Holewinskiae556d32012-05-04 20:18:50 +00002126LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002127 if (reader == NULL) {
2128 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002129 }
2130
2131 if (reader->fileName() != filename) {
2132 delete reader;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002133 reader = new LineReader(filename);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002134 }
2135
2136 return reader;
2137}
2138
Justin Holewinski0497ab12013-03-30 14:29:21 +00002139std::string LineReader::readLine(unsigned lineNum) {
Justin Holewinskiae556d32012-05-04 20:18:50 +00002140 if (lineNum < theCurLine) {
2141 theCurLine = 0;
Justin Holewinski0497ab12013-03-30 14:29:21 +00002142 fstr.seekg(0, std::ios::beg);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002143 }
2144 while (theCurLine < lineNum) {
Justin Holewinski0497ab12013-03-30 14:29:21 +00002145 fstr.getline(buff, 500);
Justin Holewinskiae556d32012-05-04 20:18:50 +00002146 theCurLine++;
2147 }
2148 return buff;
2149}
2150
2151// Force static initialization.
2152extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2153 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2154 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2155}