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