LLVM API Documentation

XCoreISelLowering.cpp

Go to the documentation of this file.
00001 //===-- XCoreISelLowering.cpp - XCore DAG Lowering Implementation   ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the XCoreTargetLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "xcore-lower"
00015 
00016 #include "XCoreISelLowering.h"
00017 #include "XCoreMachineFunctionInfo.h"
00018 #include "XCore.h"
00019 #include "XCoreTargetObjectFile.h"
00020 #include "XCoreTargetMachine.h"
00021 #include "XCoreSubtarget.h"
00022 #include "llvm/DerivedTypes.h"
00023 #include "llvm/Function.h"
00024 #include "llvm/Intrinsics.h"
00025 #include "llvm/CallingConv.h"
00026 #include "llvm/GlobalVariable.h"
00027 #include "llvm/GlobalAlias.h"
00028 #include "llvm/CodeGen/CallingConvLower.h"
00029 #include "llvm/CodeGen/MachineFrameInfo.h"
00030 #include "llvm/CodeGen/MachineFunction.h"
00031 #include "llvm/CodeGen/MachineInstrBuilder.h"
00032 #include "llvm/CodeGen/MachineRegisterInfo.h"
00033 #include "llvm/CodeGen/SelectionDAGISel.h"
00034 #include "llvm/CodeGen/ValueTypes.h"
00035 #include "llvm/Support/Debug.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include "llvm/Support/raw_ostream.h"
00038 #include "llvm/ADT/VectorExtras.h"
00039 #include <queue>
00040 #include <set>
00041 using namespace llvm;
00042 
00043 const char *XCoreTargetLowering::
00044 getTargetNodeName(unsigned Opcode) const 
00045 {
00046   switch (Opcode) 
00047   {
00048     case XCoreISD::BL                : return "XCoreISD::BL";
00049     case XCoreISD::PCRelativeWrapper : return "XCoreISD::PCRelativeWrapper";
00050     case XCoreISD::DPRelativeWrapper : return "XCoreISD::DPRelativeWrapper";
00051     case XCoreISD::CPRelativeWrapper : return "XCoreISD::CPRelativeWrapper";
00052     case XCoreISD::STWSP             : return "XCoreISD::STWSP";
00053     case XCoreISD::RETSP             : return "XCoreISD::RETSP";
00054     default                           : return NULL;
00055   }
00056 }
00057 
00058 XCoreTargetLowering::XCoreTargetLowering(XCoreTargetMachine &XTM)
00059   : TargetLowering(XTM, new XCoreTargetObjectFile()),
00060     TM(XTM),
00061     Subtarget(*XTM.getSubtargetImpl()) {
00062 
00063   // Set up the register classes.
00064   addRegisterClass(MVT::i32, XCore::GRRegsRegisterClass);
00065 
00066   // Compute derived properties from the register classes
00067   computeRegisterProperties();
00068 
00069   // Division is expensive
00070   setIntDivIsCheap(false);
00071 
00072   setShiftAmountType(MVT::i32);
00073   setStackPointerRegisterToSaveRestore(XCore::SP);
00074 
00075   setSchedulingPreference(SchedulingForRegPressure);
00076 
00077   // Use i32 for setcc operations results (slt, sgt, ...).
00078   setBooleanContents(ZeroOrOneBooleanContent);
00079 
00080   // XCore does not have the NodeTypes below.
00081   setOperationAction(ISD::BR_CC,     MVT::Other, Expand);
00082   setOperationAction(ISD::SELECT_CC, MVT::i32,   Custom);
00083   setOperationAction(ISD::ADDC, MVT::i32, Expand);
00084   setOperationAction(ISD::ADDE, MVT::i32, Expand);
00085   setOperationAction(ISD::SUBC, MVT::i32, Expand);
00086   setOperationAction(ISD::SUBE, MVT::i32, Expand);
00087 
00088   // Stop the combiner recombining select and set_cc
00089   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
00090   
00091   // 64bit
00092   if (!Subtarget.isXS1A()) {
00093     setOperationAction(ISD::ADD, MVT::i64, Custom);
00094     setOperationAction(ISD::SUB, MVT::i64, Custom);
00095   }
00096   if (Subtarget.isXS1A()) {
00097     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
00098   }
00099   setOperationAction(ISD::MULHS, MVT::i32, Expand);
00100   setOperationAction(ISD::MULHU, MVT::i32, Expand);
00101   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
00102   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
00103   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
00104   
00105   // Bit Manipulation
00106   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
00107   setOperationAction(ISD::ROTL , MVT::i32, Expand);
00108   setOperationAction(ISD::ROTR , MVT::i32, Expand);
00109   
00110   setOperationAction(ISD::TRAP, MVT::Other, Legal);
00111   
00112   // Expand jump tables for now
00113   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
00114   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
00115 
00116   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
00117   
00118   // Thread Local Storage
00119   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
00120   
00121   // Conversion of i64 -> double produces constantpool nodes
00122   setOperationAction(ISD::ConstantPool, MVT::i32,   Custom);
00123 
00124   // Loads
00125   setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
00126   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
00127   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
00128 
00129   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
00130   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Expand);
00131 
00132   // Custom expand misaligned loads / stores.
00133   setOperationAction(ISD::LOAD, MVT::i32, Custom);
00134   setOperationAction(ISD::STORE, MVT::i32, Custom);
00135 
00136   // Varargs
00137   setOperationAction(ISD::VAEND, MVT::Other, Expand);
00138   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
00139   setOperationAction(ISD::VAARG, MVT::Other, Custom);
00140   setOperationAction(ISD::VASTART, MVT::Other, Custom);
00141   
00142   // Dynamic stack
00143   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
00144   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
00145   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
00146   
00147   // Debug
00148   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
00149   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
00150 
00151   maxStoresPerMemset = 4;
00152   maxStoresPerMemmove = maxStoresPerMemcpy = 2;
00153 
00154   // We have target-specific dag combine patterns for the following nodes:
00155   setTargetDAGCombine(ISD::STORE);
00156 }
00157 
00158 SDValue XCoreTargetLowering::
00159 LowerOperation(SDValue Op, SelectionDAG &DAG) {
00160   switch (Op.getOpcode()) 
00161   {
00162   case ISD::GlobalAddress:    return LowerGlobalAddress(Op, DAG);
00163   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
00164   case ISD::ConstantPool:     return LowerConstantPool(Op, DAG);
00165   case ISD::JumpTable:        return LowerJumpTable(Op, DAG);
00166   case ISD::LOAD:             return LowerLOAD(Op, DAG);
00167   case ISD::STORE:            return LowerSTORE(Op, DAG);
00168   case ISD::SELECT_CC:        return LowerSELECT_CC(Op, DAG);
00169   case ISD::VAARG:            return LowerVAARG(Op, DAG);
00170   case ISD::VASTART:          return LowerVASTART(Op, DAG);
00171   // FIXME: Remove these when LegalizeDAGTypes lands.
00172   case ISD::ADD:
00173   case ISD::SUB:              return ExpandADDSUB(Op.getNode(), DAG);
00174   case ISD::FRAMEADDR:        return LowerFRAMEADDR(Op, DAG);
00175   default:
00176     llvm_unreachable("unimplemented operand");
00177     return SDValue();
00178   }
00179 }
00180 
00181 /// ReplaceNodeResults - Replace the results of node with an illegal result
00182 /// type with new values built out of custom code.
00183 void XCoreTargetLowering::ReplaceNodeResults(SDNode *N,
00184                                              SmallVectorImpl<SDValue>&Results,
00185                                              SelectionDAG &DAG) {
00186   switch (N->getOpcode()) {
00187   default:
00188     llvm_unreachable("Don't know how to custom expand this!");
00189     return;
00190   case ISD::ADD:
00191   case ISD::SUB:
00192     Results.push_back(ExpandADDSUB(N, DAG));
00193     return;
00194   }
00195 }
00196 
00197 /// getFunctionAlignment - Return the Log2 alignment of this function.
00198 unsigned XCoreTargetLowering::
00199 getFunctionAlignment(const Function *) const {
00200   return 1;
00201 }
00202 
00203 //===----------------------------------------------------------------------===//
00204 //  Misc Lower Operation implementation
00205 //===----------------------------------------------------------------------===//
00206 
00207 SDValue XCoreTargetLowering::
00208 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG)
00209 {
00210   DebugLoc dl = Op.getDebugLoc();
00211   SDValue Cond = DAG.getNode(ISD::SETCC, dl, MVT::i32, Op.getOperand(2),
00212                              Op.getOperand(3), Op.getOperand(4));
00213   return DAG.getNode(ISD::SELECT, dl, MVT::i32, Cond, Op.getOperand(0),
00214                      Op.getOperand(1));
00215 }
00216 
00217 SDValue XCoreTargetLowering::
00218 getGlobalAddressWrapper(SDValue GA, GlobalValue *GV, SelectionDAG &DAG)
00219 {
00220   // FIXME there is no actual debug info here
00221   DebugLoc dl = GA.getDebugLoc();
00222   if (isa<Function>(GV)) {
00223     return DAG.getNode(XCoreISD::PCRelativeWrapper, dl, MVT::i32, GA);
00224   } else if (!Subtarget.isXS1A()) {
00225     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
00226     if (!GVar) {
00227       // If GV is an alias then use the aliasee to determine constness
00228       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
00229         GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
00230     }
00231     bool isConst = GVar && GVar->isConstant();
00232     if (isConst) {
00233       return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, GA);
00234     }
00235   }
00236   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, GA);
00237 }
00238 
00239 SDValue XCoreTargetLowering::
00240 LowerGlobalAddress(SDValue Op, SelectionDAG &DAG)
00241 {
00242   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
00243   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
00244   // If it's a debug information descriptor, don't mess with it.
00245   if (DAG.isVerifiedDebugInfoDesc(Op))
00246     return GA;
00247   return getGlobalAddressWrapper(GA, GV, DAG);
00248 }
00249 
00250 static inline SDValue BuildGetId(SelectionDAG &DAG, DebugLoc dl) {
00251   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
00252                      DAG.getConstant(Intrinsic::xcore_getid, MVT::i32));
00253 }
00254 
00255 static inline bool isZeroLengthArray(const Type *Ty) {
00256   const ArrayType *AT = dyn_cast_or_null<ArrayType>(Ty);
00257   return AT && (AT->getNumElements() == 0);
00258 }
00259 
00260 SDValue XCoreTargetLowering::
00261 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG)
00262 {
00263   // FIXME there isn't really debug info here
00264   DebugLoc dl = Op.getDebugLoc();
00265   // transform to label + getid() * size
00266   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
00267   SDValue GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
00268   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
00269   if (!GVar) {
00270     // If GV is an alias then use the aliasee to determine size
00271     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
00272       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
00273   }
00274   if (! GVar) {
00275     llvm_unreachable("Thread local object not a GlobalVariable?");
00276     return SDValue();
00277   }
00278   const Type *Ty = cast<PointerType>(GV->getType())->getElementType();
00279   if (!Ty->isSized() || isZeroLengthArray(Ty)) {
00280 #ifndef NDEBUG
00281     errs() << "Size of thread local object " << GVar->getName()
00282            << " is unknown\n";
00283 #endif
00284     llvm_unreachable(0);
00285   }
00286   SDValue base = getGlobalAddressWrapper(GA, GV, DAG);
00287   const TargetData *TD = TM.getTargetData();
00288   unsigned Size = TD->getTypeAllocSize(Ty);
00289   SDValue offset = DAG.getNode(ISD::MUL, dl, MVT::i32, BuildGetId(DAG, dl),
00290                        DAG.getConstant(Size, MVT::i32));
00291   return DAG.getNode(ISD::ADD, dl, MVT::i32, base, offset);
00292 }
00293 
00294 SDValue XCoreTargetLowering::
00295 LowerConstantPool(SDValue Op, SelectionDAG &DAG)
00296 {
00297   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
00298   // FIXME there isn't really debug info here
00299   DebugLoc dl = CP->getDebugLoc();
00300   if (Subtarget.isXS1A()) {
00301     llvm_unreachable("Lowering of constant pool unimplemented");
00302     return SDValue();
00303   } else {
00304     EVT PtrVT = Op.getValueType();
00305     SDValue Res;
00306     if (CP->isMachineConstantPoolEntry()) {
00307       Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
00308                                       CP->getAlignment());
00309     } else {
00310       Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
00311                                       CP->getAlignment());
00312     }
00313     return DAG.getNode(XCoreISD::CPRelativeWrapper, dl, MVT::i32, Res);
00314   }
00315 }
00316 
00317 SDValue XCoreTargetLowering::
00318 LowerJumpTable(SDValue Op, SelectionDAG &DAG)
00319 {
00320   // FIXME there isn't really debug info here
00321   DebugLoc dl = Op.getDebugLoc();
00322   EVT PtrVT = Op.getValueType();
00323   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
00324   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
00325   return DAG.getNode(XCoreISD::DPRelativeWrapper, dl, MVT::i32, JTI);
00326 }
00327 
00328 static bool
00329 IsWordAlignedBasePlusConstantOffset(SDValue Addr, SDValue &AlignedBase,
00330                                     int64_t &Offset)
00331 {
00332   if (Addr.getOpcode() != ISD::ADD) {
00333     return false;
00334   }
00335   ConstantSDNode *CN = 0;
00336   if (!(CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
00337     return false;
00338   }
00339   int64_t off = CN->getSExtValue();
00340   const SDValue &Base = Addr.getOperand(0);
00341   const SDValue *Root = &Base;
00342   if (Base.getOpcode() == ISD::ADD &&
00343       Base.getOperand(1).getOpcode() == ISD::SHL) {
00344     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Base.getOperand(1)
00345                                                       .getOperand(1));
00346     if (CN && (CN->getSExtValue() >= 2)) {
00347       Root = &Base.getOperand(0);
00348     }
00349   }
00350   if (isa<FrameIndexSDNode>(*Root)) {
00351     // All frame indicies are word aligned
00352     AlignedBase = Base;
00353     Offset = off;
00354     return true;
00355   }
00356   if (Root->getOpcode() == XCoreISD::DPRelativeWrapper ||
00357       Root->getOpcode() == XCoreISD::CPRelativeWrapper) {
00358     // All dp / cp relative addresses are word aligned
00359     AlignedBase = Base;
00360     Offset = off;
00361     return true;
00362   }
00363   return false;
00364 }
00365 
00366 SDValue XCoreTargetLowering::
00367 LowerLOAD(SDValue Op, SelectionDAG &DAG)
00368 {
00369   LoadSDNode *LD = cast<LoadSDNode>(Op);
00370   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
00371          "Unexpected extension type");
00372   assert(LD->getMemoryVT() == MVT::i32 && "Unexpected load EVT");
00373   if (allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
00374     return SDValue();
00375   }
00376   unsigned ABIAlignment = getTargetData()->
00377     getABITypeAlignment(LD->getMemoryVT().getTypeForEVT(*DAG.getContext()));
00378   // Leave aligned load alone.
00379   if (LD->getAlignment() >= ABIAlignment) {
00380     return SDValue();
00381   }
00382   SDValue Chain = LD->getChain();
00383   SDValue BasePtr = LD->getBasePtr();
00384   DebugLoc dl = Op.getDebugLoc();
00385   
00386   SDValue Base;
00387   int64_t Offset;
00388   if (!LD->isVolatile() &&
00389       IsWordAlignedBasePlusConstantOffset(BasePtr, Base, Offset)) {
00390     if (Offset % 4 == 0) {
00391       // We've managed to infer better alignment information than the load
00392       // already has. Use an aligned load.
00393       return DAG.getLoad(getPointerTy(), dl, Chain, BasePtr, NULL, 4);
00394     }
00395     // Lower to
00396     // ldw low, base[offset >> 2]
00397     // ldw high, base[(offset >> 2) + 1]
00398     // shr low_shifted, low, (offset & 0x3) * 8
00399     // shl high_shifted, high, 32 - (offset & 0x3) * 8
00400     // or result, low_shifted, high_shifted
00401     SDValue LowOffset = DAG.getConstant(Offset & ~0x3, MVT::i32);
00402     SDValue HighOffset = DAG.getConstant((Offset & ~0x3) + 4, MVT::i32);
00403     SDValue LowShift = DAG.getConstant((Offset & 0x3) * 8, MVT::i32);
00404     SDValue HighShift = DAG.getConstant(32 - (Offset & 0x3) * 8, MVT::i32);
00405     
00406     SDValue LowAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, LowOffset);
00407     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Base, HighOffset);
00408     
00409     SDValue Low = DAG.getLoad(getPointerTy(), dl, Chain,
00410                                LowAddr, NULL, 4);
00411     SDValue High = DAG.getLoad(getPointerTy(), dl, Chain,
00412                                HighAddr, NULL, 4);
00413     SDValue LowShifted = DAG.getNode(ISD::SRL, dl, MVT::i32, Low, LowShift);
00414     SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High, HighShift);
00415     SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, LowShifted, HighShifted);
00416     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
00417                              High.getValue(1));
00418     SDValue Ops[] = { Result, Chain };
00419     return DAG.getMergeValues(Ops, 2, dl);
00420   }
00421   
00422   if (LD->getAlignment() == 2) {
00423     int SVOffset = LD->getSrcValueOffset();
00424     SDValue Low = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
00425                                  BasePtr, LD->getSrcValue(), SVOffset, MVT::i16,
00426                                  LD->isVolatile(), 2);
00427     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
00428                                    DAG.getConstant(2, MVT::i32));
00429     SDValue High = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, Chain,
00430                                   HighAddr, LD->getSrcValue(), SVOffset + 2,
00431                                   MVT::i16, LD->isVolatile(), 2);
00432     SDValue HighShifted = DAG.getNode(ISD::SHL, dl, MVT::i32, High,
00433                                       DAG.getConstant(16, MVT::i32));
00434     SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, Low, HighShifted);
00435     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Low.getValue(1),
00436                              High.getValue(1));
00437     SDValue Ops[] = { Result, Chain };
00438     return DAG.getMergeValues(Ops, 2, dl);
00439   }
00440   
00441   // Lower to a call to __misaligned_load(BasePtr).
00442   const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
00443   TargetLowering::ArgListTy Args;
00444   TargetLowering::ArgListEntry Entry;
00445   
00446   Entry.Ty = IntPtrTy;
00447   Entry.Node = BasePtr;
00448   Args.push_back(Entry);
00449   
00450   std::pair<SDValue, SDValue> CallResult =
00451         LowerCallTo(Chain, IntPtrTy, false, false,
00452                     false, false, 0, CallingConv::C, false,
00453                     /*isReturnValueUsed=*/true,
00454                     DAG.getExternalSymbol("__misaligned_load", getPointerTy()),
00455                     Args, DAG, dl);
00456 
00457   SDValue Ops[] =
00458     { CallResult.first, CallResult.second };
00459 
00460   return DAG.getMergeValues(Ops, 2, dl);
00461 }
00462 
00463 SDValue XCoreTargetLowering::
00464 LowerSTORE(SDValue Op, SelectionDAG &DAG)
00465 {
00466   StoreSDNode *ST = cast<StoreSDNode>(Op);
00467   assert(!ST->isTruncatingStore() && "Unexpected store type");
00468   assert(ST->getMemoryVT() == MVT::i32 && "Unexpected store EVT");
00469   if (allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
00470     return SDValue();
00471   }
00472   unsigned ABIAlignment = getTargetData()->
00473     getABITypeAlignment(ST->getMemoryVT().getTypeForEVT(*DAG.getContext()));
00474   // Leave aligned store alone.
00475   if (ST->getAlignment() >= ABIAlignment) {
00476     return SDValue();
00477   }
00478   SDValue Chain = ST->getChain();
00479   SDValue BasePtr = ST->getBasePtr();
00480   SDValue Value = ST->getValue();
00481   DebugLoc dl = Op.getDebugLoc();
00482   
00483   if (ST->getAlignment() == 2) {
00484     int SVOffset = ST->getSrcValueOffset();
00485     SDValue Low = Value;
00486     SDValue High = DAG.getNode(ISD::SRL, dl, MVT::i32, Value,
00487                                       DAG.getConstant(16, MVT::i32));
00488     SDValue StoreLow = DAG.getTruncStore(Chain, dl, Low, BasePtr,
00489                                          ST->getSrcValue(), SVOffset, MVT::i16,
00490                                          ST->isVolatile(), 2);
00491     SDValue HighAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, BasePtr,
00492                                    DAG.getConstant(2, MVT::i32));
00493     SDValue StoreHigh = DAG.getTruncStore(Chain, dl, High, HighAddr,
00494                                           ST->getSrcValue(), SVOffset + 2,
00495                                           MVT::i16, ST->isVolatile(), 2);
00496     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StoreLow, StoreHigh);
00497   }
00498   
00499   // Lower to a call to __misaligned_store(BasePtr, Value).
00500   const Type *IntPtrTy = getTargetData()->getIntPtrType(*DAG.getContext());
00501   TargetLowering::ArgListTy Args;
00502   TargetLowering::ArgListEntry Entry;
00503   
00504   Entry.Ty = IntPtrTy;
00505   Entry.Node = BasePtr;
00506   Args.push_back(Entry);
00507   
00508   Entry.Node = Value;
00509   Args.push_back(Entry);
00510   
00511   std::pair<SDValue, SDValue> CallResult =
00512         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()), false, false,
00513                     false, false, 0, CallingConv::C, false,
00514                     /*isReturnValueUsed=*/true,
00515                     DAG.getExternalSymbol("__misaligned_store", getPointerTy()),
00516                     Args, DAG, dl);
00517 
00518   return CallResult.second;
00519 }
00520 
00521 SDValue XCoreTargetLowering::
00522 ExpandADDSUB(SDNode *N, SelectionDAG &DAG)
00523 {
00524   assert(N->getValueType(0) == MVT::i64 &&
00525          (N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
00526         "Unknown operand to lower!");
00527   assert(!Subtarget.isXS1A() && "Cannot custom lower ADD/SUB on xs1a");
00528   DebugLoc dl = N->getDebugLoc();
00529   
00530   // Extract components
00531   SDValue LHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
00532                             N->getOperand(0),  DAG.getConstant(0, MVT::i32));
00533   SDValue LHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
00534                             N->getOperand(0),  DAG.getConstant(1, MVT::i32));
00535   SDValue RHSL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
00536                              N->getOperand(1), DAG.getConstant(0, MVT::i32));
00537   SDValue RHSH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
00538                              N->getOperand(1), DAG.getConstant(1, MVT::i32));
00539   
00540   // Expand
00541   unsigned Opcode = (N->getOpcode() == ISD::ADD) ? XCoreISD::LADD :
00542                                                    XCoreISD::LSUB;
00543   SDValue Zero = DAG.getConstant(0, MVT::i32);
00544   SDValue Carry = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
00545                                   LHSL, RHSL, Zero);
00546   SDValue Lo(Carry.getNode(), 1);
00547   
00548   SDValue Ignored = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
00549                                   LHSH, RHSH, Carry);
00550   SDValue Hi(Ignored.getNode(), 1);
00551   // Merge the pieces
00552   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
00553 }
00554 
00555 SDValue XCoreTargetLowering::
00556 LowerVAARG(SDValue Op, SelectionDAG &DAG)
00557 {
00558   llvm_unreachable("unimplemented");
00559   // FIX Arguments passed by reference need a extra dereference.
00560   SDNode *Node = Op.getNode();
00561   DebugLoc dl = Node->getDebugLoc();
00562   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
00563   EVT VT = Node->getValueType(0);
00564   SDValue VAList = DAG.getLoad(getPointerTy(), dl, Node->getOperand(0),
00565                                Node->getOperand(1), V, 0);
00566   // Increment the pointer, VAList, to the next vararg
00567   SDValue Tmp3 = DAG.getNode(ISD::ADD, dl, getPointerTy(), VAList, 
00568                      DAG.getConstant(VT.getSizeInBits(), 
00569                                      getPointerTy()));
00570   // Store the incremented VAList to the legalized pointer
00571   Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Node->getOperand(1), V, 0);
00572   // Load the actual argument out of the pointer VAList
00573   return DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
00574 }
00575 
00576 SDValue XCoreTargetLowering::
00577 LowerVASTART(SDValue Op, SelectionDAG &DAG)
00578 {
00579   DebugLoc dl = Op.getDebugLoc();
00580   // vastart stores the address of the VarArgsFrameIndex slot into the
00581   // memory location argument
00582   MachineFunction &MF = DAG.getMachineFunction();
00583   XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
00584   SDValue Addr = DAG.getFrameIndex(XFI->getVarArgsFrameIndex(), MVT::i32);
00585   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
00586   return DAG.getStore(Op.getOperand(0), dl, Addr, Op.getOperand(1), SV, 0);
00587 }
00588 
00589 SDValue XCoreTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
00590   DebugLoc dl = Op.getDebugLoc();
00591   // Depths > 0 not supported yet! 
00592   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
00593     return SDValue();
00594   
00595   MachineFunction &MF = DAG.getMachineFunction();
00596   const TargetRegisterInfo *RegInfo = getTargetMachine().getRegisterInfo();
00597   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, 
00598                             RegInfo->getFrameRegister(MF), MVT::i32);
00599 }
00600 
00601 //===----------------------------------------------------------------------===//
00602 //                      Calling Convention Implementation
00603 //===----------------------------------------------------------------------===//
00604 
00605 #include "XCoreGenCallingConv.inc"
00606 
00607 //===----------------------------------------------------------------------===//
00608 //                  Call Calling Convention Implementation
00609 //===----------------------------------------------------------------------===//
00610 
00611 /// XCore call implementation
00612 SDValue
00613 XCoreTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
00614                                unsigned CallConv, bool isVarArg,
00615                                bool isTailCall,
00616                                const SmallVectorImpl<ISD::OutputArg> &Outs,
00617                                const SmallVectorImpl<ISD::InputArg> &Ins,
00618                                DebugLoc dl, SelectionDAG &DAG,
00619                                SmallVectorImpl<SDValue> &InVals) {
00620 
00621   // For now, only CallingConv::C implemented
00622   switch (CallConv)
00623   {
00624     default:
00625       llvm_unreachable("Unsupported calling convention");
00626     case CallingConv::Fast:
00627     case CallingConv::C:
00628       return LowerCCCCallTo(Chain, Callee, CallConv, isVarArg, isTailCall,
00629                             Outs, Ins, dl, DAG, InVals);
00630   }
00631 }
00632 
00633 /// LowerCCCCallTo - functions arguments are copied from virtual
00634 /// regs to (physical regs)/(stack frame), CALLSEQ_START and
00635 /// CALLSEQ_END are emitted.
00636 /// TODO: isTailCall, sret.
00637 SDValue
00638 XCoreTargetLowering::LowerCCCCallTo(SDValue Chain, SDValue Callee,
00639                                     unsigned CallConv, bool isVarArg,
00640                                     bool isTailCall,
00641                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
00642                                     const SmallVectorImpl<ISD::InputArg> &Ins,
00643                                     DebugLoc dl, SelectionDAG &DAG,
00644                                     SmallVectorImpl<SDValue> &InVals) {
00645 
00646   // Analyze operands of the call, assigning locations to each operand.
00647   SmallVector<CCValAssign, 16> ArgLocs;
00648   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
00649                  ArgLocs, *DAG.getContext());
00650 
00651   // The ABI dictates there should be one stack slot available to the callee
00652   // on function entry (for saving lr).
00653   CCInfo.AllocateStack(4, 4);
00654 
00655   CCInfo.AnalyzeCallOperands(Outs, CC_XCore);
00656 
00657   // Get a count of how many bytes are to be pushed on the stack.
00658   unsigned NumBytes = CCInfo.getNextStackOffset();
00659 
00660   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, 
00661                                  getPointerTy(), true));
00662 
00663   SmallVector<std::pair<unsigned, SDValue>, 4> RegsToPass;
00664   SmallVector<SDValue, 12> MemOpChains;
00665 
00666   // Walk the register/memloc assignments, inserting copies/loads.
00667   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
00668     CCValAssign &VA = ArgLocs[i];
00669     SDValue Arg = Outs[i].Val;
00670 
00671     // Promote the value if needed.
00672     switch (VA.getLocInfo()) {
00673       default: llvm_unreachable("Unknown loc info!");
00674       case CCValAssign::Full: break;
00675       case CCValAssign::SExt:
00676         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
00677         break;
00678       case CCValAssign::ZExt:
00679         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
00680         break;
00681       case CCValAssign::AExt:
00682         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
00683         break;
00684     }
00685     
00686     // Arguments that can be passed on register must be kept at 
00687     // RegsToPass vector
00688     if (VA.isRegLoc()) {
00689       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
00690     } else {
00691       assert(VA.isMemLoc());
00692 
00693       int Offset = VA.getLocMemOffset();
00694 
00695       MemOpChains.push_back(DAG.getNode(XCoreISD::STWSP, dl, MVT::Other, 
00696                                         Chain, Arg,
00697                                         DAG.getConstant(Offset/4, MVT::i32)));
00698     }
00699   }
00700 
00701   // Transform all store nodes into one single node because
00702   // all store nodes are independent of each other.
00703   if (!MemOpChains.empty())
00704     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 
00705                         &MemOpChains[0], MemOpChains.size());
00706 
00707   // Build a sequence of copy-to-reg nodes chained together with token 
00708   // chain and flag operands which copy the outgoing args into registers.
00709   // The InFlag in necessary since all emited instructions must be
00710   // stuck together.
00711   SDValue InFlag;
00712   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
00713     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, 
00714                              RegsToPass[i].second, InFlag);
00715     InFlag = Chain.getValue(1);
00716   }
00717 
00718   // If the callee is a GlobalAddress node (quite common, every direct call is)
00719   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
00720   // Likewise ExternalSymbol -> TargetExternalSymbol.
00721   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
00722     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
00723   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
00724     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
00725 
00726   // XCoreBranchLink = #chain, #target_address, #opt_in_flags...
00727   //             = Chain, Callee, Reg#1, Reg#2, ...  
00728   //
00729   // Returns a chain & a flag for retval copy to use.
00730   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
00731   SmallVector<SDValue, 8> Ops;
00732   Ops.push_back(Chain);
00733   Ops.push_back(Callee);
00734 
00735   // Add argument registers to the end of the list so that they are 
00736   // known live into the call.
00737   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
00738     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
00739                                   RegsToPass[i].second.getValueType()));
00740 
00741   if (InFlag.getNode())
00742     Ops.push_back(InFlag);
00743 
00744   Chain  = DAG.getNode(XCoreISD::BL, dl, NodeTys, &Ops[0], Ops.size());
00745   InFlag = Chain.getValue(1);
00746 
00747   // Create the CALLSEQ_END node.
00748   Chain = DAG.getCALLSEQ_END(Chain,
00749                              DAG.getConstant(NumBytes, getPointerTy(), true),
00750                              DAG.getConstant(0, getPointerTy(), true),
00751                              InFlag);
00752   InFlag = Chain.getValue(1);
00753 
00754   // Handle result values, copying them out of physregs into vregs that we
00755   // return.
00756   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
00757                          Ins, dl, DAG, InVals);
00758 }
00759 
00760 /// LowerCallResult - Lower the result values of a call into the
00761 /// appropriate copies out of appropriate physical registers.
00762 SDValue
00763 XCoreTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
00764                                      unsigned CallConv, bool isVarArg,
00765                                      const SmallVectorImpl<ISD::InputArg> &Ins,
00766                                      DebugLoc dl, SelectionDAG &DAG,
00767                                      SmallVectorImpl<SDValue> &InVals) {
00768 
00769   // Assign locations to each value returned by this call.
00770   SmallVector<CCValAssign, 16> RVLocs;
00771   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
00772                  RVLocs, *DAG.getContext());
00773 
00774   CCInfo.AnalyzeCallResult(Ins, RetCC_XCore);
00775 
00776   // Copy all of the result registers out of their specified physreg.
00777   for (unsigned i = 0; i != RVLocs.size(); ++i) {
00778     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
00779                                  RVLocs[i].getValVT(), InFlag).getValue(1);
00780     InFlag = Chain.getValue(2);
00781     InVals.push_back(Chain.getValue(0));
00782   }
00783 
00784   return Chain;
00785 }
00786 
00787 //===----------------------------------------------------------------------===//
00788 //             Formal Arguments Calling Convention Implementation
00789 //===----------------------------------------------------------------------===//
00790 
00791 /// XCore formal arguments implementation
00792 SDValue
00793 XCoreTargetLowering::LowerFormalArguments(SDValue Chain,
00794                                           unsigned CallConv,
00795                                           bool isVarArg,
00796                                       const SmallVectorImpl<ISD::InputArg> &Ins,
00797                                           DebugLoc dl,
00798                                           SelectionDAG &DAG,
00799                                           SmallVectorImpl<SDValue> &InVals) {
00800   switch (CallConv)
00801   {
00802     default:
00803       llvm_unreachable("Unsupported calling convention");
00804     case CallingConv::C:
00805     case CallingConv::Fast:
00806       return LowerCCCArguments(Chain, CallConv, isVarArg,
00807                                Ins, dl, DAG, InVals);
00808   }
00809 }
00810 
00811 /// LowerCCCArguments - transform physical registers into
00812 /// virtual registers and generate load operations for
00813 /// arguments places on the stack.
00814 /// TODO: sret
00815 SDValue
00816 XCoreTargetLowering::LowerCCCArguments(SDValue Chain,
00817                                        unsigned CallConv,
00818                                        bool isVarArg,
00819                                        const SmallVectorImpl<ISD::InputArg>
00820                                          &Ins,
00821                                        DebugLoc dl,
00822                                        SelectionDAG &DAG,
00823                                        SmallVectorImpl<SDValue> &InVals) {
00824   MachineFunction &MF = DAG.getMachineFunction();
00825   MachineFrameInfo *MFI = MF.getFrameInfo();
00826   MachineRegisterInfo &RegInfo = MF.getRegInfo();
00827 
00828   // Assign locations to all of the incoming arguments.
00829   SmallVector<CCValAssign, 16> ArgLocs;
00830   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
00831                  ArgLocs, *DAG.getContext());
00832 
00833   CCInfo.AnalyzeFormalArguments(Ins, CC_XCore);
00834 
00835   unsigned StackSlotSize = XCoreFrameInfo::stackSlotSize();
00836 
00837   unsigned LRSaveSize = StackSlotSize;
00838   
00839   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
00840 
00841     CCValAssign &VA = ArgLocs[i];
00842     
00843     if (VA.isRegLoc()) {
00844       // Arguments passed in registers
00845       EVT RegVT = VA.getLocVT();
00846       switch (RegVT.getSimpleVT().SimpleTy) {
00847       default:
00848         {
00849 #ifndef NDEBUG
00850           errs() << "LowerFormalArguments Unhandled argument type: "
00851                  << RegVT.getSimpleVT().SimpleTy << "\n";
00852 #endif
00853           llvm_unreachable(0);
00854         }
00855       case MVT::i32:
00856         unsigned VReg = RegInfo.createVirtualRegister(
00857                           XCore::GRRegsRegisterClass);
00858         RegInfo.addLiveIn(VA.getLocReg(), VReg);
00859         InVals.push_back(DAG.getCopyFromReg(Chain, dl, VReg, RegVT));
00860       }
00861     } else {
00862       // sanity check
00863       assert(VA.isMemLoc());
00864       // Load the argument to a virtual register
00865       unsigned ObjSize = VA.getLocVT().getSizeInBits()/8;
00866       if (ObjSize > StackSlotSize) {
00867         errs() << "LowerFormalArguments Unhandled argument type: "
00868                << (unsigned)VA.getLocVT().getSimpleVT().SimpleTy
00869                << "\n";
00870       }
00871       // Create the frame index object for this incoming parameter...
00872       int FI = MFI->CreateFixedObject(ObjSize,
00873                                       LRSaveSize + VA.getLocMemOffset());
00874 
00875       // Create the SelectionDAG nodes corresponding to a load
00876       //from this parameter
00877       SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
00878       InVals.push_back(DAG.getLoad(VA.getLocVT(), dl, Chain, FIN, NULL, 0));
00879     }
00880   }
00881   
00882   if (isVarArg) {
00883     /* Argument registers */
00884     static const unsigned ArgRegs[] = {
00885       XCore::R0, XCore::R1, XCore::R2, XCore::R3
00886     };
00887     XCoreFunctionInfo *XFI = MF.getInfo<XCoreFunctionInfo>();
00888     unsigned FirstVAReg = CCInfo.getFirstUnallocated(ArgRegs,
00889                                                      array_lengthof(ArgRegs));
00890     if (FirstVAReg < array_lengthof(ArgRegs)) {
00891       SmallVector<SDValue, 4> MemOps;
00892       int offset = 0;
00893       // Save remaining registers, storing higher register numbers at a higher
00894       // address
00895       for (unsigned i = array_lengthof(ArgRegs) - 1; i >= FirstVAReg; --i) {
00896         // Create a stack slot
00897         int FI = MFI->CreateFixedObject(4, offset);
00898         if (i == FirstVAReg) {
00899           XFI->setVarArgsFrameIndex(FI);
00900         }
00901         offset -= StackSlotSize;
00902         SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
00903         // Move argument from phys reg -> virt reg
00904         unsigned VReg = RegInfo.createVirtualRegister(
00905                           XCore::GRRegsRegisterClass);
00906         RegInfo.addLiveIn(ArgRegs[i], VReg);
00907         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
00908         // Move argument from virt reg -> stack
00909         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
00910         MemOps.push_back(Store);
00911       }
00912       if (!MemOps.empty())
00913         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
00914                             &MemOps[0], MemOps.size());
00915     } else {
00916       // This will point to the next argument passed via stack.
00917       XFI->setVarArgsFrameIndex(
00918           MFI->CreateFixedObject(4, LRSaveSize + CCInfo.getNextStackOffset()));
00919     }
00920   }
00921   
00922   return Chain;
00923 }
00924 
00925 //===----------------------------------------------------------------------===//
00926 //               Return Value Calling Convention Implementation
00927 //===----------------------------------------------------------------------===//
00928 
00929 SDValue
00930 XCoreTargetLowering::LowerReturn(SDValue Chain,
00931                                  unsigned CallConv, bool isVarArg,
00932                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
00933                                  DebugLoc dl, SelectionDAG &DAG) {
00934 
00935   // CCValAssign - represent the assignment of
00936   // the return value to a location
00937   SmallVector<CCValAssign, 16> RVLocs;
00938 
00939   // CCState - Info about the registers and stack slot.
00940   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
00941                  RVLocs, *DAG.getContext());
00942 
00943   // Analize return values.
00944   CCInfo.AnalyzeReturn(Outs, RetCC_XCore);
00945 
00946   // If this is the first return lowered for this function, add 
00947   // the regs to the liveout set for the function.
00948   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
00949     for (unsigned i = 0; i != RVLocs.size(); ++i)
00950       if (RVLocs[i].isRegLoc())
00951         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
00952   }
00953 
00954   SDValue Flag;
00955 
00956   // Copy the result values into the output registers.
00957   for (unsigned i = 0; i != RVLocs.size(); ++i) {
00958     CCValAssign &VA = RVLocs[i];
00959     assert(VA.isRegLoc() && "Can only return in registers!");
00960 
00961     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), 
00962                              Outs[i].Val, Flag);
00963 
00964     // guarantee that all emitted copies are
00965     // stuck together, avoiding something bad
00966     Flag = Chain.getValue(1);
00967   }
00968 
00969   // Return on XCore is always a "retsp 0"
00970   if (Flag.getNode())
00971     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
00972                        Chain, DAG.getConstant(0, MVT::i32), Flag);
00973   else // Return Void
00974     return DAG.getNode(XCoreISD::RETSP, dl, MVT::Other,
00975                        Chain, DAG.getConstant(0, MVT::i32));
00976 }
00977 
00978 //===----------------------------------------------------------------------===//
00979 //  Other Lowering Code
00980 //===----------------------------------------------------------------------===//
00981 
00982 MachineBasicBlock *
00983 XCoreTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
00984                                                  MachineBasicBlock *BB) const {
00985   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
00986   DebugLoc dl = MI->getDebugLoc();
00987   assert((MI->getOpcode() == XCore::SELECT_CC) &&
00988          "Unexpected instr type to insert");
00989   
00990   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
00991   // control-flow pattern.  The incoming instruction knows the destination vreg
00992   // to set, the condition code register to branch on, the true/false values to
00993   // select between, and a branch opcode to use.
00994   const BasicBlock *LLVM_BB = BB->getBasicBlock();
00995   MachineFunction::iterator It = BB;
00996   ++It;
00997   
00998   //  thisMBB:
00999   //  ...
01000   //   TrueVal = ...
01001   //   cmpTY ccX, r1, r2
01002   //   bCC copy1MBB
01003   //   fallthrough --> copy0MBB
01004   MachineBasicBlock *thisMBB = BB;
01005   MachineFunction *F = BB->getParent();
01006   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
01007   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
01008   BuildMI(BB, dl, TII.get(XCore::BRFT_lru6))
01009     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
01010   F->insert(It, copy0MBB);
01011   F->insert(It, sinkMBB);
01012   // Update machine-CFG edges by transferring all successors of the current
01013   // block to the new block which will contain the Phi node for the select.
01014   sinkMBB->transferSuccessors(BB);
01015   // Next, add the true and fallthrough blocks as its successors.
01016   BB->addSuccessor(copy0MBB);
01017   BB->addSuccessor(sinkMBB);
01018   
01019   //  copy0MBB:
01020   //   %FalseValue = ...
01021   //   # fallthrough to sinkMBB
01022   BB = copy0MBB;
01023   
01024   // Update machine-CFG edges
01025   BB->addSuccessor(sinkMBB);
01026   
01027   //  sinkMBB:
01028   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
01029   //  ...
01030   BB = sinkMBB;
01031   BuildMI(BB, dl, TII.get(XCore::PHI), MI->getOperand(0).getReg())
01032     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
01033     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
01034   
01035   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
01036   return BB;
01037 }
01038 
01039 //===----------------------------------------------------------------------===//
01040 // Target Optimization Hooks
01041 //===----------------------------------------------------------------------===//
01042 
01043 SDValue XCoreTargetLowering::PerformDAGCombine(SDNode *N,
01044                                              DAGCombinerInfo &DCI) const {
01045   SelectionDAG &DAG = DCI.DAG;
01046   DebugLoc dl = N->getDebugLoc();
01047   switch (N->getOpcode()) {
01048   default: break;
01049   case ISD::STORE: {
01050     // Replace unaligned store of unaligned load with memmove.
01051     StoreSDNode *ST  = cast<StoreSDNode>(N);
01052     if (!DCI.isBeforeLegalize() ||
01053         allowsUnalignedMemoryAccesses(ST->getMemoryVT()) ||
01054         ST->isVolatile() || ST->isIndexed()) {
01055       break;
01056     }
01057     SDValue Chain = ST->getChain();
01058 
01059     unsigned StoreBits = ST->getMemoryVT().getStoreSizeInBits();
01060     if (StoreBits % 8) {
01061       break;
01062     }
01063     unsigned ABIAlignment = getTargetData()->getABITypeAlignment(
01064         ST->getMemoryVT().getTypeForEVT(*DCI.DAG.getContext()));
01065     unsigned Alignment = ST->getAlignment();
01066     if (Alignment >= ABIAlignment) {
01067       break;
01068     }
01069 
01070     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ST->getValue())) {
01071       if (LD->hasNUsesOfValue(1, 0) && ST->getMemoryVT() == LD->getMemoryVT() &&
01072         LD->getAlignment() == Alignment &&
01073         !LD->isVolatile() && !LD->isIndexed() &&
01074         Chain.reachesChainWithoutSideEffects(SDValue(LD, 1))) {
01075         return DAG.getMemmove(Chain, dl, ST->getBasePtr(),
01076                               LD->getBasePtr(),
01077                               DAG.getConstant(StoreBits/8, MVT::i32),
01078                               Alignment, ST->getSrcValue(),
01079                               ST->getSrcValueOffset(), LD->getSrcValue(),
01080                               LD->getSrcValueOffset());
01081       }
01082     }
01083     break;
01084   }
01085   }
01086   return SDValue();
01087 }
01088 
01089 //===----------------------------------------------------------------------===//
01090 //  Addressing mode description hooks
01091 //===----------------------------------------------------------------------===//
01092 
01093 static inline bool isImmUs(int64_t val)
01094 {
01095   return (val >= 0 && val <= 11);
01096 }
01097 
01098 static inline bool isImmUs2(int64_t val)
01099 {
01100   return (val%2 == 0 && isImmUs(val/2));
01101 }
01102 
01103 static inline bool isImmUs4(int64_t val)
01104 {
01105   return (val%4 == 0 && isImmUs(val/4));
01106 }
01107 
01108 /// isLegalAddressingMode - Return true if the addressing mode represented
01109 /// by AM is legal for this target, for a load/store of the specified type.
01110 bool
01111 XCoreTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
01112                                               const Type *Ty) const {
01113   // Be conservative with void
01114   // FIXME: Can we be more aggressive?
01115   if (Ty->getTypeID() == Type::VoidTyID)
01116     return false;
01117 
01118   const TargetData *TD = TM.getTargetData();
01119   unsigned Size = TD->getTypeAllocSize(Ty);
01120   if (AM.BaseGV) {
01121     return Size >= 4 && !AM.HasBaseReg && AM.Scale == 0 &&
01122                  AM.BaseOffs%4 == 0;
01123   }
01124   
01125   switch (Size) {
01126   case 1:
01127     // reg + imm
01128     if (AM.Scale == 0) {
01129       return isImmUs(AM.BaseOffs);
01130     }
01131     // reg + reg
01132     return AM.Scale == 1 && AM.BaseOffs == 0;
01133   case 2:
01134   case 3:
01135     // reg + imm
01136     if (AM.Scale == 0) {
01137       return isImmUs2(AM.BaseOffs);
01138     }
01139     // reg + reg<<1
01140     return AM.Scale == 2 && AM.BaseOffs == 0;
01141   default:
01142     // reg + imm
01143     if (AM.Scale == 0) {
01144       return isImmUs4(AM.BaseOffs);
01145     }
01146     // reg + reg<<2
01147     return AM.Scale == 4 && AM.BaseOffs == 0;
01148   }
01149   
01150   return false;
01151 }
01152 
01153 //===----------------------------------------------------------------------===//
01154 //                           XCore Inline Assembly Support
01155 //===----------------------------------------------------------------------===//
01156 
01157 std::vector<unsigned> XCoreTargetLowering::
01158 getRegClassForInlineAsmConstraint(const std::string &Constraint,
01159                                   EVT VT) const 
01160 {
01161   if (Constraint.size() != 1)
01162     return std::vector<unsigned>();
01163 
01164   switch (Constraint[0]) {
01165     default : break;
01166     case 'r':
01167       return make_vector<unsigned>(XCore::R0, XCore::R1,  XCore::R2, 
01168                                    XCore::R3, XCore::R4,  XCore::R5, 
01169                                    XCore::R6, XCore::R7,  XCore::R8, 
01170                                    XCore::R9, XCore::R10, XCore::R11, 0);
01171       break;
01172   }
01173   return std::vector<unsigned>();
01174 }