TweetFollow Us on Twitter

Dec 99 Factory Floor

Volume Number: 15 (1999)
Issue Number: 12
Column Tag: From the Factory Floor

Debugging AltiVec

by by Richard Atwell, ©1999 by Metrowerks, Inc., all rights reserved

Compile and debug your AltiVec code with CodeWarrior

About The Factory Floor

The Factory Floor started as a means for providing a Metrowerks presence in MacTech where you could read about the state of CodeWarrior and get to know the people behind them.

Dave Mark has been writing for the Factory Floor for about as long as I can remember. He's interviewed most of the engineers at Metrowerks and covered pretty much everything we've done since the introduction of the Power Macintosh. Dave's done a remarkable job month after month without taking a vacation so we're going to give him a break from writing for the first time in four years.

This month I'm going to show you what we've done to the debugger in order to support the debugging of AltiVec code but first I'll update you on the progress of the IDE and news about future updates.

Factory Updates

In the last article I explained how our new update strategy works. The next update should have shipped by the time this article appears in print.

Factory Update 5.3 includes updated compilers, an updated version of MSL, and the latest IDE that contains bug fixes in the integrated debugger and incorporates all the changes since the last release. The last time we updated the integrated debugger was when we shipped Pro5 back in July.

The next update that we have planned that will come out after 5.3 will include carbonized versions of MSL from our compiler/library team and a carbonized version of PowerPlant from Greg Dow, both based on the latest sources. The Pro5 reference CD contained pre-release versions of a carbonized MSL and a carbonized version of PowerPlant based on the last Pro4 update, 1.9.3. If you can't wait for the next update, that release is a good place to see what's changed although it's a little out of date with the latest Carbon SDK from Apple.

In addition we'll have a fully Carbonized IDE release that includes compilers and a single machine debugging solution for Mac OS X. You can catch up on the remote debugging news in the August 1999 issue. We've added some new features so you'll not only get a single IDE that runs on Mac OS 7-9 and Mac OS X but one that contains new features as well.

AltiVec Support

If you're not aware of what AltiVec can do be sure to read Tom Thompson's excellent article on AltiVec (MacTech July 1999). Vector technology that leapfrogs current system performance obstacles and it is built into every shipping desktop Power Macintosh.

Aside from several debugger bug fixes, the latest IDE includes complete support for debugging AltiVec code. The Pro5 IDE wasn't well suited for AltiVec debugging because the support was incomplete. AltiVec debugger support was originally added to the IDE 3.3 but because of shipping schedules, the enhancements never completely made it over to the IDE 4.0 in time for Pro5.

We've fixed this in the latest release with updates to both the PowerPC compilers and the integrated debugger. There is also a new version of the MetroNub Plugin that handles AltiVec and an AltiVec enabled MetroNub extension that also provides support for older debuggers I promised in a previous article.

Let take a tour of the new features. I'll assume that you've read Tom Thompson's article and are familiar with the AltiVec basics.

AltiVec Compiler Panel

AltiVec differs from other vector implementations because a high level programming interface is available using C/C++. Take a look at the PPC Processor panel that is available from your project target settings.


Figure 1. PPC Processor Panel.

We've added a new target processor called AltiVec. For now, this is for the only G4 class PowerPC processor option and it affects the scheduler in the compiler if you have "Schedule Instructions" enabled. The actions taken by the compiler when using this setting are based on the functional design of the G4.

You'll probably be re-writing a small portion of your program to take advantage of AltiVec but you'll still want to support the older non-AltiVec processors out there as well.

The "AltiVec Programming Model" option will enable the extensions in the compiler that deal with AltiVec additions to the C/C++ language as well as to changes in the PowerPC ABI.

In order to help you write your code, when this option is on, __VEC__ is pre-defined by the compiler. You can use this to conditionalize your code. For example:

GraphicsEngine()
{
	#if __VEC__
		AltiVecEnhanced_SceneRendering();
	#else
		PPC_SceneRendering();
	#endif
}

Over the years we've modified the compiler to support new C++ features and such and the traditional method for wrapping your code so older compilers won't try to compile code it involved checking the compiler version.

#if (__MWERKS__ >= 0x2300)
	// Use the built-in compiler feature
#else
	// fake it using a workaround
#endif

A good example of this is how bool support in handled is in Apple's CondtionalMacros.h. For AltiVec, the compiler defines __ALTIVEC__ to indicate that it can generate AltiVec code. You probably won't have to use this as often as __VEC__ so just know that it's there if you need it.

The "AltiVec Programming Model" option allows you to enable two other sub-options. The first one, "Generate VRSAVE Instructions" tells the compiler that you want it to take care of informing the OS which vector registers should be saved across context switches. A context switch occurs every-time your application is swapped out for another application. You might want to turn this off if you were writing hand-tooled assembly using our PPCAsm plugin to write your AltiVec code. Since the G4 vector unit has 32 128-bit registers and saving all of them can take numerous CPU cycles. VRSave lets you save specific registers before a context switch preserving the state of the vector unit. Enabling this option lets the compiler do the book keeping for you.

