Add clobbersPred - instruction that clobbers condition code / register which are...
[oota-llvm.git] / utils / TableGen / CodeGenTarget.cpp
1 //===- CodeGenTarget.cpp - CodeGen Target Class Wrapper ---------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class wrap target description classes used by the various code
11 // generation TableGen backends.  This makes it easier to access the data and
12 // provides a single place that needs to check it for validity.  All of these
13 // classes throw exceptions on error conditions.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "CodeGenTarget.h"
18 #include "CodeGenIntrinsics.h"
19 #include "Record.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Streams.h"
23 #include <set>
24 #include <algorithm>
25 using namespace llvm;
26
27 static cl::opt<unsigned>
28 AsmWriterNum("asmwriternum", cl::init(0),
29              cl::desc("Make -gen-asm-writer emit assembly writer #N"));
30
31 /// getValueType - Return the MCV::ValueType that the specified TableGen record
32 /// corresponds to.
33 MVT::ValueType llvm::getValueType(Record *Rec, const CodeGenTarget *CGT) {
34   return (MVT::ValueType)Rec->getValueAsInt("Value");
35 }
36
37 std::string llvm::getName(MVT::ValueType T) {
38   switch (T) {
39   case MVT::Other: return "UNKNOWN";
40   case MVT::i1:    return "MVT::i1";
41   case MVT::i8:    return "MVT::i8";
42   case MVT::i16:   return "MVT::i16";
43   case MVT::i32:   return "MVT::i32";
44   case MVT::i64:   return "MVT::i64";
45   case MVT::i128:  return "MVT::i128";
46   case MVT::iAny:  return "MVT::iAny";
47   case MVT::f32:   return "MVT::f32";
48   case MVT::f64:   return "MVT::f64";
49   case MVT::f80:   return "MVT::f80";
50   case MVT::f128:  return "MVT::f128";
51   case MVT::Flag:  return "MVT::Flag";
52   case MVT::isVoid:return "MVT::void";
53   case MVT::v8i8:  return "MVT::v8i8";
54   case MVT::v4i16: return "MVT::v4i16";
55   case MVT::v2i32: return "MVT::v2i32";
56   case MVT::v1i64: return "MVT::v1i64";
57   case MVT::v16i8: return "MVT::v16i8";
58   case MVT::v8i16: return "MVT::v8i16";
59   case MVT::v4i32: return "MVT::v4i32";
60   case MVT::v2i64: return "MVT::v2i64";
61   case MVT::v2f32: return "MVT::v2f32";
62   case MVT::v4f32: return "MVT::v4f32";
63   case MVT::v2f64: return "MVT::v2f64";
64   case MVT::iPTR:  return "TLI.getPointerTy()";
65   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
66   }
67 }
68
69 std::string llvm::getEnumName(MVT::ValueType T) {
70   switch (T) {
71   case MVT::Other: return "MVT::Other";
72   case MVT::i1:    return "MVT::i1";
73   case MVT::i8:    return "MVT::i8";
74   case MVT::i16:   return "MVT::i16";
75   case MVT::i32:   return "MVT::i32";
76   case MVT::i64:   return "MVT::i64";
77   case MVT::i128:  return "MVT::i128";
78   case MVT::iAny:  return "MVT::iAny";
79   case MVT::f32:   return "MVT::f32";
80   case MVT::f64:   return "MVT::f64";
81   case MVT::f80:   return "MVT::f80";
82   case MVT::f128:  return "MVT::f128";
83   case MVT::Flag:  return "MVT::Flag";
84   case MVT::isVoid:return "MVT::isVoid";
85   case MVT::v8i8:  return "MVT::v8i8";
86   case MVT::v4i16: return "MVT::v4i16";
87   case MVT::v2i32: return "MVT::v2i32";
88   case MVT::v1i64: return "MVT::v1i64";
89   case MVT::v16i8: return "MVT::v16i8";
90   case MVT::v8i16: return "MVT::v8i16";
91   case MVT::v4i32: return "MVT::v4i32";
92   case MVT::v2i64: return "MVT::v2i64";
93   case MVT::v2f32: return "MVT::v2f32";
94   case MVT::v4f32: return "MVT::v4f32";
95   case MVT::v2f64: return "MVT::v2f64";
96   case MVT::iPTR:  return "TLI.getPointerTy()";
97   default: assert(0 && "ILLEGAL VALUE TYPE!"); return "";
98   }
99 }
100
101
102 /// getTarget - Return the current instance of the Target class.
103 ///
104 CodeGenTarget::CodeGenTarget() {
105   std::vector<Record*> Targets = Records.getAllDerivedDefinitions("Target");
106   if (Targets.size() == 0)
107     throw std::string("ERROR: No 'Target' subclasses defined!");
108   if (Targets.size() != 1)
109     throw std::string("ERROR: Multiple subclasses of Target defined!");
110   TargetRec = Targets[0];
111 }
112
113
114 const std::string &CodeGenTarget::getName() const {
115   return TargetRec->getName();
116 }
117
118 Record *CodeGenTarget::getInstructionSet() const {
119   return TargetRec->getValueAsDef("InstructionSet");
120 }
121
122 /// getAsmWriter - Return the AssemblyWriter definition for this target.
123 ///
124 Record *CodeGenTarget::getAsmWriter() const {
125   std::vector<Record*> LI = TargetRec->getValueAsListOfDefs("AssemblyWriters");
126   if (AsmWriterNum >= LI.size())
127     throw "Target does not have an AsmWriter #" + utostr(AsmWriterNum) + "!";
128   return LI[AsmWriterNum];
129 }
130
131 void CodeGenTarget::ReadRegisters() const {
132   std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
133   if (Regs.empty())
134     throw std::string("No 'Register' subclasses defined!");
135
136   Registers.reserve(Regs.size());
137   Registers.assign(Regs.begin(), Regs.end());
138 }
139
140 CodeGenRegister::CodeGenRegister(Record *R) : TheDef(R) {
141   DeclaredSpillSize = R->getValueAsInt("SpillSize");
142   DeclaredSpillAlignment = R->getValueAsInt("SpillAlignment");
143 }
144
145 const std::string &CodeGenRegister::getName() const {
146   return TheDef->getName();
147 }
148
149 void CodeGenTarget::ReadRegisterClasses() const {
150   std::vector<Record*> RegClasses =
151     Records.getAllDerivedDefinitions("RegisterClass");
152   if (RegClasses.empty())
153     throw std::string("No 'RegisterClass' subclasses defined!");
154
155   RegisterClasses.reserve(RegClasses.size());
156   RegisterClasses.assign(RegClasses.begin(), RegClasses.end());
157 }
158
159 std::vector<unsigned char> CodeGenTarget::getRegisterVTs(Record *R) const {
160   std::vector<unsigned char> Result;
161   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
162   for (unsigned i = 0, e = RCs.size(); i != e; ++i) {
163     const CodeGenRegisterClass &RC = RegisterClasses[i];
164     for (unsigned ei = 0, ee = RC.Elements.size(); ei != ee; ++ei) {
165       if (R == RC.Elements[ei]) {
166         const std::vector<MVT::ValueType> &InVTs = RC.getValueTypes();
167         for (unsigned i = 0, e = InVTs.size(); i != e; ++i)
168           Result.push_back(InVTs[i]);
169       }
170     }
171   }
172   return Result;
173 }
174
175
176 CodeGenRegisterClass::CodeGenRegisterClass(Record *R) : TheDef(R) {
177   // Rename anonymous register classes.
178   if (R->getName().size() > 9 && R->getName()[9] == '.') {
179     static unsigned AnonCounter = 0;
180     R->setName("AnonRegClass_"+utostr(AnonCounter++));
181   } 
182   
183   std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
184   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
185     Record *Type = TypeList[i];
186     if (!Type->isSubClassOf("ValueType"))
187       throw "RegTypes list member '" + Type->getName() +
188         "' does not derive from the ValueType class!";
189     VTs.push_back(getValueType(Type));
190   }
191   assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!");
192   
193   std::vector<Record*> RegList = R->getValueAsListOfDefs("MemberList");
194   for (unsigned i = 0, e = RegList.size(); i != e; ++i) {
195     Record *Reg = RegList[i];
196     if (!Reg->isSubClassOf("Register"))
197       throw "Register Class member '" + Reg->getName() +
198             "' does not derive from the Register class!";
199     Elements.push_back(Reg);
200   }
201   
202   // Allow targets to override the size in bits of the RegisterClass.
203   unsigned Size = R->getValueAsInt("Size");
204
205   Namespace = R->getValueAsString("Namespace");
206   SpillSize = Size ? Size : MVT::getSizeInBits(VTs[0]);
207   SpillAlignment = R->getValueAsInt("Alignment");
208   MethodBodies = R->getValueAsCode("MethodBodies");
209   MethodProtos = R->getValueAsCode("MethodProtos");
210 }
211
212 const std::string &CodeGenRegisterClass::getName() const {
213   return TheDef->getName();
214 }
215
216 void CodeGenTarget::ReadLegalValueTypes() const {
217   const std::vector<CodeGenRegisterClass> &RCs = getRegisterClasses();
218   for (unsigned i = 0, e = RCs.size(); i != e; ++i)
219     for (unsigned ri = 0, re = RCs[i].VTs.size(); ri != re; ++ri)
220       LegalValueTypes.push_back(RCs[i].VTs[ri]);
221   
222   // Remove duplicates.
223   std::sort(LegalValueTypes.begin(), LegalValueTypes.end());
224   LegalValueTypes.erase(std::unique(LegalValueTypes.begin(),
225                                     LegalValueTypes.end()),
226                         LegalValueTypes.end());
227 }
228
229
230 void CodeGenTarget::ReadInstructions() const {
231   std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
232   if (Insts.size() <= 2)
233     throw std::string("No 'Instruction' subclasses defined!");
234
235   // Parse the instructions defined in the .td file.
236   std::string InstFormatName =
237     getAsmWriter()->getValueAsString("InstFormatName");
238
239   for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
240     std::string AsmStr = Insts[i]->getValueAsString(InstFormatName);
241     Instructions.insert(std::make_pair(Insts[i]->getName(),
242                                        CodeGenInstruction(Insts[i], AsmStr)));
243   }
244 }
245
246 /// getInstructionsByEnumValue - Return all of the instructions defined by the
247 /// target, ordered by their enum value.
248 void CodeGenTarget::
249 getInstructionsByEnumValue(std::vector<const CodeGenInstruction*>
250                                                  &NumberedInstructions) {
251   std::map<std::string, CodeGenInstruction>::const_iterator I;
252   I = getInstructions().find("PHI");
253   if (I == Instructions.end()) throw "Could not find 'PHI' instruction!";
254   const CodeGenInstruction *PHI = &I->second;
255   
256   I = getInstructions().find("INLINEASM");
257   if (I == Instructions.end()) throw "Could not find 'INLINEASM' instruction!";
258   const CodeGenInstruction *INLINEASM = &I->second;
259   
260   I = getInstructions().find("LABEL");
261   if (I == Instructions.end()) throw "Could not find 'LABEL' instruction!";
262   const CodeGenInstruction *LABEL = &I->second;
263   
264   // Print out the rest of the instructions now.
265   NumberedInstructions.push_back(PHI);
266   NumberedInstructions.push_back(INLINEASM);
267   NumberedInstructions.push_back(LABEL);
268   for (inst_iterator II = inst_begin(), E = inst_end(); II != E; ++II)
269     if (&II->second != PHI &&
270         &II->second != INLINEASM &&
271         &II->second != LABEL)
272       NumberedInstructions.push_back(&II->second);
273 }
274
275
276 /// isLittleEndianEncoding - Return whether this target encodes its instruction
277 /// in little-endian format, i.e. bits laid out in the order [0..n]
278 ///
279 bool CodeGenTarget::isLittleEndianEncoding() const {
280   return getInstructionSet()->getValueAsBit("isLittleEndianEncoding");
281 }
282
283
284
285 static void ParseConstraint(const std::string &CStr, CodeGenInstruction *I) {
286   // FIXME: Only supports TIED_TO for now.
287   std::string::size_type pos = CStr.find_first_of('=');
288   assert(pos != std::string::npos && "Unrecognized constraint");
289   std::string Name = CStr.substr(0, pos);
290
291   // TIED_TO: $src1 = $dst
292   std::string::size_type wpos = Name.find_first_of(" \t");
293   if (wpos == std::string::npos)
294     throw "Illegal format for tied-to constraint: '" + CStr + "'";
295   std::string DestOpName = Name.substr(0, wpos);
296   std::pair<unsigned,unsigned> DestOp = I->ParseOperandName(DestOpName, false);
297
298   Name = CStr.substr(pos+1);
299   wpos = Name.find_first_not_of(" \t");
300   if (wpos == std::string::npos)
301     throw "Illegal format for tied-to constraint: '" + CStr + "'";
302     
303   std::pair<unsigned,unsigned> SrcOp =
304     I->ParseOperandName(Name.substr(wpos), false);
305   if (SrcOp > DestOp)
306     throw "Illegal tied-to operand constraint '" + CStr + "'";
307   
308   
309   unsigned FlatOpNo = I->getFlattenedOperandNumber(SrcOp);
310   // Build the string for the operand.
311   std::string OpConstraint =
312     "((" + utostr(FlatOpNo) + " << 16) | (1 << TOI::TIED_TO))";
313
314   
315   if (!I->OperandList[DestOp.first].Constraints[DestOp.second].empty())
316     throw "Operand '" + DestOpName + "' cannot have multiple constraints!";
317   I->OperandList[DestOp.first].Constraints[DestOp.second] = OpConstraint;
318 }
319
320 static void ParseConstraints(const std::string &CStr, CodeGenInstruction *I) {
321   // Make sure the constraints list for each operand is large enough to hold
322   // constraint info, even if none is present.
323   for (unsigned i = 0, e = I->OperandList.size(); i != e; ++i) 
324     I->OperandList[i].Constraints.resize(I->OperandList[i].MINumOperands);
325   
326   if (CStr.empty()) return;
327   
328   const std::string delims(",");
329   std::string::size_type bidx, eidx;
330
331   bidx = CStr.find_first_not_of(delims);
332   while (bidx != std::string::npos) {
333     eidx = CStr.find_first_of(delims, bidx);
334     if (eidx == std::string::npos)
335       eidx = CStr.length();
336     
337     ParseConstraint(CStr.substr(bidx, eidx), I);
338     bidx = CStr.find_first_not_of(delims, eidx);
339   }
340 }
341
342 CodeGenInstruction::CodeGenInstruction(Record *R, const std::string &AsmStr)
343   : TheDef(R), AsmString(AsmStr) {
344   Name      = R->getValueAsString("Name");
345   Namespace = R->getValueAsString("Namespace");
346
347   isReturn     = R->getValueAsBit("isReturn");
348   isBranch     = R->getValueAsBit("isBranch");
349   isBarrier    = R->getValueAsBit("isBarrier");
350   isCall       = R->getValueAsBit("isCall");
351   isLoad       = R->getValueAsBit("isLoad");
352   isStore      = R->getValueAsBit("isStore");
353   bool isTwoAddress = R->getValueAsBit("isTwoAddress");
354   isPredicable = R->getValueAsBit("isPredicable");
355   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
356   isCommutable = R->getValueAsBit("isCommutable");
357   isTerminator = R->getValueAsBit("isTerminator");
358   isReMaterializable = R->getValueAsBit("isReMaterializable");
359   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
360   usesCustomDAGSchedInserter = R->getValueAsBit("usesCustomDAGSchedInserter");
361   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
362   noResults    = R->getValueAsBit("noResults");
363   clobbersPred = R->getValueAsBit("clobbersPred");
364   hasVariableNumberOfOperands = false;
365   
366   DagInit *DI;
367   try {
368     DI = R->getValueAsDag("OperandList");
369   } catch (...) {
370     // Error getting operand list, just ignore it (sparcv9).
371     AsmString.clear();
372     OperandList.clear();
373     return;
374   }
375
376   unsigned MIOperandNo = 0;
377   std::set<std::string> OperandNames;
378   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
379     DefInit *Arg = dynamic_cast<DefInit*>(DI->getArg(i));
380     if (!Arg)
381       throw "Illegal operand for the '" + R->getName() + "' instruction!";
382
383     Record *Rec = Arg->getDef();
384     std::string PrintMethod = "printOperand";
385     unsigned NumOps = 1;
386     DagInit *MIOpInfo = 0;
387     if (Rec->isSubClassOf("Operand")) {
388       PrintMethod = Rec->getValueAsString("PrintMethod");
389       MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
390       
391       // Verify that MIOpInfo has an 'ops' root value.
392       if (!dynamic_cast<DefInit*>(MIOpInfo->getOperator()) ||
393           dynamic_cast<DefInit*>(MIOpInfo->getOperator())
394                ->getDef()->getName() != "ops")
395         throw "Bad value for MIOperandInfo in operand '" + Rec->getName() +
396               "'\n";
397
398       // If we have MIOpInfo, then we have #operands equal to number of entries
399       // in MIOperandInfo.
400       if (unsigned NumArgs = MIOpInfo->getNumArgs())
401         NumOps = NumArgs;
402
403       isPredicable |= Rec->isSubClassOf("PredicateOperand");
404     } else if (Rec->getName() == "variable_ops") {
405       hasVariableNumberOfOperands = true;
406       continue;
407     } else if (!Rec->isSubClassOf("RegisterClass") && 
408                Rec->getName() != "ptr_rc")
409       throw "Unknown operand class '" + Rec->getName() +
410             "' in instruction '" + R->getName() + "' instruction!";
411
412     // Check that the operand has a name and that it's unique.
413     if (DI->getArgName(i).empty())
414       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
415         " has no name!";
416     if (!OperandNames.insert(DI->getArgName(i)).second)
417       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
418         " has the same name as a previous operand!";
419     
420     OperandList.push_back(OperandInfo(Rec, DI->getArgName(i), PrintMethod, 
421                                       MIOperandNo, NumOps, MIOpInfo));
422     MIOperandNo += NumOps;
423   }
424
425   // Parse Constraints.
426   ParseConstraints(R->getValueAsString("Constraints"), this);
427   
428   // For backward compatibility: isTwoAddress means operand 1 is tied to
429   // operand 0.
430   if (isTwoAddress) {
431     if (!OperandList[1].Constraints[0].empty())
432       throw R->getName() + ": cannot use isTwoAddress property: instruction "
433             "already has constraint set!";
434     OperandList[1].Constraints[0] = "((0 << 16) | (1 << TOI::TIED_TO))";
435   }
436   
437   // Any operands with unset constraints get 0 as their constraint.
438   for (unsigned op = 0, e = OperandList.size(); op != e; ++op)
439     for (unsigned j = 0, e = OperandList[op].MINumOperands; j != e; ++j)
440       if (OperandList[op].Constraints[j].empty())
441         OperandList[op].Constraints[j] = "0";
442   
443   // Parse the DisableEncoding field.
444   std::string DisableEncoding = R->getValueAsString("DisableEncoding");
445   while (1) {
446     std::string OpName = getToken(DisableEncoding, " ,\t");
447     if (OpName.empty()) break;
448
449     // Figure out which operand this is.
450     std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
451
452     // Mark the operand as not-to-be encoded.
453     if (Op.second >= OperandList[Op.first].DoNotEncode.size())
454       OperandList[Op.first].DoNotEncode.resize(Op.second+1);
455     OperandList[Op.first].DoNotEncode[Op.second] = true;
456   }
457 }
458
459
460
461 /// getOperandNamed - Return the index of the operand with the specified
462 /// non-empty name.  If the instruction does not have an operand with the
463 /// specified name, throw an exception.
464 ///
465 unsigned CodeGenInstruction::getOperandNamed(const std::string &Name) const {
466   assert(!Name.empty() && "Cannot search for operand with no name!");
467   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
468     if (OperandList[i].Name == Name) return i;
469   throw "Instruction '" + TheDef->getName() +
470         "' does not have an operand named '$" + Name + "'!";
471 }
472
473 std::pair<unsigned,unsigned> 
474 CodeGenInstruction::ParseOperandName(const std::string &Op,
475                                      bool AllowWholeOp) {
476   if (Op.empty() || Op[0] != '$')
477     throw TheDef->getName() + ": Illegal operand name: '" + Op + "'";
478   
479   std::string OpName = Op.substr(1);
480   std::string SubOpName;
481   
482   // Check to see if this is $foo.bar.
483   std::string::size_type DotIdx = OpName.find_first_of(".");
484   if (DotIdx != std::string::npos) {
485     SubOpName = OpName.substr(DotIdx+1);
486     if (SubOpName.empty())
487       throw TheDef->getName() + ": illegal empty suboperand name in '" +Op +"'";
488     OpName = OpName.substr(0, DotIdx);
489   }
490   
491   unsigned OpIdx = getOperandNamed(OpName);
492
493   if (SubOpName.empty()) {  // If no suboperand name was specified:
494     // If one was needed, throw.
495     if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
496         SubOpName.empty())
497       throw TheDef->getName() + ": Illegal to refer to"
498             " whole operand part of complex operand '" + Op + "'";
499   
500     // Otherwise, return the operand.
501     return std::make_pair(OpIdx, 0U);
502   }
503   
504   // Find the suboperand number involved.
505   DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
506   if (MIOpInfo == 0)
507     throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
508   
509   // Find the operand with the right name.
510   for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
511     if (MIOpInfo->getArgName(i) == SubOpName)
512       return std::make_pair(OpIdx, i);
513
514   // Otherwise, didn't find it!
515   throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
516 }
517
518
519
520
521 //===----------------------------------------------------------------------===//
522 // ComplexPattern implementation
523 //
524 ComplexPattern::ComplexPattern(Record *R) {
525   Ty          = ::getValueType(R->getValueAsDef("Ty"));
526   NumOperands = R->getValueAsInt("NumOperands");
527   SelectFunc  = R->getValueAsString("SelectFunc");
528   RootNodes   = R->getValueAsListOfDefs("RootNodes");
529
530   // Parse the properties.
531   Properties = 0;
532   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
533   for (unsigned i = 0, e = PropList.size(); i != e; ++i)
534     if (PropList[i]->getName() == "SDNPHasChain") {
535       Properties |= 1 << SDNPHasChain;
536     } else if (PropList[i]->getName() == "SDNPOptInFlag") {
537       Properties |= 1 << SDNPOptInFlag;
538     } else {
539       cerr << "Unsupported SD Node property '" << PropList[i]->getName()
540            << "' on ComplexPattern '" << R->getName() << "'!\n";
541       exit(1);
542     }
543 }
544
545 //===----------------------------------------------------------------------===//
546 // CodeGenIntrinsic Implementation
547 //===----------------------------------------------------------------------===//
548
549 std::vector<CodeGenIntrinsic> llvm::LoadIntrinsics(const RecordKeeper &RC) {
550   std::vector<Record*> I = RC.getAllDerivedDefinitions("Intrinsic");
551   
552   std::vector<CodeGenIntrinsic> Result;
553
554   // If we are in the context of a target .td file, get the target info so that
555   // we can decode the current intptr_t.
556   CodeGenTarget *CGT = 0;
557   if (Records.getClass("Target") &&
558       Records.getAllDerivedDefinitions("Target").size() == 1)
559     CGT = new CodeGenTarget();
560   
561   for (unsigned i = 0, e = I.size(); i != e; ++i)
562     Result.push_back(CodeGenIntrinsic(I[i], CGT));
563   delete CGT;
564   return Result;
565 }
566
567 CodeGenIntrinsic::CodeGenIntrinsic(Record *R, CodeGenTarget *CGT) {
568   TheDef = R;
569   std::string DefName = R->getName();
570   ModRef = WriteMem;
571   isOverloaded = false;
572   
573   if (DefName.size() <= 4 || 
574       std::string(DefName.begin(), DefName.begin()+4) != "int_")
575     throw "Intrinsic '" + DefName + "' does not start with 'int_'!";
576   EnumName = std::string(DefName.begin()+4, DefName.end());
577   if (R->getValue("GCCBuiltinName"))  // Ignore a missing GCCBuiltinName field.
578     GCCBuiltinName = R->getValueAsString("GCCBuiltinName");
579   TargetPrefix   = R->getValueAsString("TargetPrefix");
580   Name = R->getValueAsString("LLVMName");
581   if (Name == "") {
582     // If an explicit name isn't specified, derive one from the DefName.
583     Name = "llvm.";
584     for (unsigned i = 0, e = EnumName.size(); i != e; ++i)
585       if (EnumName[i] == '_')
586         Name += '.';
587       else
588         Name += EnumName[i];
589   } else {
590     // Verify it starts with "llvm.".
591     if (Name.size() <= 5 || 
592         std::string(Name.begin(), Name.begin()+5) != "llvm.")
593       throw "Intrinsic '" + DefName + "'s name does not start with 'llvm.'!";
594   }
595   
596   // If TargetPrefix is specified, make sure that Name starts with
597   // "llvm.<targetprefix>.".
598   if (!TargetPrefix.empty()) {
599     if (Name.size() < 6+TargetPrefix.size() ||
600         std::string(Name.begin()+5, Name.begin()+6+TargetPrefix.size()) 
601         != (TargetPrefix+"."))
602       throw "Intrinsic '" + DefName + "' does not start with 'llvm." + 
603         TargetPrefix + ".'!";
604   }
605   
606   // Parse the list of argument types.
607   ListInit *TypeList = R->getValueAsListInit("Types");
608   for (unsigned i = 0, e = TypeList->getSize(); i != e; ++i) {
609     Record *TyEl = TypeList->getElementAsRecord(i);
610     assert(TyEl->isSubClassOf("LLVMType") && "Expected a type!");
611     ArgTypes.push_back(TyEl->getValueAsString("TypeVal"));
612     MVT::ValueType VT = getValueType(TyEl->getValueAsDef("VT"), CGT);
613     isOverloaded |= VT == MVT::iAny;
614     ArgVTs.push_back(VT);
615     ArgTypeDefs.push_back(TyEl);
616   }
617   if (ArgTypes.size() == 0)
618     throw "Intrinsic '"+DefName+"' needs at least a type for the ret value!";
619
620   
621   // Parse the intrinsic properties.
622   ListInit *PropList = R->getValueAsListInit("Properties");
623   for (unsigned i = 0, e = PropList->getSize(); i != e; ++i) {
624     Record *Property = PropList->getElementAsRecord(i);
625     assert(Property->isSubClassOf("IntrinsicProperty") &&
626            "Expected a property!");
627     
628     if (Property->getName() == "IntrNoMem")
629       ModRef = NoMem;
630     else if (Property->getName() == "IntrReadArgMem")
631       ModRef = ReadArgMem;
632     else if (Property->getName() == "IntrReadMem")
633       ModRef = ReadMem;
634     else if (Property->getName() == "IntrWriteArgMem")
635       ModRef = WriteArgMem;
636     else if (Property->getName() == "IntrWriteMem")
637       ModRef = WriteMem;
638     else
639       assert(0 && "Unknown property!");
640   }
641 }