The second option, "Auto Vectorize (Ignored, TBI)", isn't available yet. This option was intended to allow you to vectorize scalar code automatically but we haven't had time to implement this yet.

The last addition for AltiVec is "Store Static Vector Data in TOC" and you have to enable "Store Small Static Data in TOC" to enable this option. If you choose this option your vector data will be placed in the fragment's TOC which has the effect of reducing the number of memory reads to access the data but the trade off is that you loose some precious space in the TOC. Because there's a 64k TOC-limit in the current compiler you'll have to decide whether you can trade off the space for speed.

AltiVec Language Enhancements

The enhancements to the C/C++ language come in the form of the vector keyword. You may recognize vector as the C++ library's (from the former STL) sequential container. The Motorola designers who extended the C/C++ language to handle AltiVec didn't think programmers would be mixing AltiVec code and C++ in the same file so they decided to reuse this identifier as a new keyword in C.

Although this was awkward for our compiler writers to implement you can now mix C, C++, function-level assembly and inline assembly all within the same file using the CodeWarrior compiler.

Vector variables are declared using these new types. All vectors are 128-bits wide and are composed of smaller scalar elements that are opaque in the sense that you can't directly access the elements inside.

vector [ unsigned | signed | bool ] int [*]
vector [ unsigned | signed | bool ] short
vector [ unsigned | signed | bool ] char
vector float
vector pixel

You may have seen code written with vector unsigned long. The int notation is preferred to the long or long int forms that are deprecated in the final programming interface specification from Motorola. Here's a simple vector declaration:

	vector unsigned int x = (vector unsigned int) (1, 2, 3, 4);

Notice that we have to cast the initializer. If you don't do this you will get a syntax error from the compiler. We can also use a shortcut if we want to initialize all the elements to the same value (called a splat):

	vector unsigned int x = (vector unsigned int) (1);

AltiVec code is written using intrinsic functions. These are the C equivalents of the assembly language instructions available in the assembler but take vector variables as parameters and return results in vector variables. Here's how to XOR two vector variables and store the result in one:

	vector unsigned int a = (vector unsigned int) (255);
	vector unsigned int b = (vector unsigned int) (-1, 0, -1, 0);

	a = vec_xor(a, b);

	- result -

	0 255 0 255

AltiVec adds 162 new PowerPC instructions and the compiler supports an intrinsic function for each one so you can do all your programming from C/C++.

In addition to the language changes there are 2 new pragmas supported by the compiler:

	#pragma altivec_model on | off
	#pragma altivec_vrsave on | off | allon

The first one is equivalent to the "AltiVec Programming Model" option in the PPC Processor panel.

The second one allows source code level control of the VRSave code generation that was described earlier. The allon option is like on except all registers are saved instead of the just the ones determined necessary by the compiler.

AltiVec MSL and Runtimes

To compliment the changes in the compiler, we've modified MSL in several ways to support the AltiVec programming model.

printf and scanf both take a new control string option for formatting. The options %vl %vh and %v break up the vector into 4, 8 or 16 elements for printing and scanning. Like the other control strings, you need to postfix these options with a conversion option to display hex or decimal. For example, this code yields the following result:

	vector unsigned int val = (vector unsigned int) (0x2A);

	printf(" hex: 0x%vlX\n dec: %vhd\n", val, val);

	- output -

	hex: 2A 2A 2A 2A
	dec: 0 42 0 42 0 42 0 42

Further additions include vector versions of the C memory allocators: vec_malloc(), vec_calloc(), vec_realloc(), and vec_free(). These routines return a 16-byte aligned address. This is very important for accuracy and maximizing the performance of the vector unit so be sure to use these with vectors variables instead of the normal forms.

There are no special versions of the MSL C.PPC.Lib or MSL C++.PPC.Lib libraries that you are required to use with AltiVec targets but you do have to select the correct runtime library.

The AltiVec programming model places some extra restrictions on the PowerPC ABI. One such restriction involves 16-byte alignment of data in memory. For example, stack frames have to be created and destroyed with this restriction so we've had to provide vector implementations of setjmp() and longjmp(). Changes to our C++ exception handler to support AltiVec were also required.

You'll need the correct version of the runtime routines depending on the AltiVec code generation setting. If you use any of the libraries on the left, be sure to use the AltiVec equivalent in your AltiVec targets.

	MSL MPWCRuntimePPC.Lib	->		MSL MPWCRuntimeAltiVec.Lib
	MSL RuntimePPC++.DLL		->	MSL RuntimeAltiVec++.DLL
	MSL RuntimePPC.DLL			->	MSL RuntimeAltiVec.DLL
	MSL RuntimePPC.Lib			->	MSL RuntimeAltiVec.Lib
	MSL StdCRuntimePPC.Lib		->	MSL StdCRuntimeAltiVec.Lib


Figure 2. Example Project Window.

That briefly summarizes what's changed in the compiler and the libraries. I've only covered the basics here and you can read about all the details in the "AltiVec Technology Programming Interface Manual" from Motorola. Apple's website has a good introduction to AltiVec and they've provided some sample code for your as well.

AltiVec Register Window

Debugging your AltiVec code is just as easy as debugging any other code using CodeWarrior.

Vector variables can be stored in vector registers or they can be stored relative to the stack as local or global variables. You can use the register keyword to ask the compiler to store variables in registers but it's up to the compiler to honor this request just like any other variable.

To make the viewing and manipulation of vector registers possible a new register window was designed and it available from the Window menu. Because vector registers are 128-bits wide the AltiVec Register window was created as a resizable window so screen real estate can be preserved as much as possible and a scrollbar has been included so you can navigate within the window at any window size.

Unlike the General and FPU Register windows, there is a zoom control so you can maximize and minimize the window to examine the contents of all registers with a single click. If the window grows so that part of it will draw off-screen the window positions itself to the borders of the monitor so the entire window is visible. Clicking zoom again will restore the original window position and scroll the window to the last register you were looking at.


Figure 3. AltiVec Register Window.

Because vector variables really just contain multiples of scalar elements each register is broken into 4 32-bit quantities. This is useful for viewing elements as ints, shorts, chars and floats. When a vector register changes value you'll notice that only the scalar element that changed is draw in red instead of the whole register. This helps you notice bugs in your code as you vectorize your existing algorithms comparing them to the original output the generate.

Finally, there is a contextual menu available that you can activate to change the display format from hex to float. When you do this for any scalar element all elements change at once as a convenience for you.

AltiVec Stack Crawl Window

Motorola states that vector variables are opaque structures and access to individual elements inside is forbidden but that's not very useful for debugging purposes.

Displaying vector variables as 16-byte quantities was awkward so we decided to display variables as structs with array like labels. Take a look at the stack crawl window and you'll see vector variables in registers are denoted with a ®VRx label in the right column or an address which indicates that variables are stack-based.


Figure 4. Stack Crawl Window.

Normally variables in registers aren't denoted in the register name but for vector variables we do because they are treated as structs in the debugger and structs can't fit within registers.

When disclosed, vector variables reveal the scalar elements that make up the variables. When the variable changes only the elements that change will hilite in red just as other array or struct elements hilite when changed. You can also edit elements one at a time which is much easier than having to insert text into a 16-byte hex value.

You can convert any of the elements using the Data menu to display the elements of a vectors as hex, signed value or other convertible formats. Because some vector variables have 16 elements inside we've automated the formatting of all elements at once whether they are in registers or on the stack. You can also reformat elements using the contextual menu.

Vector variables can be thought of arrays of scalar elements but if you remember I called them structs earlier. This is an important distinction because you can't use array notation to access vector variables in expressions.

For expressions and conditional breakpoints you need to think of them as structs. Here's an example that will stop at the breakpoint when the first element of result equals 69.


Figure 5. Conditional Breakpoints using an expression.

The [0] is the label of the first element inside the vector variable result. If you find this odd you're probably not alone because this isn't valid C/C++ syntax but at least we have a way to use vector variables in expressions.

Development Tips

Once you learn the instrinsic operators, you can concentrate on vectorizing the bottlenecks in your program instead of dealing with the awkwardness of assembly language. Optimizing AltiVec code is another article by itself, maybe even a book but here are a few tips to consider.

Always look for register spillage. This occurs when there are too many variables and too few registers to store them in. Spilled registers are stored on the stack and it's well known that programs run faster when computation is done enitrely in the registers.

Look for dependencies that reduce the usage of the multiple functional units within the G4 processor. Try to interleave usage of the permute unit with the integer or floating point units. For example:

Permute, multiply, permute, xor, permute, add, etc.

You can easily double your performance using this technique. Lastly, always double-check your alignment. AltiVec register loads and stores must always be 16-byte aligned in memory so if you don't abide by the rules your code won't be correct.

Summary

Being able to write vectorized code in C/C++ and debug it with a source level debugger is a huge improvement over other vector implementations like Intel's MMX, SSE and AMD's 3DNow!.

Because the CodeWarrior compiler has full C/C++ support for the AltiVec programming model you only have to use assembly in you want to. For example, all of Photoshop's AltiVec support was written entirely in C ; no assembly.

This capability makes it a lot easier to integrate and reuse code as well as debug and maintain your programs than if you had to write and debug entirely in assembly.

Good luck with your AltiVec endeavors and come visit our booth at MacWorld SF in January.

References

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.